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, MVT::i64,
5569 LDBase->getPointerInfo(),
5570 LDBase->getAlignment(),
5571 false/*isVolatile*/, true/*ReadMem*/,
5574 // Make sure the newly-created LOAD is in the same position as LDBase in
5575 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5576 // update uses of LDBase's output chain to use the TokenFactor.
5577 if (LDBase->hasAnyUseOfValue(1)) {
5578 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5579 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5580 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5581 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5582 SDValue(ResNode.getNode(), 1));
5585 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5590 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5591 /// to generate a splat value for the following cases:
5592 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5593 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5594 /// a scalar load, or a constant.
5595 /// The VBROADCAST node is returned when a pattern is found,
5596 /// or SDValue() otherwise.
5597 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5598 SelectionDAG &DAG) {
5599 if (!Subtarget->hasFp256())
5602 MVT VT = Op.getSimpleValueType();
5605 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5606 "Unsupported vector type for broadcast.");
5611 switch (Op.getOpcode()) {
5613 // Unknown pattern found.
5616 case ISD::BUILD_VECTOR: {
5617 // The BUILD_VECTOR node must be a splat.
5618 if (!isSplatVector(Op.getNode()))
5621 Ld = Op.getOperand(0);
5622 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5623 Ld.getOpcode() == ISD::ConstantFP);
5625 // The suspected load node has several users. Make sure that all
5626 // of its users are from the BUILD_VECTOR node.
5627 // Constants may have multiple users.
5628 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5633 case ISD::VECTOR_SHUFFLE: {
5634 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5636 // Shuffles must have a splat mask where the first element is
5638 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5641 SDValue Sc = Op.getOperand(0);
5642 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5643 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5645 if (!Subtarget->hasInt256())
5648 // Use the register form of the broadcast instruction available on AVX2.
5649 if (VT.getSizeInBits() >= 256)
5650 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5651 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5654 Ld = Sc.getOperand(0);
5655 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5656 Ld.getOpcode() == ISD::ConstantFP);
5658 // The scalar_to_vector node and the suspected
5659 // load node must have exactly one user.
5660 // Constants may have multiple users.
5662 // AVX-512 has register version of the broadcast
5663 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5664 Ld.getValueType().getSizeInBits() >= 32;
5665 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5672 bool IsGE256 = (VT.getSizeInBits() >= 256);
5674 // Handle the broadcasting a single constant scalar from the constant pool
5675 // into a vector. On Sandybridge it is still better to load a constant vector
5676 // from the constant pool and not to broadcast it from a scalar.
5677 if (ConstSplatVal && Subtarget->hasInt256()) {
5678 EVT CVT = Ld.getValueType();
5679 assert(!CVT.isVector() && "Must not broadcast a vector type");
5680 unsigned ScalarSize = CVT.getSizeInBits();
5682 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5683 const Constant *C = nullptr;
5684 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5685 C = CI->getConstantIntValue();
5686 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5687 C = CF->getConstantFPValue();
5689 assert(C && "Invalid constant type");
5691 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5692 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5693 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5694 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5695 MachinePointerInfo::getConstantPool(),
5696 false, false, false, Alignment);
5698 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5702 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5703 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5705 // Handle AVX2 in-register broadcasts.
5706 if (!IsLoad && Subtarget->hasInt256() &&
5707 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5708 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5710 // The scalar source must be a normal load.
5714 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5715 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5717 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5718 // double since there is no vbroadcastsd xmm
5719 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5720 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5721 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5724 // Unsupported broadcast.
5728 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5729 /// underlying vector and index.
5731 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5733 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5735 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5736 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5739 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5741 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5743 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5744 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5747 // In this case the vector is the extract_subvector expression and the index
5748 // is 2, as specified by the shuffle.
5749 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5750 SDValue ShuffleVec = SVOp->getOperand(0);
5751 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5752 assert(ShuffleVecVT.getVectorElementType() ==
5753 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5755 int ShuffleIdx = SVOp->getMaskElt(Idx);
5756 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5757 ExtractedFromVec = ShuffleVec;
5763 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5764 MVT VT = Op.getSimpleValueType();
5766 // Skip if insert_vec_elt is not supported.
5767 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5768 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5772 unsigned NumElems = Op.getNumOperands();
5776 SmallVector<unsigned, 4> InsertIndices;
5777 SmallVector<int, 8> Mask(NumElems, -1);
5779 for (unsigned i = 0; i != NumElems; ++i) {
5780 unsigned Opc = Op.getOperand(i).getOpcode();
5782 if (Opc == ISD::UNDEF)
5785 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5786 // Quit if more than 1 elements need inserting.
5787 if (InsertIndices.size() > 1)
5790 InsertIndices.push_back(i);
5794 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5795 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5796 // Quit if non-constant index.
5797 if (!isa<ConstantSDNode>(ExtIdx))
5799 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5801 // Quit if extracted from vector of different type.
5802 if (ExtractedFromVec.getValueType() != VT)
5805 if (!VecIn1.getNode())
5806 VecIn1 = ExtractedFromVec;
5807 else if (VecIn1 != ExtractedFromVec) {
5808 if (!VecIn2.getNode())
5809 VecIn2 = ExtractedFromVec;
5810 else if (VecIn2 != ExtractedFromVec)
5811 // Quit if more than 2 vectors to shuffle
5815 if (ExtractedFromVec == VecIn1)
5817 else if (ExtractedFromVec == VecIn2)
5818 Mask[i] = Idx + NumElems;
5821 if (!VecIn1.getNode())
5824 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5825 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5826 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5827 unsigned Idx = InsertIndices[i];
5828 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5829 DAG.getIntPtrConstant(Idx));
5835 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5837 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5839 MVT VT = Op.getSimpleValueType();
5840 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5841 "Unexpected type in LowerBUILD_VECTORvXi1!");
5844 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5845 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5846 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5847 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5850 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5851 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5852 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5853 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5856 bool AllContants = true;
5857 uint64_t Immediate = 0;
5858 int NonConstIdx = -1;
5859 bool IsSplat = true;
5860 unsigned NumNonConsts = 0;
5861 unsigned NumConsts = 0;
5862 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5863 SDValue In = Op.getOperand(idx);
5864 if (In.getOpcode() == ISD::UNDEF)
5866 if (!isa<ConstantSDNode>(In)) {
5867 AllContants = false;
5873 if (cast<ConstantSDNode>(In)->getZExtValue())
5874 Immediate |= (1ULL << idx);
5876 if (In != Op.getOperand(0))
5881 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5882 DAG.getConstant(Immediate, MVT::i16));
5883 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5884 DAG.getIntPtrConstant(0));
5887 if (NumNonConsts == 1 && NonConstIdx != 0) {
5890 SDValue VecAsImm = DAG.getConstant(Immediate,
5891 MVT::getIntegerVT(VT.getSizeInBits()));
5892 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5895 DstVec = DAG.getUNDEF(VT);
5896 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5897 Op.getOperand(NonConstIdx),
5898 DAG.getIntPtrConstant(NonConstIdx));
5900 if (!IsSplat && (NonConstIdx != 0))
5901 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5902 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5905 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5906 DAG.getConstant(-1, SelectVT),
5907 DAG.getConstant(0, SelectVT));
5909 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5910 DAG.getConstant((Immediate | 1), SelectVT),
5911 DAG.getConstant(Immediate, SelectVT));
5912 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5916 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5919 MVT VT = Op.getSimpleValueType();
5920 MVT ExtVT = VT.getVectorElementType();
5921 unsigned NumElems = Op.getNumOperands();
5923 // Generate vectors for predicate vectors.
5924 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5925 return LowerBUILD_VECTORvXi1(Op, DAG);
5927 // Vectors containing all zeros can be matched by pxor and xorps later
5928 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5929 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5930 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5931 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5934 return getZeroVector(VT, Subtarget, DAG, dl);
5937 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5938 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5939 // vpcmpeqd on 256-bit vectors.
5940 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5941 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5944 if (!VT.is512BitVector())
5945 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5948 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5949 if (Broadcast.getNode())
5952 unsigned EVTBits = ExtVT.getSizeInBits();
5954 unsigned NumZero = 0;
5955 unsigned NumNonZero = 0;
5956 unsigned NonZeros = 0;
5957 bool IsAllConstants = true;
5958 SmallSet<SDValue, 8> Values;
5959 for (unsigned i = 0; i < NumElems; ++i) {
5960 SDValue Elt = Op.getOperand(i);
5961 if (Elt.getOpcode() == ISD::UNDEF)
5964 if (Elt.getOpcode() != ISD::Constant &&
5965 Elt.getOpcode() != ISD::ConstantFP)
5966 IsAllConstants = false;
5967 if (X86::isZeroNode(Elt))
5970 NonZeros |= (1 << i);
5975 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5976 if (NumNonZero == 0)
5977 return DAG.getUNDEF(VT);
5979 // Special case for single non-zero, non-undef, element.
5980 if (NumNonZero == 1) {
5981 unsigned Idx = countTrailingZeros(NonZeros);
5982 SDValue Item = Op.getOperand(Idx);
5984 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5985 // the value are obviously zero, truncate the value to i32 and do the
5986 // insertion that way. Only do this if the value is non-constant or if the
5987 // value is a constant being inserted into element 0. It is cheaper to do
5988 // a constant pool load than it is to do a movd + shuffle.
5989 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5990 (!IsAllConstants || Idx == 0)) {
5991 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5993 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5994 EVT VecVT = MVT::v4i32;
5995 unsigned VecElts = 4;
5997 // Truncate the value (which may itself be a constant) to i32, and
5998 // convert it to a vector with movd (S2V+shuffle to zero extend).
5999 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6000 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6001 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6003 // Now we have our 32-bit value zero extended in the low element of
6004 // a vector. If Idx != 0, swizzle it into place.
6006 SmallVector<int, 4> Mask;
6007 Mask.push_back(Idx);
6008 for (unsigned i = 1; i != VecElts; ++i)
6010 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6013 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6017 // If we have a constant or non-constant insertion into the low element of
6018 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6019 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6020 // depending on what the source datatype is.
6023 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6025 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6026 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6027 if (VT.is256BitVector() || VT.is512BitVector()) {
6028 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6029 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6030 Item, DAG.getIntPtrConstant(0));
6032 assert(VT.is128BitVector() && "Expected an SSE value type!");
6033 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6034 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6035 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6038 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6039 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6040 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6041 if (VT.is256BitVector()) {
6042 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6043 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6045 assert(VT.is128BitVector() && "Expected an SSE value type!");
6046 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6048 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6052 // Is it a vector logical left shift?
6053 if (NumElems == 2 && Idx == 1 &&
6054 X86::isZeroNode(Op.getOperand(0)) &&
6055 !X86::isZeroNode(Op.getOperand(1))) {
6056 unsigned NumBits = VT.getSizeInBits();
6057 return getVShift(true, VT,
6058 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6059 VT, Op.getOperand(1)),
6060 NumBits/2, DAG, *this, dl);
6063 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6066 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6067 // is a non-constant being inserted into an element other than the low one,
6068 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6069 // movd/movss) to move this into the low element, then shuffle it into
6071 if (EVTBits == 32) {
6072 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6074 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6075 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6076 SmallVector<int, 8> MaskVec;
6077 for (unsigned i = 0; i != NumElems; ++i)
6078 MaskVec.push_back(i == Idx ? 0 : 1);
6079 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6083 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6084 if (Values.size() == 1) {
6085 if (EVTBits == 32) {
6086 // Instead of a shuffle like this:
6087 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6088 // Check if it's possible to issue this instead.
6089 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6090 unsigned Idx = countTrailingZeros(NonZeros);
6091 SDValue Item = Op.getOperand(Idx);
6092 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6093 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6098 // A vector full of immediates; various special cases are already
6099 // handled, so this is best done with a single constant-pool load.
6103 // For AVX-length vectors, build the individual 128-bit pieces and use
6104 // shuffles to put them in place.
6105 if (VT.is256BitVector() || VT.is512BitVector()) {
6106 SmallVector<SDValue, 64> V;
6107 for (unsigned i = 0; i != NumElems; ++i)
6108 V.push_back(Op.getOperand(i));
6110 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6112 // Build both the lower and upper subvector.
6113 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6114 ArrayRef<SDValue>(&V[0], NumElems/2));
6115 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6116 ArrayRef<SDValue>(&V[NumElems / 2],
6119 // Recreate the wider vector with the lower and upper part.
6120 if (VT.is256BitVector())
6121 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6122 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6125 // Let legalizer expand 2-wide build_vectors.
6126 if (EVTBits == 64) {
6127 if (NumNonZero == 1) {
6128 // One half is zero or undef.
6129 unsigned Idx = countTrailingZeros(NonZeros);
6130 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6131 Op.getOperand(Idx));
6132 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6137 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6138 if (EVTBits == 8 && NumElems == 16) {
6139 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6141 if (V.getNode()) return V;
6144 if (EVTBits == 16 && NumElems == 8) {
6145 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6147 if (V.getNode()) return V;
6150 // If element VT is == 32 bits, turn it into a number of shuffles.
6151 SmallVector<SDValue, 8> V(NumElems);
6152 if (NumElems == 4 && NumZero > 0) {
6153 for (unsigned i = 0; i < 4; ++i) {
6154 bool isZero = !(NonZeros & (1 << i));
6156 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6158 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6161 for (unsigned i = 0; i < 2; ++i) {
6162 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6165 V[i] = V[i*2]; // Must be a zero vector.
6168 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6171 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6174 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6179 bool Reverse1 = (NonZeros & 0x3) == 2;
6180 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6184 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6185 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6187 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6190 if (Values.size() > 1 && VT.is128BitVector()) {
6191 // Check for a build vector of consecutive loads.
6192 for (unsigned i = 0; i < NumElems; ++i)
6193 V[i] = Op.getOperand(i);
6195 // Check for elements which are consecutive loads.
6196 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6200 // Check for a build vector from mostly shuffle plus few inserting.
6201 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6205 // For SSE 4.1, use insertps to put the high elements into the low element.
6206 if (getSubtarget()->hasSSE41()) {
6208 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6209 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6211 Result = DAG.getUNDEF(VT);
6213 for (unsigned i = 1; i < NumElems; ++i) {
6214 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6215 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6216 Op.getOperand(i), DAG.getIntPtrConstant(i));
6221 // Otherwise, expand into a number of unpckl*, start by extending each of
6222 // our (non-undef) elements to the full vector width with the element in the
6223 // bottom slot of the vector (which generates no code for SSE).
6224 for (unsigned i = 0; i < NumElems; ++i) {
6225 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6226 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6228 V[i] = DAG.getUNDEF(VT);
6231 // Next, we iteratively mix elements, e.g. for v4f32:
6232 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6233 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6234 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6235 unsigned EltStride = NumElems >> 1;
6236 while (EltStride != 0) {
6237 for (unsigned i = 0; i < EltStride; ++i) {
6238 // If V[i+EltStride] is undef and this is the first round of mixing,
6239 // then it is safe to just drop this shuffle: V[i] is already in the
6240 // right place, the one element (since it's the first round) being
6241 // inserted as undef can be dropped. This isn't safe for successive
6242 // rounds because they will permute elements within both vectors.
6243 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6244 EltStride == NumElems/2)
6247 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6256 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6257 // to create 256-bit vectors from two other 128-bit ones.
6258 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6260 MVT ResVT = Op.getSimpleValueType();
6262 assert((ResVT.is256BitVector() ||
6263 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6265 SDValue V1 = Op.getOperand(0);
6266 SDValue V2 = Op.getOperand(1);
6267 unsigned NumElems = ResVT.getVectorNumElements();
6268 if(ResVT.is256BitVector())
6269 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6271 if (Op.getNumOperands() == 4) {
6272 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6273 ResVT.getVectorNumElements()/2);
6274 SDValue V3 = Op.getOperand(2);
6275 SDValue V4 = Op.getOperand(3);
6276 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6277 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6279 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6282 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6283 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6284 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6285 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6286 Op.getNumOperands() == 4)));
6288 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6289 // from two other 128-bit ones.
6291 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6292 return LowerAVXCONCAT_VECTORS(Op, DAG);
6295 // Try to lower a shuffle node into a simple blend instruction.
6297 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6298 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6299 SDValue V1 = SVOp->getOperand(0);
6300 SDValue V2 = SVOp->getOperand(1);
6302 MVT VT = SVOp->getSimpleValueType(0);
6303 MVT EltVT = VT.getVectorElementType();
6304 unsigned NumElems = VT.getVectorNumElements();
6306 // There is no blend with immediate in AVX-512.
6307 if (VT.is512BitVector())
6310 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6312 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6315 // Check the mask for BLEND and build the value.
6316 unsigned MaskValue = 0;
6317 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6318 unsigned NumLanes = (NumElems-1)/8 + 1;
6319 unsigned NumElemsInLane = NumElems / NumLanes;
6321 // Blend for v16i16 should be symetric for the both lanes.
6322 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6324 int SndLaneEltIdx = (NumLanes == 2) ?
6325 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6326 int EltIdx = SVOp->getMaskElt(i);
6328 if ((EltIdx < 0 || EltIdx == (int)i) &&
6329 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6332 if (((unsigned)EltIdx == (i + NumElems)) &&
6333 (SndLaneEltIdx < 0 ||
6334 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6335 MaskValue |= (1<<i);
6340 // Convert i32 vectors to floating point if it is not AVX2.
6341 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6343 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6344 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6346 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6347 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6350 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6351 DAG.getConstant(MaskValue, MVT::i32));
6352 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6355 /// In vector type \p VT, return true if the element at index \p InputIdx
6356 /// falls on a different 128-bit lane than \p OutputIdx.
6357 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6358 unsigned OutputIdx) {
6359 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6360 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6363 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6364 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6365 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6366 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6368 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6369 SelectionDAG &DAG) {
6370 MVT VT = V1.getSimpleValueType();
6371 assert(VT.is128BitVector() || VT.is256BitVector());
6373 MVT EltVT = VT.getVectorElementType();
6374 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6375 unsigned NumElts = VT.getVectorNumElements();
6377 SmallVector<SDValue, 32> PshufbMask;
6378 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6379 int InputIdx = MaskVals[OutputIdx];
6380 unsigned InputByteIdx;
6382 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6383 InputByteIdx = 0x80;
6385 // Cross lane is not allowed.
6386 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6388 InputByteIdx = InputIdx * EltSizeInBytes;
6389 // Index is an byte offset within the 128-bit lane.
6390 InputByteIdx &= 0xf;
6393 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6394 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6395 if (InputByteIdx != 0x80)
6400 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6402 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6403 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6404 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6407 // v8i16 shuffles - Prefer shuffles in the following order:
6408 // 1. [all] pshuflw, pshufhw, optional move
6409 // 2. [ssse3] 1 x pshufb
6410 // 3. [ssse3] 2 x pshufb + 1 x por
6411 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6413 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6414 SelectionDAG &DAG) {
6415 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6416 SDValue V1 = SVOp->getOperand(0);
6417 SDValue V2 = SVOp->getOperand(1);
6419 SmallVector<int, 8> MaskVals;
6421 // Determine if more than 1 of the words in each of the low and high quadwords
6422 // of the result come from the same quadword of one of the two inputs. Undef
6423 // mask values count as coming from any quadword, for better codegen.
6425 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6426 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6427 unsigned LoQuad[] = { 0, 0, 0, 0 };
6428 unsigned HiQuad[] = { 0, 0, 0, 0 };
6429 // Indices of quads used.
6430 std::bitset<4> InputQuads;
6431 for (unsigned i = 0; i < 8; ++i) {
6432 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6433 int EltIdx = SVOp->getMaskElt(i);
6434 MaskVals.push_back(EltIdx);
6443 InputQuads.set(EltIdx / 4);
6446 int BestLoQuad = -1;
6447 unsigned MaxQuad = 1;
6448 for (unsigned i = 0; i < 4; ++i) {
6449 if (LoQuad[i] > MaxQuad) {
6451 MaxQuad = LoQuad[i];
6455 int BestHiQuad = -1;
6457 for (unsigned i = 0; i < 4; ++i) {
6458 if (HiQuad[i] > MaxQuad) {
6460 MaxQuad = HiQuad[i];
6464 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6465 // of the two input vectors, shuffle them into one input vector so only a
6466 // single pshufb instruction is necessary. If there are more than 2 input
6467 // quads, disable the next transformation since it does not help SSSE3.
6468 bool V1Used = InputQuads[0] || InputQuads[1];
6469 bool V2Used = InputQuads[2] || InputQuads[3];
6470 if (Subtarget->hasSSSE3()) {
6471 if (InputQuads.count() == 2 && V1Used && V2Used) {
6472 BestLoQuad = InputQuads[0] ? 0 : 1;
6473 BestHiQuad = InputQuads[2] ? 2 : 3;
6475 if (InputQuads.count() > 2) {
6481 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6482 // the shuffle mask. If a quad is scored as -1, that means that it contains
6483 // words from all 4 input quadwords.
6485 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6487 BestLoQuad < 0 ? 0 : BestLoQuad,
6488 BestHiQuad < 0 ? 1 : BestHiQuad
6490 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6491 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6492 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6493 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6495 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6496 // source words for the shuffle, to aid later transformations.
6497 bool AllWordsInNewV = true;
6498 bool InOrder[2] = { true, true };
6499 for (unsigned i = 0; i != 8; ++i) {
6500 int idx = MaskVals[i];
6502 InOrder[i/4] = false;
6503 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6505 AllWordsInNewV = false;
6509 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6510 if (AllWordsInNewV) {
6511 for (int i = 0; i != 8; ++i) {
6512 int idx = MaskVals[i];
6515 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6516 if ((idx != i) && idx < 4)
6518 if ((idx != i) && idx > 3)
6527 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6528 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6529 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6530 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6531 unsigned TargetMask = 0;
6532 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6533 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6534 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6535 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6536 getShufflePSHUFLWImmediate(SVOp);
6537 V1 = NewV.getOperand(0);
6538 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6542 // Promote splats to a larger type which usually leads to more efficient code.
6543 // FIXME: Is this true if pshufb is available?
6544 if (SVOp->isSplat())
6545 return PromoteSplat(SVOp, DAG);
6547 // If we have SSSE3, and all words of the result are from 1 input vector,
6548 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6549 // is present, fall back to case 4.
6550 if (Subtarget->hasSSSE3()) {
6551 SmallVector<SDValue,16> pshufbMask;
6553 // If we have elements from both input vectors, set the high bit of the
6554 // shuffle mask element to zero out elements that come from V2 in the V1
6555 // mask, and elements that come from V1 in the V2 mask, so that the two
6556 // results can be OR'd together.
6557 bool TwoInputs = V1Used && V2Used;
6558 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6560 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6562 // Calculate the shuffle mask for the second input, shuffle it, and
6563 // OR it with the first shuffled input.
6564 CommuteVectorShuffleMask(MaskVals, 8);
6565 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6566 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6567 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6570 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6571 // and update MaskVals with new element order.
6572 std::bitset<8> InOrder;
6573 if (BestLoQuad >= 0) {
6574 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6575 for (int i = 0; i != 4; ++i) {
6576 int idx = MaskVals[i];
6579 } else if ((idx / 4) == BestLoQuad) {
6584 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6587 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6588 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6589 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6591 getShufflePSHUFLWImmediate(SVOp), DAG);
6595 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6596 // and update MaskVals with the new element order.
6597 if (BestHiQuad >= 0) {
6598 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6599 for (unsigned i = 4; i != 8; ++i) {
6600 int idx = MaskVals[i];
6603 } else if ((idx / 4) == BestHiQuad) {
6604 MaskV[i] = (idx & 3) + 4;
6608 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6611 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6612 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6613 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6615 getShufflePSHUFHWImmediate(SVOp), DAG);
6619 // In case BestHi & BestLo were both -1, which means each quadword has a word
6620 // from each of the four input quadwords, calculate the InOrder bitvector now
6621 // before falling through to the insert/extract cleanup.
6622 if (BestLoQuad == -1 && BestHiQuad == -1) {
6624 for (int i = 0; i != 8; ++i)
6625 if (MaskVals[i] < 0 || MaskVals[i] == i)
6629 // The other elements are put in the right place using pextrw and pinsrw.
6630 for (unsigned i = 0; i != 8; ++i) {
6633 int EltIdx = MaskVals[i];
6636 SDValue ExtOp = (EltIdx < 8) ?
6637 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6638 DAG.getIntPtrConstant(EltIdx)) :
6639 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6640 DAG.getIntPtrConstant(EltIdx - 8));
6641 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6642 DAG.getIntPtrConstant(i));
6647 /// \brief v16i16 shuffles
6649 /// FIXME: We only support generation of a single pshufb currently. We can
6650 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6651 /// well (e.g 2 x pshufb + 1 x por).
6653 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6654 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6655 SDValue V1 = SVOp->getOperand(0);
6656 SDValue V2 = SVOp->getOperand(1);
6659 if (V2.getOpcode() != ISD::UNDEF)
6662 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6663 return getPSHUFB(MaskVals, V1, dl, DAG);
6666 // v16i8 shuffles - Prefer shuffles in the following order:
6667 // 1. [ssse3] 1 x pshufb
6668 // 2. [ssse3] 2 x pshufb + 1 x por
6669 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6670 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6671 const X86Subtarget* Subtarget,
6672 SelectionDAG &DAG) {
6673 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6674 SDValue V1 = SVOp->getOperand(0);
6675 SDValue V2 = SVOp->getOperand(1);
6677 ArrayRef<int> MaskVals = SVOp->getMask();
6679 // Promote splats to a larger type which usually leads to more efficient code.
6680 // FIXME: Is this true if pshufb is available?
6681 if (SVOp->isSplat())
6682 return PromoteSplat(SVOp, DAG);
6684 // If we have SSSE3, case 1 is generated when all result bytes come from
6685 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6686 // present, fall back to case 3.
6688 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6689 if (Subtarget->hasSSSE3()) {
6690 SmallVector<SDValue,16> pshufbMask;
6692 // If all result elements are from one input vector, then only translate
6693 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6695 // Otherwise, we have elements from both input vectors, and must zero out
6696 // elements that come from V2 in the first mask, and V1 in the second mask
6697 // so that we can OR them together.
6698 for (unsigned i = 0; i != 16; ++i) {
6699 int EltIdx = MaskVals[i];
6700 if (EltIdx < 0 || EltIdx >= 16)
6702 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6704 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6705 DAG.getNode(ISD::BUILD_VECTOR, dl,
6706 MVT::v16i8, pshufbMask));
6708 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6709 // the 2nd operand if it's undefined or zero.
6710 if (V2.getOpcode() == ISD::UNDEF ||
6711 ISD::isBuildVectorAllZeros(V2.getNode()))
6714 // Calculate the shuffle mask for the second input, shuffle it, and
6715 // OR it with the first shuffled input.
6717 for (unsigned i = 0; i != 16; ++i) {
6718 int EltIdx = MaskVals[i];
6719 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6720 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6722 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6723 DAG.getNode(ISD::BUILD_VECTOR, dl,
6724 MVT::v16i8, pshufbMask));
6725 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6728 // No SSSE3 - Calculate in place words and then fix all out of place words
6729 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6730 // the 16 different words that comprise the two doublequadword input vectors.
6731 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6732 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6734 for (int i = 0; i != 8; ++i) {
6735 int Elt0 = MaskVals[i*2];
6736 int Elt1 = MaskVals[i*2+1];
6738 // This word of the result is all undef, skip it.
6739 if (Elt0 < 0 && Elt1 < 0)
6742 // This word of the result is already in the correct place, skip it.
6743 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6746 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6747 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6750 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6751 // using a single extract together, load it and store it.
6752 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6753 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6754 DAG.getIntPtrConstant(Elt1 / 2));
6755 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6756 DAG.getIntPtrConstant(i));
6760 // If Elt1 is defined, extract it from the appropriate source. If the
6761 // source byte is not also odd, shift the extracted word left 8 bits
6762 // otherwise clear the bottom 8 bits if we need to do an or.
6764 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6765 DAG.getIntPtrConstant(Elt1 / 2));
6766 if ((Elt1 & 1) == 0)
6767 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6769 TLI.getShiftAmountTy(InsElt.getValueType())));
6771 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6772 DAG.getConstant(0xFF00, MVT::i16));
6774 // If Elt0 is defined, extract it from the appropriate source. If the
6775 // source byte is not also even, shift the extracted word right 8 bits. If
6776 // Elt1 was also defined, OR the extracted values together before
6777 // inserting them in the result.
6779 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6780 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6781 if ((Elt0 & 1) != 0)
6782 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6784 TLI.getShiftAmountTy(InsElt0.getValueType())));
6786 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6787 DAG.getConstant(0x00FF, MVT::i16));
6788 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6791 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6792 DAG.getIntPtrConstant(i));
6794 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6797 // v32i8 shuffles - Translate to VPSHUFB if possible.
6799 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6800 const X86Subtarget *Subtarget,
6801 SelectionDAG &DAG) {
6802 MVT VT = SVOp->getSimpleValueType(0);
6803 SDValue V1 = SVOp->getOperand(0);
6804 SDValue V2 = SVOp->getOperand(1);
6806 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6808 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6809 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6810 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6812 // VPSHUFB may be generated if
6813 // (1) one of input vector is undefined or zeroinitializer.
6814 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6815 // And (2) the mask indexes don't cross the 128-bit lane.
6816 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6817 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6820 if (V1IsAllZero && !V2IsAllZero) {
6821 CommuteVectorShuffleMask(MaskVals, 32);
6824 return getPSHUFB(MaskVals, V1, dl, DAG);
6827 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6828 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6829 /// done when every pair / quad of shuffle mask elements point to elements in
6830 /// the right sequence. e.g.
6831 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6833 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6834 SelectionDAG &DAG) {
6835 MVT VT = SVOp->getSimpleValueType(0);
6837 unsigned NumElems = VT.getVectorNumElements();
6840 switch (VT.SimpleTy) {
6841 default: llvm_unreachable("Unexpected!");
6842 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6843 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6844 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6845 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6846 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6847 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6850 SmallVector<int, 8> MaskVec;
6851 for (unsigned i = 0; i != NumElems; i += Scale) {
6853 for (unsigned j = 0; j != Scale; ++j) {
6854 int EltIdx = SVOp->getMaskElt(i+j);
6858 StartIdx = (EltIdx / Scale);
6859 if (EltIdx != (int)(StartIdx*Scale + j))
6862 MaskVec.push_back(StartIdx);
6865 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6866 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6867 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6870 /// getVZextMovL - Return a zero-extending vector move low node.
6872 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6873 SDValue SrcOp, SelectionDAG &DAG,
6874 const X86Subtarget *Subtarget, SDLoc dl) {
6875 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6876 LoadSDNode *LD = nullptr;
6877 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6878 LD = dyn_cast<LoadSDNode>(SrcOp);
6880 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6882 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6883 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6884 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6885 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6886 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6888 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6889 return DAG.getNode(ISD::BITCAST, dl, VT,
6890 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6891 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6899 return DAG.getNode(ISD::BITCAST, dl, VT,
6900 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6901 DAG.getNode(ISD::BITCAST, dl,
6905 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6906 /// which could not be matched by any known target speficic shuffle
6908 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6910 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6911 if (NewOp.getNode())
6914 MVT VT = SVOp->getSimpleValueType(0);
6916 unsigned NumElems = VT.getVectorNumElements();
6917 unsigned NumLaneElems = NumElems / 2;
6920 MVT EltVT = VT.getVectorElementType();
6921 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6924 SmallVector<int, 16> Mask;
6925 for (unsigned l = 0; l < 2; ++l) {
6926 // Build a shuffle mask for the output, discovering on the fly which
6927 // input vectors to use as shuffle operands (recorded in InputUsed).
6928 // If building a suitable shuffle vector proves too hard, then bail
6929 // out with UseBuildVector set.
6930 bool UseBuildVector = false;
6931 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6932 unsigned LaneStart = l * NumLaneElems;
6933 for (unsigned i = 0; i != NumLaneElems; ++i) {
6934 // The mask element. This indexes into the input.
6935 int Idx = SVOp->getMaskElt(i+LaneStart);
6937 // the mask element does not index into any input vector.
6942 // The input vector this mask element indexes into.
6943 int Input = Idx / NumLaneElems;
6945 // Turn the index into an offset from the start of the input vector.
6946 Idx -= Input * NumLaneElems;
6948 // Find or create a shuffle vector operand to hold this input.
6950 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6951 if (InputUsed[OpNo] == Input)
6952 // This input vector is already an operand.
6954 if (InputUsed[OpNo] < 0) {
6955 // Create a new operand for this input vector.
6956 InputUsed[OpNo] = Input;
6961 if (OpNo >= array_lengthof(InputUsed)) {
6962 // More than two input vectors used! Give up on trying to create a
6963 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6964 UseBuildVector = true;
6968 // Add the mask index for the new shuffle vector.
6969 Mask.push_back(Idx + OpNo * NumLaneElems);
6972 if (UseBuildVector) {
6973 SmallVector<SDValue, 16> SVOps;
6974 for (unsigned i = 0; i != NumLaneElems; ++i) {
6975 // The mask element. This indexes into the input.
6976 int Idx = SVOp->getMaskElt(i+LaneStart);
6978 SVOps.push_back(DAG.getUNDEF(EltVT));
6982 // The input vector this mask element indexes into.
6983 int Input = Idx / NumElems;
6985 // Turn the index into an offset from the start of the input vector.
6986 Idx -= Input * NumElems;
6988 // Extract the vector element by hand.
6989 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6990 SVOp->getOperand(Input),
6991 DAG.getIntPtrConstant(Idx)));
6994 // Construct the output using a BUILD_VECTOR.
6995 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
6996 } else if (InputUsed[0] < 0) {
6997 // No input vectors were used! The result is undefined.
6998 Output[l] = DAG.getUNDEF(NVT);
7000 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7001 (InputUsed[0] % 2) * NumLaneElems,
7003 // If only one input was used, use an undefined vector for the other.
7004 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7005 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7006 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7007 // At least one input vector was used. Create a new shuffle vector.
7008 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7014 // Concatenate the result back
7015 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7018 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7019 /// 4 elements, and match them with several different shuffle types.
7021 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7022 SDValue V1 = SVOp->getOperand(0);
7023 SDValue V2 = SVOp->getOperand(1);
7025 MVT VT = SVOp->getSimpleValueType(0);
7027 assert(VT.is128BitVector() && "Unsupported vector size");
7029 std::pair<int, int> Locs[4];
7030 int Mask1[] = { -1, -1, -1, -1 };
7031 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7035 for (unsigned i = 0; i != 4; ++i) {
7036 int Idx = PermMask[i];
7038 Locs[i] = std::make_pair(-1, -1);
7040 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7042 Locs[i] = std::make_pair(0, NumLo);
7046 Locs[i] = std::make_pair(1, NumHi);
7048 Mask1[2+NumHi] = Idx;
7054 if (NumLo <= 2 && NumHi <= 2) {
7055 // If no more than two elements come from either vector. This can be
7056 // implemented with two shuffles. First shuffle gather the elements.
7057 // The second shuffle, which takes the first shuffle as both of its
7058 // vector operands, put the elements into the right order.
7059 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7061 int Mask2[] = { -1, -1, -1, -1 };
7063 for (unsigned i = 0; i != 4; ++i)
7064 if (Locs[i].first != -1) {
7065 unsigned Idx = (i < 2) ? 0 : 4;
7066 Idx += Locs[i].first * 2 + Locs[i].second;
7070 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7073 if (NumLo == 3 || NumHi == 3) {
7074 // Otherwise, we must have three elements from one vector, call it X, and
7075 // one element from the other, call it Y. First, use a shufps to build an
7076 // intermediate vector with the one element from Y and the element from X
7077 // that will be in the same half in the final destination (the indexes don't
7078 // matter). Then, use a shufps to build the final vector, taking the half
7079 // containing the element from Y from the intermediate, and the other half
7082 // Normalize it so the 3 elements come from V1.
7083 CommuteVectorShuffleMask(PermMask, 4);
7087 // Find the element from V2.
7089 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7090 int Val = PermMask[HiIndex];
7097 Mask1[0] = PermMask[HiIndex];
7099 Mask1[2] = PermMask[HiIndex^1];
7101 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7104 Mask1[0] = PermMask[0];
7105 Mask1[1] = PermMask[1];
7106 Mask1[2] = HiIndex & 1 ? 6 : 4;
7107 Mask1[3] = HiIndex & 1 ? 4 : 6;
7108 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7111 Mask1[0] = HiIndex & 1 ? 2 : 0;
7112 Mask1[1] = HiIndex & 1 ? 0 : 2;
7113 Mask1[2] = PermMask[2];
7114 Mask1[3] = PermMask[3];
7119 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7122 // Break it into (shuffle shuffle_hi, shuffle_lo).
7123 int LoMask[] = { -1, -1, -1, -1 };
7124 int HiMask[] = { -1, -1, -1, -1 };
7126 int *MaskPtr = LoMask;
7127 unsigned MaskIdx = 0;
7130 for (unsigned i = 0; i != 4; ++i) {
7137 int Idx = PermMask[i];
7139 Locs[i] = std::make_pair(-1, -1);
7140 } else if (Idx < 4) {
7141 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7142 MaskPtr[LoIdx] = Idx;
7145 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7146 MaskPtr[HiIdx] = Idx;
7151 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7152 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7153 int MaskOps[] = { -1, -1, -1, -1 };
7154 for (unsigned i = 0; i != 4; ++i)
7155 if (Locs[i].first != -1)
7156 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7157 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7160 static bool MayFoldVectorLoad(SDValue V) {
7161 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7162 V = V.getOperand(0);
7164 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7165 V = V.getOperand(0);
7166 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7167 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7168 // BUILD_VECTOR (load), undef
7169 V = V.getOperand(0);
7171 return MayFoldLoad(V);
7175 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7176 MVT VT = Op.getSimpleValueType();
7178 // Canonizalize to v2f64.
7179 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7180 return DAG.getNode(ISD::BITCAST, dl, VT,
7181 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7186 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7188 SDValue V1 = Op.getOperand(0);
7189 SDValue V2 = Op.getOperand(1);
7190 MVT VT = Op.getSimpleValueType();
7192 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7194 if (HasSSE2 && VT == MVT::v2f64)
7195 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7197 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7198 return DAG.getNode(ISD::BITCAST, dl, VT,
7199 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7200 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7201 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7205 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7206 SDValue V1 = Op.getOperand(0);
7207 SDValue V2 = Op.getOperand(1);
7208 MVT VT = Op.getSimpleValueType();
7210 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7211 "unsupported shuffle type");
7213 if (V2.getOpcode() == ISD::UNDEF)
7217 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7221 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7222 SDValue V1 = Op.getOperand(0);
7223 SDValue V2 = Op.getOperand(1);
7224 MVT VT = Op.getSimpleValueType();
7225 unsigned NumElems = VT.getVectorNumElements();
7227 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7228 // operand of these instructions is only memory, so check if there's a
7229 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7231 bool CanFoldLoad = false;
7233 // Trivial case, when V2 comes from a load.
7234 if (MayFoldVectorLoad(V2))
7237 // When V1 is a load, it can be folded later into a store in isel, example:
7238 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7240 // (MOVLPSmr addr:$src1, VR128:$src2)
7241 // So, recognize this potential and also use MOVLPS or MOVLPD
7242 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7245 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7247 if (HasSSE2 && NumElems == 2)
7248 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7251 // If we don't care about the second element, proceed to use movss.
7252 if (SVOp->getMaskElt(1) != -1)
7253 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7256 // movl and movlp will both match v2i64, but v2i64 is never matched by
7257 // movl earlier because we make it strict to avoid messing with the movlp load
7258 // folding logic (see the code above getMOVLP call). Match it here then,
7259 // this is horrible, but will stay like this until we move all shuffle
7260 // matching to x86 specific nodes. Note that for the 1st condition all
7261 // types are matched with movsd.
7263 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7264 // as to remove this logic from here, as much as possible
7265 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7266 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7267 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7270 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7272 // Invert the operand order and use SHUFPS to match it.
7273 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7274 getShuffleSHUFImmediate(SVOp), DAG);
7277 // It is only safe to call this function if isINSERTPSMask is true for
7278 // this shufflevector mask.
7279 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7280 SelectionDAG &DAG) {
7281 // Generate an insertps instruction when inserting an f32 from memory onto a
7282 // v4f32 or when copying a member from one v4f32 to another.
7283 // We also use it for transferring i32 from one register to another,
7284 // since it simply copies the same bits.
7285 // If we're transfering an i32 from memory to a specific element in a
7286 // register, we output a generic DAG that will match the PINSRD
7288 // TODO: Optimize for AVX cases too (VINSERTPS)
7289 MVT VT = SVOp->getSimpleValueType(0);
7290 MVT EVT = VT.getVectorElementType();
7291 SDValue V1 = SVOp->getOperand(0);
7292 SDValue V2 = SVOp->getOperand(1);
7293 auto Mask = SVOp->getMask();
7294 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7295 "unsupported vector type for insertps/pinsrd");
7297 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7298 [](const int &i) { return i < 4; });
7306 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7307 [](const int &i) { return i < 4; }) -
7312 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7313 [](const int &i) { return i >= 4; }) -
7317 if (MayFoldLoad(From)) {
7318 // Trivial case, when From comes from a load and is only used by the
7319 // shuffle. Make it use insertps from the vector that we need from that
7321 SDValue Addr = From.getOperand(1);
7323 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7324 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7325 Addr.getSimpleValueType()));
7327 LoadSDNode *Load = cast<LoadSDNode>(From);
7329 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7330 DAG.getMachineFunction().getMachineMemOperand(
7331 Load->getMemOperand(), 0, EVT.getStoreSize()));
7333 if (EVT == MVT::f32) {
7334 // Create this as a scalar to vector to match the instruction pattern.
7335 SDValue LoadScalarToVector =
7336 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7337 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7338 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7340 } else { // EVT == MVT::i32
7341 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7342 // instruction, to match the PINSRD instruction, which loads an i32 to a
7343 // certain vector element.
7344 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7345 DAG.getConstant(DestIndex, MVT::i32));
7349 // Vector-element-to-vector
7350 unsigned SrcIndex = Mask[DestIndex] % 4;
7351 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7352 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7355 // Reduce a vector shuffle to zext.
7356 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7357 SelectionDAG &DAG) {
7358 // PMOVZX is only available from SSE41.
7359 if (!Subtarget->hasSSE41())
7362 MVT VT = Op.getSimpleValueType();
7364 // Only AVX2 support 256-bit vector integer extending.
7365 if (!Subtarget->hasInt256() && VT.is256BitVector())
7368 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7370 SDValue V1 = Op.getOperand(0);
7371 SDValue V2 = Op.getOperand(1);
7372 unsigned NumElems = VT.getVectorNumElements();
7374 // Extending is an unary operation and the element type of the source vector
7375 // won't be equal to or larger than i64.
7376 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7377 VT.getVectorElementType() == MVT::i64)
7380 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7381 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7382 while ((1U << Shift) < NumElems) {
7383 if (SVOp->getMaskElt(1U << Shift) == 1)
7386 // The maximal ratio is 8, i.e. from i8 to i64.
7391 // Check the shuffle mask.
7392 unsigned Mask = (1U << Shift) - 1;
7393 for (unsigned i = 0; i != NumElems; ++i) {
7394 int EltIdx = SVOp->getMaskElt(i);
7395 if ((i & Mask) != 0 && EltIdx != -1)
7397 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7401 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7402 MVT NeVT = MVT::getIntegerVT(NBits);
7403 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7405 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7408 // Simplify the operand as it's prepared to be fed into shuffle.
7409 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7410 if (V1.getOpcode() == ISD::BITCAST &&
7411 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7412 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7413 V1.getOperand(0).getOperand(0)
7414 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7415 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7416 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7417 ConstantSDNode *CIdx =
7418 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7419 // If it's foldable, i.e. normal load with single use, we will let code
7420 // selection to fold it. Otherwise, we will short the conversion sequence.
7421 if (CIdx && CIdx->getZExtValue() == 0 &&
7422 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7423 MVT FullVT = V.getSimpleValueType();
7424 MVT V1VT = V1.getSimpleValueType();
7425 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7426 // The "ext_vec_elt" node is wider than the result node.
7427 // In this case we should extract subvector from V.
7428 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7429 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7430 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7431 FullVT.getVectorNumElements()/Ratio);
7432 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7433 DAG.getIntPtrConstant(0));
7435 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7439 return DAG.getNode(ISD::BITCAST, DL, VT,
7440 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7444 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7445 SelectionDAG &DAG) {
7446 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7447 MVT VT = Op.getSimpleValueType();
7449 SDValue V1 = Op.getOperand(0);
7450 SDValue V2 = Op.getOperand(1);
7452 if (isZeroShuffle(SVOp))
7453 return getZeroVector(VT, Subtarget, DAG, dl);
7455 // Handle splat operations
7456 if (SVOp->isSplat()) {
7457 // Use vbroadcast whenever the splat comes from a foldable load
7458 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7459 if (Broadcast.getNode())
7463 // Check integer expanding shuffles.
7464 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7465 if (NewOp.getNode())
7468 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7470 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7471 VT == MVT::v16i16 || VT == MVT::v32i8) {
7472 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7473 if (NewOp.getNode())
7474 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7475 } else if ((VT == MVT::v4i32 ||
7476 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7477 // FIXME: Figure out a cleaner way to do this.
7478 // Try to make use of movq to zero out the top part.
7479 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7480 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7481 if (NewOp.getNode()) {
7482 MVT NewVT = NewOp.getSimpleValueType();
7483 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7484 NewVT, true, false))
7485 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7486 DAG, Subtarget, dl);
7488 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7489 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7490 if (NewOp.getNode()) {
7491 MVT NewVT = NewOp.getSimpleValueType();
7492 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7493 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7494 DAG, Subtarget, dl);
7502 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7503 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7504 SDValue V1 = Op.getOperand(0);
7505 SDValue V2 = Op.getOperand(1);
7506 MVT VT = Op.getSimpleValueType();
7508 unsigned NumElems = VT.getVectorNumElements();
7509 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7510 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7511 bool V1IsSplat = false;
7512 bool V2IsSplat = false;
7513 bool HasSSE2 = Subtarget->hasSSE2();
7514 bool HasFp256 = Subtarget->hasFp256();
7515 bool HasInt256 = Subtarget->hasInt256();
7516 MachineFunction &MF = DAG.getMachineFunction();
7517 bool OptForSize = MF.getFunction()->getAttributes().
7518 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7520 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7522 if (V1IsUndef && V2IsUndef)
7523 return DAG.getUNDEF(VT);
7525 // When we create a shuffle node we put the UNDEF node to second operand,
7526 // but in some cases the first operand may be transformed to UNDEF.
7527 // In this case we should just commute the node.
7529 return CommuteVectorShuffle(SVOp, DAG);
7531 // Vector shuffle lowering takes 3 steps:
7533 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7534 // narrowing and commutation of operands should be handled.
7535 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7537 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7538 // so the shuffle can be broken into other shuffles and the legalizer can
7539 // try the lowering again.
7541 // The general idea is that no vector_shuffle operation should be left to
7542 // be matched during isel, all of them must be converted to a target specific
7545 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7546 // narrowing and commutation of operands should be handled. The actual code
7547 // doesn't include all of those, work in progress...
7548 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7549 if (NewOp.getNode())
7552 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7554 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7555 // unpckh_undef). Only use pshufd if speed is more important than size.
7556 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7557 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7558 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7559 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7561 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7562 V2IsUndef && MayFoldVectorLoad(V1))
7563 return getMOVDDup(Op, dl, V1, DAG);
7565 if (isMOVHLPS_v_undef_Mask(M, VT))
7566 return getMOVHighToLow(Op, dl, DAG);
7568 // Use to match splats
7569 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7570 (VT == MVT::v2f64 || VT == MVT::v2i64))
7571 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7573 if (isPSHUFDMask(M, VT)) {
7574 // The actual implementation will match the mask in the if above and then
7575 // during isel it can match several different instructions, not only pshufd
7576 // as its name says, sad but true, emulate the behavior for now...
7577 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7578 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7580 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7582 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7583 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7585 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7586 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7589 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7593 if (isPALIGNRMask(M, VT, Subtarget))
7594 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7595 getShufflePALIGNRImmediate(SVOp),
7598 // Check if this can be converted into a logical shift.
7599 bool isLeft = false;
7602 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7603 if (isShift && ShVal.hasOneUse()) {
7604 // If the shifted value has multiple uses, it may be cheaper to use
7605 // v_set0 + movlhps or movhlps, etc.
7606 MVT EltVT = VT.getVectorElementType();
7607 ShAmt *= EltVT.getSizeInBits();
7608 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7611 if (isMOVLMask(M, VT)) {
7612 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7613 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7614 if (!isMOVLPMask(M, VT)) {
7615 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7616 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7618 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7619 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7623 // FIXME: fold these into legal mask.
7624 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7625 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7627 if (isMOVHLPSMask(M, VT))
7628 return getMOVHighToLow(Op, dl, DAG);
7630 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7631 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7633 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7634 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7636 if (isMOVLPMask(M, VT))
7637 return getMOVLP(Op, dl, DAG, HasSSE2);
7639 if (ShouldXformToMOVHLPS(M, VT) ||
7640 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7641 return CommuteVectorShuffle(SVOp, DAG);
7644 // No better options. Use a vshldq / vsrldq.
7645 MVT EltVT = VT.getVectorElementType();
7646 ShAmt *= EltVT.getSizeInBits();
7647 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7650 bool Commuted = false;
7651 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7652 // 1,1,1,1 -> v8i16 though.
7653 V1IsSplat = isSplatVector(V1.getNode());
7654 V2IsSplat = isSplatVector(V2.getNode());
7656 // Canonicalize the splat or undef, if present, to be on the RHS.
7657 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7658 CommuteVectorShuffleMask(M, NumElems);
7660 std::swap(V1IsSplat, V2IsSplat);
7664 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7665 // Shuffling low element of v1 into undef, just return v1.
7668 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7669 // the instruction selector will not match, so get a canonical MOVL with
7670 // swapped operands to undo the commute.
7671 return getMOVL(DAG, dl, VT, V2, V1);
7674 if (isUNPCKLMask(M, VT, HasInt256))
7675 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7677 if (isUNPCKHMask(M, VT, HasInt256))
7678 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7681 // Normalize mask so all entries that point to V2 points to its first
7682 // element then try to match unpck{h|l} again. If match, return a
7683 // new vector_shuffle with the corrected mask.p
7684 SmallVector<int, 8> NewMask(M.begin(), M.end());
7685 NormalizeMask(NewMask, NumElems);
7686 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7687 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7688 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7689 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7693 // Commute is back and try unpck* again.
7694 // FIXME: this seems wrong.
7695 CommuteVectorShuffleMask(M, NumElems);
7697 std::swap(V1IsSplat, V2IsSplat);
7699 if (isUNPCKLMask(M, VT, HasInt256))
7700 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7702 if (isUNPCKHMask(M, VT, HasInt256))
7703 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7706 // Normalize the node to match x86 shuffle ops if needed
7707 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7708 return CommuteVectorShuffle(SVOp, DAG);
7710 // The checks below are all present in isShuffleMaskLegal, but they are
7711 // inlined here right now to enable us to directly emit target specific
7712 // nodes, and remove one by one until they don't return Op anymore.
7714 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7715 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7716 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7717 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7720 if (isPSHUFHWMask(M, VT, HasInt256))
7721 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7722 getShufflePSHUFHWImmediate(SVOp),
7725 if (isPSHUFLWMask(M, VT, HasInt256))
7726 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7727 getShufflePSHUFLWImmediate(SVOp),
7730 if (isSHUFPMask(M, VT))
7731 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7732 getShuffleSHUFImmediate(SVOp), DAG);
7734 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7735 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7736 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7737 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7739 //===--------------------------------------------------------------------===//
7740 // Generate target specific nodes for 128 or 256-bit shuffles only
7741 // supported in the AVX instruction set.
7744 // Handle VMOVDDUPY permutations
7745 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7746 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7748 // Handle VPERMILPS/D* permutations
7749 if (isVPERMILPMask(M, VT)) {
7750 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7751 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7752 getShuffleSHUFImmediate(SVOp), DAG);
7753 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7754 getShuffleSHUFImmediate(SVOp), DAG);
7757 // Handle VPERM2F128/VPERM2I128 permutations
7758 if (isVPERM2X128Mask(M, VT, HasFp256))
7759 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7760 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7762 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7763 if (BlendOp.getNode())
7766 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7767 return getINSERTPS(SVOp, dl, DAG);
7770 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7771 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7773 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7774 VT.is512BitVector()) {
7775 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7776 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7777 SmallVector<SDValue, 16> permclMask;
7778 for (unsigned i = 0; i != NumElems; ++i) {
7779 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7782 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7784 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7785 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7786 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7787 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7788 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7791 //===--------------------------------------------------------------------===//
7792 // Since no target specific shuffle was selected for this generic one,
7793 // lower it into other known shuffles. FIXME: this isn't true yet, but
7794 // this is the plan.
7797 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7798 if (VT == MVT::v8i16) {
7799 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7800 if (NewOp.getNode())
7804 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7805 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7806 if (NewOp.getNode())
7810 if (VT == MVT::v16i8) {
7811 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7812 if (NewOp.getNode())
7816 if (VT == MVT::v32i8) {
7817 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7818 if (NewOp.getNode())
7822 // Handle all 128-bit wide vectors with 4 elements, and match them with
7823 // several different shuffle types.
7824 if (NumElems == 4 && VT.is128BitVector())
7825 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7827 // Handle general 256-bit shuffles
7828 if (VT.is256BitVector())
7829 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7834 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7835 MVT VT = Op.getSimpleValueType();
7838 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7841 if (VT.getSizeInBits() == 8) {
7842 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7843 Op.getOperand(0), Op.getOperand(1));
7844 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7845 DAG.getValueType(VT));
7846 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7849 if (VT.getSizeInBits() == 16) {
7850 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7851 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7853 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7854 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7855 DAG.getNode(ISD::BITCAST, dl,
7859 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7860 Op.getOperand(0), Op.getOperand(1));
7861 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7862 DAG.getValueType(VT));
7863 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7866 if (VT == MVT::f32) {
7867 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7868 // the result back to FR32 register. It's only worth matching if the
7869 // result has a single use which is a store or a bitcast to i32. And in
7870 // the case of a store, it's not worth it if the index is a constant 0,
7871 // because a MOVSSmr can be used instead, which is smaller and faster.
7872 if (!Op.hasOneUse())
7874 SDNode *User = *Op.getNode()->use_begin();
7875 if ((User->getOpcode() != ISD::STORE ||
7876 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7877 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7878 (User->getOpcode() != ISD::BITCAST ||
7879 User->getValueType(0) != MVT::i32))
7881 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7882 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7885 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7888 if (VT == MVT::i32 || VT == MVT::i64) {
7889 // ExtractPS/pextrq works with constant index.
7890 if (isa<ConstantSDNode>(Op.getOperand(1)))
7896 /// Extract one bit from mask vector, like v16i1 or v8i1.
7897 /// AVX-512 feature.
7899 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7900 SDValue Vec = Op.getOperand(0);
7902 MVT VecVT = Vec.getSimpleValueType();
7903 SDValue Idx = Op.getOperand(1);
7904 MVT EltVT = Op.getSimpleValueType();
7906 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7908 // variable index can't be handled in mask registers,
7909 // extend vector to VR512
7910 if (!isa<ConstantSDNode>(Idx)) {
7911 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7912 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7913 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7914 ExtVT.getVectorElementType(), Ext, Idx);
7915 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7918 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7919 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7920 unsigned MaxSift = rc->getSize()*8 - 1;
7921 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7922 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7923 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7924 DAG.getConstant(MaxSift, MVT::i8));
7925 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7926 DAG.getIntPtrConstant(0));
7930 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7931 SelectionDAG &DAG) const {
7933 SDValue Vec = Op.getOperand(0);
7934 MVT VecVT = Vec.getSimpleValueType();
7935 SDValue Idx = Op.getOperand(1);
7937 if (Op.getSimpleValueType() == MVT::i1)
7938 return ExtractBitFromMaskVector(Op, DAG);
7940 if (!isa<ConstantSDNode>(Idx)) {
7941 if (VecVT.is512BitVector() ||
7942 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7943 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7946 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7947 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7948 MaskEltVT.getSizeInBits());
7950 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7951 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7952 getZeroVector(MaskVT, Subtarget, DAG, dl),
7953 Idx, DAG.getConstant(0, getPointerTy()));
7954 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7955 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7956 Perm, DAG.getConstant(0, getPointerTy()));
7961 // If this is a 256-bit vector result, first extract the 128-bit vector and
7962 // then extract the element from the 128-bit vector.
7963 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7965 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7966 // Get the 128-bit vector.
7967 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7968 MVT EltVT = VecVT.getVectorElementType();
7970 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7972 //if (IdxVal >= NumElems/2)
7973 // IdxVal -= NumElems/2;
7974 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7975 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7976 DAG.getConstant(IdxVal, MVT::i32));
7979 assert(VecVT.is128BitVector() && "Unexpected vector length");
7981 if (Subtarget->hasSSE41()) {
7982 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7987 MVT VT = Op.getSimpleValueType();
7988 // TODO: handle v16i8.
7989 if (VT.getSizeInBits() == 16) {
7990 SDValue Vec = Op.getOperand(0);
7991 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7993 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7994 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7995 DAG.getNode(ISD::BITCAST, dl,
7998 // Transform it so it match pextrw which produces a 32-bit result.
7999 MVT EltVT = MVT::i32;
8000 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8001 Op.getOperand(0), Op.getOperand(1));
8002 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8003 DAG.getValueType(VT));
8004 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8007 if (VT.getSizeInBits() == 32) {
8008 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8012 // SHUFPS the element to the lowest double word, then movss.
8013 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8014 MVT VVT = Op.getOperand(0).getSimpleValueType();
8015 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8016 DAG.getUNDEF(VVT), Mask);
8017 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8018 DAG.getIntPtrConstant(0));
8021 if (VT.getSizeInBits() == 64) {
8022 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8023 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8024 // to match extract_elt for f64.
8025 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8029 // UNPCKHPD the element to the lowest double word, then movsd.
8030 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8031 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8032 int Mask[2] = { 1, -1 };
8033 MVT VVT = Op.getOperand(0).getSimpleValueType();
8034 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8035 DAG.getUNDEF(VVT), Mask);
8036 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8037 DAG.getIntPtrConstant(0));
8043 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8044 MVT VT = Op.getSimpleValueType();
8045 MVT EltVT = VT.getVectorElementType();
8048 SDValue N0 = Op.getOperand(0);
8049 SDValue N1 = Op.getOperand(1);
8050 SDValue N2 = Op.getOperand(2);
8052 if (!VT.is128BitVector())
8055 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8056 isa<ConstantSDNode>(N2)) {
8058 if (VT == MVT::v8i16)
8059 Opc = X86ISD::PINSRW;
8060 else if (VT == MVT::v16i8)
8061 Opc = X86ISD::PINSRB;
8063 Opc = X86ISD::PINSRB;
8065 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8067 if (N1.getValueType() != MVT::i32)
8068 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8069 if (N2.getValueType() != MVT::i32)
8070 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8071 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8074 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8075 // Bits [7:6] of the constant are the source select. This will always be
8076 // zero here. The DAG Combiner may combine an extract_elt index into these
8077 // bits. For example (insert (extract, 3), 2) could be matched by putting
8078 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8079 // Bits [5:4] of the constant are the destination select. This is the
8080 // value of the incoming immediate.
8081 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8082 // combine either bitwise AND or insert of float 0.0 to set these bits.
8083 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8084 // Create this as a scalar to vector..
8085 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8086 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8089 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8090 // PINSR* works with constant index.
8096 /// Insert one bit to mask vector, like v16i1 or v8i1.
8097 /// AVX-512 feature.
8099 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8101 SDValue Vec = Op.getOperand(0);
8102 SDValue Elt = Op.getOperand(1);
8103 SDValue Idx = Op.getOperand(2);
8104 MVT VecVT = Vec.getSimpleValueType();
8106 if (!isa<ConstantSDNode>(Idx)) {
8107 // Non constant index. Extend source and destination,
8108 // insert element and then truncate the result.
8109 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8110 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8111 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8112 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8113 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8114 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8117 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8118 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8119 if (Vec.getOpcode() == ISD::UNDEF)
8120 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8121 DAG.getConstant(IdxVal, MVT::i8));
8122 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8123 unsigned MaxSift = rc->getSize()*8 - 1;
8124 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8125 DAG.getConstant(MaxSift, MVT::i8));
8126 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8127 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8128 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8131 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8132 MVT VT = Op.getSimpleValueType();
8133 MVT EltVT = VT.getVectorElementType();
8135 if (EltVT == MVT::i1)
8136 return InsertBitToMaskVector(Op, DAG);
8139 SDValue N0 = Op.getOperand(0);
8140 SDValue N1 = Op.getOperand(1);
8141 SDValue N2 = Op.getOperand(2);
8143 // If this is a 256-bit vector result, first extract the 128-bit vector,
8144 // insert the element into the extracted half and then place it back.
8145 if (VT.is256BitVector() || VT.is512BitVector()) {
8146 if (!isa<ConstantSDNode>(N2))
8149 // Get the desired 128-bit vector half.
8150 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8151 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8153 // Insert the element into the desired half.
8154 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8155 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8157 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8158 DAG.getConstant(IdxIn128, MVT::i32));
8160 // Insert the changed part back to the 256-bit vector
8161 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8164 if (Subtarget->hasSSE41())
8165 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8167 if (EltVT == MVT::i8)
8170 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8171 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8172 // as its second argument.
8173 if (N1.getValueType() != MVT::i32)
8174 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8175 if (N2.getValueType() != MVT::i32)
8176 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8177 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8182 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8184 MVT OpVT = Op.getSimpleValueType();
8186 // If this is a 256-bit vector result, first insert into a 128-bit
8187 // vector and then insert into the 256-bit vector.
8188 if (!OpVT.is128BitVector()) {
8189 // Insert into a 128-bit vector.
8190 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8191 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8192 OpVT.getVectorNumElements() / SizeFactor);
8194 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8196 // Insert the 128-bit vector.
8197 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8200 if (OpVT == MVT::v1i64 &&
8201 Op.getOperand(0).getValueType() == MVT::i64)
8202 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8204 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8205 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8206 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8207 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8210 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8211 // a simple subregister reference or explicit instructions to grab
8212 // upper bits of a vector.
8213 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8214 SelectionDAG &DAG) {
8216 SDValue In = Op.getOperand(0);
8217 SDValue Idx = Op.getOperand(1);
8218 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8219 MVT ResVT = Op.getSimpleValueType();
8220 MVT InVT = In.getSimpleValueType();
8222 if (Subtarget->hasFp256()) {
8223 if (ResVT.is128BitVector() &&
8224 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8225 isa<ConstantSDNode>(Idx)) {
8226 return Extract128BitVector(In, IdxVal, DAG, dl);
8228 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8229 isa<ConstantSDNode>(Idx)) {
8230 return Extract256BitVector(In, IdxVal, DAG, dl);
8236 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8237 // simple superregister reference or explicit instructions to insert
8238 // the upper bits of a vector.
8239 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8240 SelectionDAG &DAG) {
8241 if (Subtarget->hasFp256()) {
8242 SDLoc dl(Op.getNode());
8243 SDValue Vec = Op.getNode()->getOperand(0);
8244 SDValue SubVec = Op.getNode()->getOperand(1);
8245 SDValue Idx = Op.getNode()->getOperand(2);
8247 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8248 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8249 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8250 isa<ConstantSDNode>(Idx)) {
8251 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8252 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8255 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8256 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8257 isa<ConstantSDNode>(Idx)) {
8258 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8259 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8265 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8266 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8267 // one of the above mentioned nodes. It has to be wrapped because otherwise
8268 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8269 // be used to form addressing mode. These wrapped nodes will be selected
8272 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8273 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8275 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8277 unsigned char OpFlag = 0;
8278 unsigned WrapperKind = X86ISD::Wrapper;
8279 CodeModel::Model M = getTargetMachine().getCodeModel();
8281 if (Subtarget->isPICStyleRIPRel() &&
8282 (M == CodeModel::Small || M == CodeModel::Kernel))
8283 WrapperKind = X86ISD::WrapperRIP;
8284 else if (Subtarget->isPICStyleGOT())
8285 OpFlag = X86II::MO_GOTOFF;
8286 else if (Subtarget->isPICStyleStubPIC())
8287 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8289 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8291 CP->getOffset(), OpFlag);
8293 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8294 // With PIC, the address is actually $g + Offset.
8296 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8297 DAG.getNode(X86ISD::GlobalBaseReg,
8298 SDLoc(), getPointerTy()),
8305 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8306 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8308 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8310 unsigned char OpFlag = 0;
8311 unsigned WrapperKind = X86ISD::Wrapper;
8312 CodeModel::Model M = getTargetMachine().getCodeModel();
8314 if (Subtarget->isPICStyleRIPRel() &&
8315 (M == CodeModel::Small || M == CodeModel::Kernel))
8316 WrapperKind = X86ISD::WrapperRIP;
8317 else if (Subtarget->isPICStyleGOT())
8318 OpFlag = X86II::MO_GOTOFF;
8319 else if (Subtarget->isPICStyleStubPIC())
8320 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8322 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8325 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8327 // With PIC, the address is actually $g + Offset.
8329 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8330 DAG.getNode(X86ISD::GlobalBaseReg,
8331 SDLoc(), getPointerTy()),
8338 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8339 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8341 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8343 unsigned char OpFlag = 0;
8344 unsigned WrapperKind = X86ISD::Wrapper;
8345 CodeModel::Model M = getTargetMachine().getCodeModel();
8347 if (Subtarget->isPICStyleRIPRel() &&
8348 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8349 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8350 OpFlag = X86II::MO_GOTPCREL;
8351 WrapperKind = X86ISD::WrapperRIP;
8352 } else if (Subtarget->isPICStyleGOT()) {
8353 OpFlag = X86II::MO_GOT;
8354 } else if (Subtarget->isPICStyleStubPIC()) {
8355 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8356 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8357 OpFlag = X86II::MO_DARWIN_NONLAZY;
8360 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8363 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8365 // With PIC, the address is actually $g + Offset.
8366 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8367 !Subtarget->is64Bit()) {
8368 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8369 DAG.getNode(X86ISD::GlobalBaseReg,
8370 SDLoc(), getPointerTy()),
8374 // For symbols that require a load from a stub to get the address, emit the
8376 if (isGlobalStubReference(OpFlag))
8377 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8378 MachinePointerInfo::getGOT(), false, false, false, 0);
8384 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8385 // Create the TargetBlockAddressAddress node.
8386 unsigned char OpFlags =
8387 Subtarget->ClassifyBlockAddressReference();
8388 CodeModel::Model M = getTargetMachine().getCodeModel();
8389 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8390 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8392 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8395 if (Subtarget->isPICStyleRIPRel() &&
8396 (M == CodeModel::Small || M == CodeModel::Kernel))
8397 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8399 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8401 // With PIC, the address is actually $g + Offset.
8402 if (isGlobalRelativeToPICBase(OpFlags)) {
8403 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8404 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8412 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8413 int64_t Offset, SelectionDAG &DAG) const {
8414 // Create the TargetGlobalAddress node, folding in the constant
8415 // offset if it is legal.
8416 unsigned char OpFlags =
8417 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8418 CodeModel::Model M = getTargetMachine().getCodeModel();
8420 if (OpFlags == X86II::MO_NO_FLAG &&
8421 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8422 // A direct static reference to a global.
8423 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8426 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8429 if (Subtarget->isPICStyleRIPRel() &&
8430 (M == CodeModel::Small || M == CodeModel::Kernel))
8431 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8433 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8435 // With PIC, the address is actually $g + Offset.
8436 if (isGlobalRelativeToPICBase(OpFlags)) {
8437 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8438 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8442 // For globals that require a load from a stub to get the address, emit the
8444 if (isGlobalStubReference(OpFlags))
8445 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8446 MachinePointerInfo::getGOT(), false, false, false, 0);
8448 // If there was a non-zero offset that we didn't fold, create an explicit
8451 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8452 DAG.getConstant(Offset, getPointerTy()));
8458 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8459 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8460 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8461 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8465 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8466 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8467 unsigned char OperandFlags, bool LocalDynamic = false) {
8468 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8469 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8471 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8472 GA->getValueType(0),
8476 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8480 SDValue Ops[] = { Chain, TGA, *InFlag };
8481 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8483 SDValue Ops[] = { Chain, TGA };
8484 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8487 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8488 MFI->setAdjustsStack(true);
8490 SDValue Flag = Chain.getValue(1);
8491 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8494 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8496 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8499 SDLoc dl(GA); // ? function entry point might be better
8500 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8501 DAG.getNode(X86ISD::GlobalBaseReg,
8502 SDLoc(), PtrVT), InFlag);
8503 InFlag = Chain.getValue(1);
8505 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8508 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8510 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8512 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8513 X86::RAX, X86II::MO_TLSGD);
8516 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8522 // Get the start address of the TLS block for this module.
8523 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8524 .getInfo<X86MachineFunctionInfo>();
8525 MFI->incNumLocalDynamicTLSAccesses();
8529 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8530 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8533 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8534 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8535 InFlag = Chain.getValue(1);
8536 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8537 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8540 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8544 unsigned char OperandFlags = X86II::MO_DTPOFF;
8545 unsigned WrapperKind = X86ISD::Wrapper;
8546 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8547 GA->getValueType(0),
8548 GA->getOffset(), OperandFlags);
8549 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8551 // Add x@dtpoff with the base.
8552 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8555 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8556 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8557 const EVT PtrVT, TLSModel::Model model,
8558 bool is64Bit, bool isPIC) {
8561 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8562 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8563 is64Bit ? 257 : 256));
8565 SDValue ThreadPointer =
8566 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8567 MachinePointerInfo(Ptr), false, false, false, 0);
8569 unsigned char OperandFlags = 0;
8570 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8572 unsigned WrapperKind = X86ISD::Wrapper;
8573 if (model == TLSModel::LocalExec) {
8574 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8575 } else if (model == TLSModel::InitialExec) {
8577 OperandFlags = X86II::MO_GOTTPOFF;
8578 WrapperKind = X86ISD::WrapperRIP;
8580 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8583 llvm_unreachable("Unexpected model");
8586 // emit "addl x@ntpoff,%eax" (local exec)
8587 // or "addl x@indntpoff,%eax" (initial exec)
8588 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8590 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8591 GA->getOffset(), OperandFlags);
8592 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8594 if (model == TLSModel::InitialExec) {
8595 if (isPIC && !is64Bit) {
8596 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8597 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8601 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8602 MachinePointerInfo::getGOT(), false, false, false, 0);
8605 // The address of the thread local variable is the add of the thread
8606 // pointer with the offset of the variable.
8607 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8611 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8613 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8614 const GlobalValue *GV = GA->getGlobal();
8616 if (Subtarget->isTargetELF()) {
8617 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8620 case TLSModel::GeneralDynamic:
8621 if (Subtarget->is64Bit())
8622 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8623 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8624 case TLSModel::LocalDynamic:
8625 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8626 Subtarget->is64Bit());
8627 case TLSModel::InitialExec:
8628 case TLSModel::LocalExec:
8629 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8630 Subtarget->is64Bit(),
8631 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8633 llvm_unreachable("Unknown TLS model.");
8636 if (Subtarget->isTargetDarwin()) {
8637 // Darwin only has one model of TLS. Lower to that.
8638 unsigned char OpFlag = 0;
8639 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8640 X86ISD::WrapperRIP : X86ISD::Wrapper;
8642 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8644 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8645 !Subtarget->is64Bit();
8647 OpFlag = X86II::MO_TLVP_PIC_BASE;
8649 OpFlag = X86II::MO_TLVP;
8651 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8652 GA->getValueType(0),
8653 GA->getOffset(), OpFlag);
8654 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8656 // With PIC32, the address is actually $g + Offset.
8658 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8659 DAG.getNode(X86ISD::GlobalBaseReg,
8660 SDLoc(), getPointerTy()),
8663 // Lowering the machine isd will make sure everything is in the right
8665 SDValue Chain = DAG.getEntryNode();
8666 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8667 SDValue Args[] = { Chain, Offset };
8668 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8670 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8671 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8672 MFI->setAdjustsStack(true);
8674 // And our return value (tls address) is in the standard call return value
8676 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8677 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8681 if (Subtarget->isTargetKnownWindowsMSVC() ||
8682 Subtarget->isTargetWindowsGNU()) {
8683 // Just use the implicit TLS architecture
8684 // Need to generate someting similar to:
8685 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8687 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8688 // mov rcx, qword [rdx+rcx*8]
8689 // mov eax, .tls$:tlsvar
8690 // [rax+rcx] contains the address
8691 // Windows 64bit: gs:0x58
8692 // Windows 32bit: fs:__tls_array
8694 // If GV is an alias then use the aliasee for determining
8695 // thread-localness.
8696 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8697 GV = GA->getAliasedGlobal();
8699 SDValue Chain = DAG.getEntryNode();
8701 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8702 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8703 // use its literal value of 0x2C.
8704 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8705 ? Type::getInt8PtrTy(*DAG.getContext(),
8707 : Type::getInt32PtrTy(*DAG.getContext(),
8711 Subtarget->is64Bit()
8712 ? DAG.getIntPtrConstant(0x58)
8713 : (Subtarget->isTargetWindowsGNU()
8714 ? DAG.getIntPtrConstant(0x2C)
8715 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8717 SDValue ThreadPointer =
8718 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8719 MachinePointerInfo(Ptr), false, false, false, 0);
8721 // Load the _tls_index variable
8722 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8723 if (Subtarget->is64Bit())
8724 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8725 IDX, MachinePointerInfo(), MVT::i32,
8728 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8729 false, false, false, 0);
8731 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8733 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8735 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8736 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8737 false, false, false, 0);
8739 // Get the offset of start of .tls section
8740 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8741 GA->getValueType(0),
8742 GA->getOffset(), X86II::MO_SECREL);
8743 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8745 // The address of the thread local variable is the add of the thread
8746 // pointer with the offset of the variable.
8747 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8750 llvm_unreachable("TLS not implemented for this target.");
8753 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8754 /// and take a 2 x i32 value to shift plus a shift amount.
8755 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8756 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8757 MVT VT = Op.getSimpleValueType();
8758 unsigned VTBits = VT.getSizeInBits();
8760 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8761 SDValue ShOpLo = Op.getOperand(0);
8762 SDValue ShOpHi = Op.getOperand(1);
8763 SDValue ShAmt = Op.getOperand(2);
8764 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8765 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8767 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8768 DAG.getConstant(VTBits - 1, MVT::i8));
8769 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8770 DAG.getConstant(VTBits - 1, MVT::i8))
8771 : DAG.getConstant(0, VT);
8774 if (Op.getOpcode() == ISD::SHL_PARTS) {
8775 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8776 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8778 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8779 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8782 // If the shift amount is larger or equal than the width of a part we can't
8783 // rely on the results of shld/shrd. Insert a test and select the appropriate
8784 // values for large shift amounts.
8785 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8786 DAG.getConstant(VTBits, MVT::i8));
8787 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8788 AndNode, DAG.getConstant(0, MVT::i8));
8791 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8792 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8793 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8795 if (Op.getOpcode() == ISD::SHL_PARTS) {
8796 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8797 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8799 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8800 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8803 SDValue Ops[2] = { Lo, Hi };
8804 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8807 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8808 SelectionDAG &DAG) const {
8809 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8811 if (SrcVT.isVector())
8814 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8815 "Unknown SINT_TO_FP to lower!");
8817 // These are really Legal; return the operand so the caller accepts it as
8819 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8821 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8822 Subtarget->is64Bit()) {
8827 unsigned Size = SrcVT.getSizeInBits()/8;
8828 MachineFunction &MF = DAG.getMachineFunction();
8829 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8830 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8831 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8833 MachinePointerInfo::getFixedStack(SSFI),
8835 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8838 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8840 SelectionDAG &DAG) const {
8844 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8846 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8848 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8850 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8852 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8853 MachineMemOperand *MMO;
8855 int SSFI = FI->getIndex();
8857 DAG.getMachineFunction()
8858 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8859 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8861 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8862 StackSlot = StackSlot.getOperand(1);
8864 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8865 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8867 Tys, Ops, SrcVT, MMO);
8870 Chain = Result.getValue(1);
8871 SDValue InFlag = Result.getValue(2);
8873 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8874 // shouldn't be necessary except that RFP cannot be live across
8875 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8876 MachineFunction &MF = DAG.getMachineFunction();
8877 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8878 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8879 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8880 Tys = DAG.getVTList(MVT::Other);
8882 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8884 MachineMemOperand *MMO =
8885 DAG.getMachineFunction()
8886 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8887 MachineMemOperand::MOStore, SSFISize, SSFISize);
8889 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8890 Ops, Op.getValueType(), MMO);
8891 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8892 MachinePointerInfo::getFixedStack(SSFI),
8893 false, false, false, 0);
8899 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8900 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8901 SelectionDAG &DAG) const {
8902 // This algorithm is not obvious. Here it is what we're trying to output:
8905 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8906 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8910 pshufd $0x4e, %xmm0, %xmm1
8916 LLVMContext *Context = DAG.getContext();
8918 // Build some magic constants.
8919 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8920 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8921 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8923 SmallVector<Constant*,2> CV1;
8925 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8926 APInt(64, 0x4330000000000000ULL))));
8928 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8929 APInt(64, 0x4530000000000000ULL))));
8930 Constant *C1 = ConstantVector::get(CV1);
8931 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8933 // Load the 64-bit value into an XMM register.
8934 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8936 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8937 MachinePointerInfo::getConstantPool(),
8938 false, false, false, 16);
8939 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8940 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8943 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8944 MachinePointerInfo::getConstantPool(),
8945 false, false, false, 16);
8946 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8947 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8950 if (Subtarget->hasSSE3()) {
8951 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8952 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8954 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8955 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8957 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8958 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8962 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8963 DAG.getIntPtrConstant(0));
8966 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8967 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8968 SelectionDAG &DAG) const {
8970 // FP constant to bias correct the final result.
8971 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8974 // Load the 32-bit value into an XMM register.
8975 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8978 // Zero out the upper parts of the register.
8979 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8981 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8982 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8983 DAG.getIntPtrConstant(0));
8985 // Or the load with the bias.
8986 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8987 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8988 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8990 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8991 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8992 MVT::v2f64, Bias)));
8993 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8994 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8995 DAG.getIntPtrConstant(0));
8997 // Subtract the bias.
8998 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9000 // Handle final rounding.
9001 EVT DestVT = Op.getValueType();
9003 if (DestVT.bitsLT(MVT::f64))
9004 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9005 DAG.getIntPtrConstant(0));
9006 if (DestVT.bitsGT(MVT::f64))
9007 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9009 // Handle final rounding.
9013 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9014 SelectionDAG &DAG) const {
9015 SDValue N0 = Op.getOperand(0);
9016 MVT SVT = N0.getSimpleValueType();
9019 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9020 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9021 "Custom UINT_TO_FP is not supported!");
9023 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9024 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9025 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9028 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9029 SelectionDAG &DAG) const {
9030 SDValue N0 = Op.getOperand(0);
9033 if (Op.getValueType().isVector())
9034 return lowerUINT_TO_FP_vec(Op, DAG);
9036 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9037 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9038 // the optimization here.
9039 if (DAG.SignBitIsZero(N0))
9040 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9042 MVT SrcVT = N0.getSimpleValueType();
9043 MVT DstVT = Op.getSimpleValueType();
9044 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9045 return LowerUINT_TO_FP_i64(Op, DAG);
9046 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9047 return LowerUINT_TO_FP_i32(Op, DAG);
9048 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9051 // Make a 64-bit buffer, and use it to build an FILD.
9052 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9053 if (SrcVT == MVT::i32) {
9054 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9055 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9056 getPointerTy(), StackSlot, WordOff);
9057 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9058 StackSlot, MachinePointerInfo(),
9060 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9061 OffsetSlot, MachinePointerInfo(),
9063 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9067 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9068 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9069 StackSlot, MachinePointerInfo(),
9071 // For i64 source, we need to add the appropriate power of 2 if the input
9072 // was negative. This is the same as the optimization in
9073 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9074 // we must be careful to do the computation in x87 extended precision, not
9075 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9076 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9077 MachineMemOperand *MMO =
9078 DAG.getMachineFunction()
9079 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9080 MachineMemOperand::MOLoad, 8, 8);
9082 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9083 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9084 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9087 APInt FF(32, 0x5F800000ULL);
9089 // Check whether the sign bit is set.
9090 SDValue SignSet = DAG.getSetCC(dl,
9091 getSetCCResultType(*DAG.getContext(), MVT::i64),
9092 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9095 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9096 SDValue FudgePtr = DAG.getConstantPool(
9097 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9100 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9101 SDValue Zero = DAG.getIntPtrConstant(0);
9102 SDValue Four = DAG.getIntPtrConstant(4);
9103 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9105 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9107 // Load the value out, extending it from f32 to f80.
9108 // FIXME: Avoid the extend by constructing the right constant pool?
9109 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9110 FudgePtr, MachinePointerInfo::getConstantPool(),
9111 MVT::f32, false, false, 4);
9112 // Extend everything to 80 bits to force it to be done on x87.
9113 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9114 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9117 std::pair<SDValue,SDValue>
9118 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9119 bool IsSigned, bool IsReplace) const {
9122 EVT DstTy = Op.getValueType();
9124 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9125 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9129 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9130 DstTy.getSimpleVT() >= MVT::i16 &&
9131 "Unknown FP_TO_INT to lower!");
9133 // These are really Legal.
9134 if (DstTy == MVT::i32 &&
9135 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9136 return std::make_pair(SDValue(), SDValue());
9137 if (Subtarget->is64Bit() &&
9138 DstTy == MVT::i64 &&
9139 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9140 return std::make_pair(SDValue(), SDValue());
9142 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9143 // stack slot, or into the FTOL runtime function.
9144 MachineFunction &MF = DAG.getMachineFunction();
9145 unsigned MemSize = DstTy.getSizeInBits()/8;
9146 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9147 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9150 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9151 Opc = X86ISD::WIN_FTOL;
9153 switch (DstTy.getSimpleVT().SimpleTy) {
9154 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9155 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9156 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9157 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9160 SDValue Chain = DAG.getEntryNode();
9161 SDValue Value = Op.getOperand(0);
9162 EVT TheVT = Op.getOperand(0).getValueType();
9163 // FIXME This causes a redundant load/store if the SSE-class value is already
9164 // in memory, such as if it is on the callstack.
9165 if (isScalarFPTypeInSSEReg(TheVT)) {
9166 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9167 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9168 MachinePointerInfo::getFixedStack(SSFI),
9170 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9172 Chain, StackSlot, DAG.getValueType(TheVT)
9175 MachineMemOperand *MMO =
9176 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9177 MachineMemOperand::MOLoad, MemSize, MemSize);
9178 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9179 Chain = Value.getValue(1);
9180 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9181 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9184 MachineMemOperand *MMO =
9185 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9186 MachineMemOperand::MOStore, MemSize, MemSize);
9188 if (Opc != X86ISD::WIN_FTOL) {
9189 // Build the FP_TO_INT*_IN_MEM
9190 SDValue Ops[] = { Chain, Value, StackSlot };
9191 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9193 return std::make_pair(FIST, StackSlot);
9195 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9196 DAG.getVTList(MVT::Other, MVT::Glue),
9198 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9199 MVT::i32, ftol.getValue(1));
9200 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9201 MVT::i32, eax.getValue(2));
9202 SDValue Ops[] = { eax, edx };
9203 SDValue pair = IsReplace
9204 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9205 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9206 return std::make_pair(pair, SDValue());
9210 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9211 const X86Subtarget *Subtarget) {
9212 MVT VT = Op->getSimpleValueType(0);
9213 SDValue In = Op->getOperand(0);
9214 MVT InVT = In.getSimpleValueType();
9217 // Optimize vectors in AVX mode:
9220 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9221 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9222 // Concat upper and lower parts.
9225 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9226 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9227 // Concat upper and lower parts.
9230 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9231 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9232 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9235 if (Subtarget->hasInt256())
9236 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9238 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9239 SDValue Undef = DAG.getUNDEF(InVT);
9240 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9241 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9242 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9244 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9245 VT.getVectorNumElements()/2);
9247 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9248 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9250 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9253 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9254 SelectionDAG &DAG) {
9255 MVT VT = Op->getSimpleValueType(0);
9256 SDValue In = Op->getOperand(0);
9257 MVT InVT = In.getSimpleValueType();
9259 unsigned int NumElts = VT.getVectorNumElements();
9260 if (NumElts != 8 && NumElts != 16)
9263 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9264 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9266 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9267 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9268 // Now we have only mask extension
9269 assert(InVT.getVectorElementType() == MVT::i1);
9270 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9271 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9272 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9273 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9274 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9275 MachinePointerInfo::getConstantPool(),
9276 false, false, false, Alignment);
9278 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9279 if (VT.is512BitVector())
9281 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9284 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9285 SelectionDAG &DAG) {
9286 if (Subtarget->hasFp256()) {
9287 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9295 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9296 SelectionDAG &DAG) {
9298 MVT VT = Op.getSimpleValueType();
9299 SDValue In = Op.getOperand(0);
9300 MVT SVT = In.getSimpleValueType();
9302 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9303 return LowerZERO_EXTEND_AVX512(Op, DAG);
9305 if (Subtarget->hasFp256()) {
9306 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9311 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9312 VT.getVectorNumElements() != SVT.getVectorNumElements());
9316 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9318 MVT VT = Op.getSimpleValueType();
9319 SDValue In = Op.getOperand(0);
9320 MVT InVT = In.getSimpleValueType();
9322 if (VT == MVT::i1) {
9323 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9324 "Invalid scalar TRUNCATE operation");
9325 if (InVT == MVT::i32)
9327 if (InVT.getSizeInBits() == 64)
9328 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9329 else if (InVT.getSizeInBits() < 32)
9330 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9331 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9333 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9334 "Invalid TRUNCATE operation");
9336 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9337 if (VT.getVectorElementType().getSizeInBits() >=8)
9338 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9340 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9341 unsigned NumElts = InVT.getVectorNumElements();
9342 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9343 if (InVT.getSizeInBits() < 512) {
9344 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9345 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9349 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9350 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9351 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9352 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9353 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9354 MachinePointerInfo::getConstantPool(),
9355 false, false, false, Alignment);
9356 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9357 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9358 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9361 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9362 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9363 if (Subtarget->hasInt256()) {
9364 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9365 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9366 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9368 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9369 DAG.getIntPtrConstant(0));
9372 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9373 DAG.getIntPtrConstant(0));
9374 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9375 DAG.getIntPtrConstant(2));
9376 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9377 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9378 static const int ShufMask[] = {0, 2, 4, 6};
9379 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9382 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9383 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9384 if (Subtarget->hasInt256()) {
9385 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9387 SmallVector<SDValue,32> pshufbMask;
9388 for (unsigned i = 0; i < 2; ++i) {
9389 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9390 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9391 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9392 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9393 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9394 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9395 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9396 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9397 for (unsigned j = 0; j < 8; ++j)
9398 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9400 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9401 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9402 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9404 static const int ShufMask[] = {0, 2, -1, -1};
9405 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9407 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9408 DAG.getIntPtrConstant(0));
9409 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9412 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9413 DAG.getIntPtrConstant(0));
9415 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9416 DAG.getIntPtrConstant(4));
9418 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9419 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9422 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9423 -1, -1, -1, -1, -1, -1, -1, -1};
9425 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9426 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9427 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9429 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9430 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9432 // The MOVLHPS Mask:
9433 static const int ShufMask2[] = {0, 1, 4, 5};
9434 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9435 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9438 // Handle truncation of V256 to V128 using shuffles.
9439 if (!VT.is128BitVector() || !InVT.is256BitVector())
9442 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9444 unsigned NumElems = VT.getVectorNumElements();
9445 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9447 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9448 // Prepare truncation shuffle mask
9449 for (unsigned i = 0; i != NumElems; ++i)
9451 SDValue V = DAG.getVectorShuffle(NVT, DL,
9452 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9453 DAG.getUNDEF(NVT), &MaskVec[0]);
9454 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9455 DAG.getIntPtrConstant(0));
9458 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9459 SelectionDAG &DAG) const {
9460 assert(!Op.getSimpleValueType().isVector());
9462 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9463 /*IsSigned=*/ true, /*IsReplace=*/ false);
9464 SDValue FIST = Vals.first, StackSlot = Vals.second;
9465 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9466 if (!FIST.getNode()) return Op;
9468 if (StackSlot.getNode())
9470 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9471 FIST, StackSlot, MachinePointerInfo(),
9472 false, false, false, 0);
9474 // The node is the result.
9478 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9479 SelectionDAG &DAG) const {
9480 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9481 /*IsSigned=*/ false, /*IsReplace=*/ false);
9482 SDValue FIST = Vals.first, StackSlot = Vals.second;
9483 assert(FIST.getNode() && "Unexpected failure");
9485 if (StackSlot.getNode())
9487 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9488 FIST, StackSlot, MachinePointerInfo(),
9489 false, false, false, 0);
9491 // The node is the result.
9495 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9497 MVT VT = Op.getSimpleValueType();
9498 SDValue In = Op.getOperand(0);
9499 MVT SVT = In.getSimpleValueType();
9501 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9503 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9504 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9505 In, DAG.getUNDEF(SVT)));
9508 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9509 LLVMContext *Context = DAG.getContext();
9511 MVT VT = Op.getSimpleValueType();
9513 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9514 if (VT.isVector()) {
9515 EltVT = VT.getVectorElementType();
9516 NumElts = VT.getVectorNumElements();
9519 if (EltVT == MVT::f64)
9520 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9521 APInt(64, ~(1ULL << 63))));
9523 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9524 APInt(32, ~(1U << 31))));
9525 C = ConstantVector::getSplat(NumElts, C);
9526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9527 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9528 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9529 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9530 MachinePointerInfo::getConstantPool(),
9531 false, false, false, Alignment);
9532 if (VT.isVector()) {
9533 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9534 return DAG.getNode(ISD::BITCAST, dl, VT,
9535 DAG.getNode(ISD::AND, dl, ANDVT,
9536 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9538 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9540 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9543 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9544 LLVMContext *Context = DAG.getContext();
9546 MVT VT = Op.getSimpleValueType();
9548 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9549 if (VT.isVector()) {
9550 EltVT = VT.getVectorElementType();
9551 NumElts = VT.getVectorNumElements();
9554 if (EltVT == MVT::f64)
9555 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9556 APInt(64, 1ULL << 63)));
9558 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9559 APInt(32, 1U << 31)));
9560 C = ConstantVector::getSplat(NumElts, C);
9561 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9562 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9563 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9564 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9565 MachinePointerInfo::getConstantPool(),
9566 false, false, false, Alignment);
9567 if (VT.isVector()) {
9568 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9569 return DAG.getNode(ISD::BITCAST, dl, VT,
9570 DAG.getNode(ISD::XOR, dl, XORVT,
9571 DAG.getNode(ISD::BITCAST, dl, XORVT,
9573 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9576 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9579 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9581 LLVMContext *Context = DAG.getContext();
9582 SDValue Op0 = Op.getOperand(0);
9583 SDValue Op1 = Op.getOperand(1);
9585 MVT VT = Op.getSimpleValueType();
9586 MVT SrcVT = Op1.getSimpleValueType();
9588 // If second operand is smaller, extend it first.
9589 if (SrcVT.bitsLT(VT)) {
9590 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9593 // And if it is bigger, shrink it first.
9594 if (SrcVT.bitsGT(VT)) {
9595 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9599 // At this point the operands and the result should have the same
9600 // type, and that won't be f80 since that is not custom lowered.
9602 // First get the sign bit of second operand.
9603 SmallVector<Constant*,4> CV;
9604 if (SrcVT == MVT::f64) {
9605 const fltSemantics &Sem = APFloat::IEEEdouble;
9606 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9607 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9609 const fltSemantics &Sem = APFloat::IEEEsingle;
9610 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9611 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9612 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9613 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9615 Constant *C = ConstantVector::get(CV);
9616 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9617 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9618 MachinePointerInfo::getConstantPool(),
9619 false, false, false, 16);
9620 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9622 // Shift sign bit right or left if the two operands have different types.
9623 if (SrcVT.bitsGT(VT)) {
9624 // Op0 is MVT::f32, Op1 is MVT::f64.
9625 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9626 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9627 DAG.getConstant(32, MVT::i32));
9628 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9629 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9630 DAG.getIntPtrConstant(0));
9633 // Clear first operand sign bit.
9635 if (VT == MVT::f64) {
9636 const fltSemantics &Sem = APFloat::IEEEdouble;
9637 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9638 APInt(64, ~(1ULL << 63)))));
9639 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9641 const fltSemantics &Sem = APFloat::IEEEsingle;
9642 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9643 APInt(32, ~(1U << 31)))));
9644 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9645 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9646 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9648 C = ConstantVector::get(CV);
9649 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9650 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9651 MachinePointerInfo::getConstantPool(),
9652 false, false, false, 16);
9653 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9655 // Or the value with the sign bit.
9656 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9659 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9660 SDValue N0 = Op.getOperand(0);
9662 MVT VT = Op.getSimpleValueType();
9664 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9665 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9666 DAG.getConstant(1, VT));
9667 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9670 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9672 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9673 SelectionDAG &DAG) {
9674 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9676 if (!Subtarget->hasSSE41())
9679 if (!Op->hasOneUse())
9682 SDNode *N = Op.getNode();
9685 SmallVector<SDValue, 8> Opnds;
9686 DenseMap<SDValue, unsigned> VecInMap;
9687 SmallVector<SDValue, 8> VecIns;
9688 EVT VT = MVT::Other;
9690 // Recognize a special case where a vector is casted into wide integer to
9692 Opnds.push_back(N->getOperand(0));
9693 Opnds.push_back(N->getOperand(1));
9695 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9696 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9697 // BFS traverse all OR'd operands.
9698 if (I->getOpcode() == ISD::OR) {
9699 Opnds.push_back(I->getOperand(0));
9700 Opnds.push_back(I->getOperand(1));
9701 // Re-evaluate the number of nodes to be traversed.
9702 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9706 // Quit if a non-EXTRACT_VECTOR_ELT
9707 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9710 // Quit if without a constant index.
9711 SDValue Idx = I->getOperand(1);
9712 if (!isa<ConstantSDNode>(Idx))
9715 SDValue ExtractedFromVec = I->getOperand(0);
9716 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9717 if (M == VecInMap.end()) {
9718 VT = ExtractedFromVec.getValueType();
9719 // Quit if not 128/256-bit vector.
9720 if (!VT.is128BitVector() && !VT.is256BitVector())
9722 // Quit if not the same type.
9723 if (VecInMap.begin() != VecInMap.end() &&
9724 VT != VecInMap.begin()->first.getValueType())
9726 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9727 VecIns.push_back(ExtractedFromVec);
9729 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9732 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9733 "Not extracted from 128-/256-bit vector.");
9735 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9737 for (DenseMap<SDValue, unsigned>::const_iterator
9738 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9739 // Quit if not all elements are used.
9740 if (I->second != FullMask)
9744 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9746 // Cast all vectors into TestVT for PTEST.
9747 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9748 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9750 // If more than one full vectors are evaluated, OR them first before PTEST.
9751 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9752 // Each iteration will OR 2 nodes and append the result until there is only
9753 // 1 node left, i.e. the final OR'd value of all vectors.
9754 SDValue LHS = VecIns[Slot];
9755 SDValue RHS = VecIns[Slot + 1];
9756 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9759 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9760 VecIns.back(), VecIns.back());
9763 /// \brief return true if \c Op has a use that doesn't just read flags.
9764 static bool hasNonFlagsUse(SDValue Op) {
9765 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9768 unsigned UOpNo = UI.getOperandNo();
9769 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9770 // Look pass truncate.
9771 UOpNo = User->use_begin().getOperandNo();
9772 User = *User->use_begin();
9775 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9776 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9782 /// Emit nodes that will be selected as "test Op0,Op0", or something
9784 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9785 SelectionDAG &DAG) const {
9786 if (Op.getValueType() == MVT::i1)
9787 // KORTEST instruction should be selected
9788 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9789 DAG.getConstant(0, Op.getValueType()));
9791 // CF and OF aren't always set the way we want. Determine which
9792 // of these we need.
9793 bool NeedCF = false;
9794 bool NeedOF = false;
9797 case X86::COND_A: case X86::COND_AE:
9798 case X86::COND_B: case X86::COND_BE:
9801 case X86::COND_G: case X86::COND_GE:
9802 case X86::COND_L: case X86::COND_LE:
9803 case X86::COND_O: case X86::COND_NO:
9807 // See if we can use the EFLAGS value from the operand instead of
9808 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9809 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9810 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9811 // Emit a CMP with 0, which is the TEST pattern.
9812 //if (Op.getValueType() == MVT::i1)
9813 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9814 // DAG.getConstant(0, MVT::i1));
9815 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9816 DAG.getConstant(0, Op.getValueType()));
9818 unsigned Opcode = 0;
9819 unsigned NumOperands = 0;
9821 // Truncate operations may prevent the merge of the SETCC instruction
9822 // and the arithmetic instruction before it. Attempt to truncate the operands
9823 // of the arithmetic instruction and use a reduced bit-width instruction.
9824 bool NeedTruncation = false;
9825 SDValue ArithOp = Op;
9826 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9827 SDValue Arith = Op->getOperand(0);
9828 // Both the trunc and the arithmetic op need to have one user each.
9829 if (Arith->hasOneUse())
9830 switch (Arith.getOpcode()) {
9837 NeedTruncation = true;
9843 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9844 // which may be the result of a CAST. We use the variable 'Op', which is the
9845 // non-casted variable when we check for possible users.
9846 switch (ArithOp.getOpcode()) {
9848 // Due to an isel shortcoming, be conservative if this add is likely to be
9849 // selected as part of a load-modify-store instruction. When the root node
9850 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9851 // uses of other nodes in the match, such as the ADD in this case. This
9852 // leads to the ADD being left around and reselected, with the result being
9853 // two adds in the output. Alas, even if none our users are stores, that
9854 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9855 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9856 // climbing the DAG back to the root, and it doesn't seem to be worth the
9858 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9859 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9860 if (UI->getOpcode() != ISD::CopyToReg &&
9861 UI->getOpcode() != ISD::SETCC &&
9862 UI->getOpcode() != ISD::STORE)
9865 if (ConstantSDNode *C =
9866 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9867 // An add of one will be selected as an INC.
9868 if (C->getAPIntValue() == 1) {
9869 Opcode = X86ISD::INC;
9874 // An add of negative one (subtract of one) will be selected as a DEC.
9875 if (C->getAPIntValue().isAllOnesValue()) {
9876 Opcode = X86ISD::DEC;
9882 // Otherwise use a regular EFLAGS-setting add.
9883 Opcode = X86ISD::ADD;
9888 // If we have a constant logical shift that's only used in a comparison
9889 // against zero turn it into an equivalent AND. This allows turning it into
9890 // a TEST instruction later.
9891 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9892 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9893 EVT VT = Op.getValueType();
9894 unsigned BitWidth = VT.getSizeInBits();
9895 unsigned ShAmt = Op->getConstantOperandVal(1);
9896 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9898 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9899 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9900 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9901 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9903 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9904 DAG.getConstant(Mask, VT));
9905 DAG.ReplaceAllUsesWith(Op, New);
9911 // If the primary and result isn't used, don't bother using X86ISD::AND,
9912 // because a TEST instruction will be better.
9913 if (!hasNonFlagsUse(Op))
9919 // Due to the ISEL shortcoming noted above, be conservative if this op is
9920 // likely to be selected as part of a load-modify-store instruction.
9921 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9922 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9923 if (UI->getOpcode() == ISD::STORE)
9926 // Otherwise use a regular EFLAGS-setting instruction.
9927 switch (ArithOp.getOpcode()) {
9928 default: llvm_unreachable("unexpected operator!");
9929 case ISD::SUB: Opcode = X86ISD::SUB; break;
9930 case ISD::XOR: Opcode = X86ISD::XOR; break;
9931 case ISD::AND: Opcode = X86ISD::AND; break;
9933 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9934 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9935 if (EFLAGS.getNode())
9938 Opcode = X86ISD::OR;
9952 return SDValue(Op.getNode(), 1);
9958 // If we found that truncation is beneficial, perform the truncation and
9960 if (NeedTruncation) {
9961 EVT VT = Op.getValueType();
9962 SDValue WideVal = Op->getOperand(0);
9963 EVT WideVT = WideVal.getValueType();
9964 unsigned ConvertedOp = 0;
9965 // Use a target machine opcode to prevent further DAGCombine
9966 // optimizations that may separate the arithmetic operations
9967 // from the setcc node.
9968 switch (WideVal.getOpcode()) {
9970 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9971 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9972 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9973 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9974 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9978 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9979 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9980 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9981 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9982 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9988 // Emit a CMP with 0, which is the TEST pattern.
9989 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9990 DAG.getConstant(0, Op.getValueType()));
9992 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9993 SmallVector<SDValue, 4> Ops;
9994 for (unsigned i = 0; i != NumOperands; ++i)
9995 Ops.push_back(Op.getOperand(i));
9997 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
9998 DAG.ReplaceAllUsesWith(Op, New);
9999 return SDValue(New.getNode(), 1);
10002 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10004 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10005 SDLoc dl, SelectionDAG &DAG) const {
10006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10007 if (C->getAPIntValue() == 0)
10008 return EmitTest(Op0, X86CC, dl, DAG);
10010 if (Op0.getValueType() == MVT::i1)
10011 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10014 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10015 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10016 // Do the comparison at i32 if it's smaller, besides the Atom case.
10017 // This avoids subregister aliasing issues. Keep the smaller reference
10018 // if we're optimizing for size, however, as that'll allow better folding
10019 // of memory operations.
10020 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10021 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10022 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10023 !Subtarget->isAtom()) {
10024 unsigned ExtendOp =
10025 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10026 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10027 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10029 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10030 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10031 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10033 return SDValue(Sub.getNode(), 1);
10035 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10038 /// Convert a comparison if required by the subtarget.
10039 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10040 SelectionDAG &DAG) const {
10041 // If the subtarget does not support the FUCOMI instruction, floating-point
10042 // comparisons have to be converted.
10043 if (Subtarget->hasCMov() ||
10044 Cmp.getOpcode() != X86ISD::CMP ||
10045 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10046 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10049 // The instruction selector will select an FUCOM instruction instead of
10050 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10051 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10052 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10054 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10055 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10056 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10057 DAG.getConstant(8, MVT::i8));
10058 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10059 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10062 static bool isAllOnes(SDValue V) {
10063 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10064 return C && C->isAllOnesValue();
10067 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10068 /// if it's possible.
10069 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10070 SDLoc dl, SelectionDAG &DAG) const {
10071 SDValue Op0 = And.getOperand(0);
10072 SDValue Op1 = And.getOperand(1);
10073 if (Op0.getOpcode() == ISD::TRUNCATE)
10074 Op0 = Op0.getOperand(0);
10075 if (Op1.getOpcode() == ISD::TRUNCATE)
10076 Op1 = Op1.getOperand(0);
10079 if (Op1.getOpcode() == ISD::SHL)
10080 std::swap(Op0, Op1);
10081 if (Op0.getOpcode() == ISD::SHL) {
10082 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10083 if (And00C->getZExtValue() == 1) {
10084 // If we looked past a truncate, check that it's only truncating away
10086 unsigned BitWidth = Op0.getValueSizeInBits();
10087 unsigned AndBitWidth = And.getValueSizeInBits();
10088 if (BitWidth > AndBitWidth) {
10090 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10091 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10095 RHS = Op0.getOperand(1);
10097 } else if (Op1.getOpcode() == ISD::Constant) {
10098 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10099 uint64_t AndRHSVal = AndRHS->getZExtValue();
10100 SDValue AndLHS = Op0;
10102 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10103 LHS = AndLHS.getOperand(0);
10104 RHS = AndLHS.getOperand(1);
10107 // Use BT if the immediate can't be encoded in a TEST instruction.
10108 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10110 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10114 if (LHS.getNode()) {
10115 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10116 // instruction. Since the shift amount is in-range-or-undefined, we know
10117 // that doing a bittest on the i32 value is ok. We extend to i32 because
10118 // the encoding for the i16 version is larger than the i32 version.
10119 // Also promote i16 to i32 for performance / code size reason.
10120 if (LHS.getValueType() == MVT::i8 ||
10121 LHS.getValueType() == MVT::i16)
10122 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10124 // If the operand types disagree, extend the shift amount to match. Since
10125 // BT ignores high bits (like shifts) we can use anyextend.
10126 if (LHS.getValueType() != RHS.getValueType())
10127 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10129 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10130 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10131 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10132 DAG.getConstant(Cond, MVT::i8), BT);
10138 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10140 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10145 // SSE Condition code mapping:
10154 switch (SetCCOpcode) {
10155 default: llvm_unreachable("Unexpected SETCC condition");
10157 case ISD::SETEQ: SSECC = 0; break;
10159 case ISD::SETGT: Swap = true; // Fallthrough
10161 case ISD::SETOLT: SSECC = 1; break;
10163 case ISD::SETGE: Swap = true; // Fallthrough
10165 case ISD::SETOLE: SSECC = 2; break;
10166 case ISD::SETUO: SSECC = 3; break;
10168 case ISD::SETNE: SSECC = 4; break;
10169 case ISD::SETULE: Swap = true; // Fallthrough
10170 case ISD::SETUGE: SSECC = 5; break;
10171 case ISD::SETULT: Swap = true; // Fallthrough
10172 case ISD::SETUGT: SSECC = 6; break;
10173 case ISD::SETO: SSECC = 7; break;
10175 case ISD::SETONE: SSECC = 8; break;
10178 std::swap(Op0, Op1);
10183 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10184 // ones, and then concatenate the result back.
10185 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10186 MVT VT = Op.getSimpleValueType();
10188 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10189 "Unsupported value type for operation");
10191 unsigned NumElems = VT.getVectorNumElements();
10193 SDValue CC = Op.getOperand(2);
10195 // Extract the LHS vectors
10196 SDValue LHS = Op.getOperand(0);
10197 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10198 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10200 // Extract the RHS vectors
10201 SDValue RHS = Op.getOperand(1);
10202 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10203 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10205 // Issue the operation on the smaller types and concatenate the result back
10206 MVT EltVT = VT.getVectorElementType();
10207 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10208 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10209 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10210 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10213 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10214 const X86Subtarget *Subtarget) {
10215 SDValue Op0 = Op.getOperand(0);
10216 SDValue Op1 = Op.getOperand(1);
10217 SDValue CC = Op.getOperand(2);
10218 MVT VT = Op.getSimpleValueType();
10221 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10222 Op.getValueType().getScalarType() == MVT::i1 &&
10223 "Cannot set masked compare for this operation");
10225 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10227 bool Unsigned = false;
10230 switch (SetCCOpcode) {
10231 default: llvm_unreachable("Unexpected SETCC condition");
10232 case ISD::SETNE: SSECC = 4; break;
10233 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10234 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10235 case ISD::SETLT: Swap = true; //fall-through
10236 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10237 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10238 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10239 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10240 case ISD::SETULE: Unsigned = true; //fall-through
10241 case ISD::SETLE: SSECC = 2; break;
10245 std::swap(Op0, Op1);
10247 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10248 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10249 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10250 DAG.getConstant(SSECC, MVT::i8));
10253 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10254 /// operand \p Op1. If non-trivial (for example because it's not constant)
10255 /// return an empty value.
10256 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10258 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10262 MVT VT = Op1.getSimpleValueType();
10263 MVT EVT = VT.getVectorElementType();
10264 unsigned n = VT.getVectorNumElements();
10265 SmallVector<SDValue, 8> ULTOp1;
10267 for (unsigned i = 0; i < n; ++i) {
10268 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10269 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10272 // Avoid underflow.
10273 APInt Val = Elt->getAPIntValue();
10277 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10280 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10283 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10284 SelectionDAG &DAG) {
10285 SDValue Op0 = Op.getOperand(0);
10286 SDValue Op1 = Op.getOperand(1);
10287 SDValue CC = Op.getOperand(2);
10288 MVT VT = Op.getSimpleValueType();
10289 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10290 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10295 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10296 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10299 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10300 unsigned Opc = X86ISD::CMPP;
10301 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10302 assert(VT.getVectorNumElements() <= 16);
10303 Opc = X86ISD::CMPM;
10305 // In the two special cases we can't handle, emit two comparisons.
10308 unsigned CombineOpc;
10309 if (SetCCOpcode == ISD::SETUEQ) {
10310 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10312 assert(SetCCOpcode == ISD::SETONE);
10313 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10316 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10317 DAG.getConstant(CC0, MVT::i8));
10318 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10319 DAG.getConstant(CC1, MVT::i8));
10320 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10322 // Handle all other FP comparisons here.
10323 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10324 DAG.getConstant(SSECC, MVT::i8));
10327 // Break 256-bit integer vector compare into smaller ones.
10328 if (VT.is256BitVector() && !Subtarget->hasInt256())
10329 return Lower256IntVSETCC(Op, DAG);
10331 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10332 EVT OpVT = Op1.getValueType();
10333 if (Subtarget->hasAVX512()) {
10334 if (Op1.getValueType().is512BitVector() ||
10335 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10336 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10338 // In AVX-512 architecture setcc returns mask with i1 elements,
10339 // But there is no compare instruction for i8 and i16 elements.
10340 // We are not talking about 512-bit operands in this case, these
10341 // types are illegal.
10343 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10344 OpVT.getVectorElementType().getSizeInBits() >= 8))
10345 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10346 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10349 // We are handling one of the integer comparisons here. Since SSE only has
10350 // GT and EQ comparisons for integer, swapping operands and multiple
10351 // operations may be required for some comparisons.
10353 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10354 bool Subus = false;
10356 switch (SetCCOpcode) {
10357 default: llvm_unreachable("Unexpected SETCC condition");
10358 case ISD::SETNE: Invert = true;
10359 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10360 case ISD::SETLT: Swap = true;
10361 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10362 case ISD::SETGE: Swap = true;
10363 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10364 Invert = true; break;
10365 case ISD::SETULT: Swap = true;
10366 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10367 FlipSigns = true; break;
10368 case ISD::SETUGE: Swap = true;
10369 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10370 FlipSigns = true; Invert = true; break;
10373 // Special case: Use min/max operations for SETULE/SETUGE
10374 MVT VET = VT.getVectorElementType();
10376 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10377 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10380 switch (SetCCOpcode) {
10382 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10383 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10386 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10389 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10390 if (!MinMax && hasSubus) {
10391 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10393 // t = psubus Op0, Op1
10394 // pcmpeq t, <0..0>
10395 switch (SetCCOpcode) {
10397 case ISD::SETULT: {
10398 // If the comparison is against a constant we can turn this into a
10399 // setule. With psubus, setule does not require a swap. This is
10400 // beneficial because the constant in the register is no longer
10401 // destructed as the destination so it can be hoisted out of a loop.
10402 // Only do this pre-AVX since vpcmp* is no longer destructive.
10403 if (Subtarget->hasAVX())
10405 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10406 if (ULEOp1.getNode()) {
10408 Subus = true; Invert = false; Swap = false;
10412 // Psubus is better than flip-sign because it requires no inversion.
10413 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10414 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10418 Opc = X86ISD::SUBUS;
10424 std::swap(Op0, Op1);
10426 // Check that the operation in question is available (most are plain SSE2,
10427 // but PCMPGTQ and PCMPEQQ have different requirements).
10428 if (VT == MVT::v2i64) {
10429 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10430 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10432 // First cast everything to the right type.
10433 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10434 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10436 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10437 // bits of the inputs before performing those operations. The lower
10438 // compare is always unsigned.
10441 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10443 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10444 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10445 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10446 Sign, Zero, Sign, Zero);
10448 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10449 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10451 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10452 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10453 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10455 // Create masks for only the low parts/high parts of the 64 bit integers.
10456 static const int MaskHi[] = { 1, 1, 3, 3 };
10457 static const int MaskLo[] = { 0, 0, 2, 2 };
10458 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10459 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10460 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10462 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10463 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10466 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10468 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10471 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10472 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10473 // pcmpeqd + pshufd + pand.
10474 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10476 // First cast everything to the right type.
10477 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10478 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10481 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10483 // Make sure the lower and upper halves are both all-ones.
10484 static const int Mask[] = { 1, 0, 3, 2 };
10485 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10486 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10489 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10491 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10495 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10496 // bits of the inputs before performing those operations.
10498 EVT EltVT = VT.getVectorElementType();
10499 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10500 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10501 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10504 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10506 // If the logical-not of the result is required, perform that now.
10508 Result = DAG.getNOT(dl, Result, VT);
10511 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10514 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10515 getZeroVector(VT, Subtarget, DAG, dl));
10520 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10522 MVT VT = Op.getSimpleValueType();
10524 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10526 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10527 && "SetCC type must be 8-bit or 1-bit integer");
10528 SDValue Op0 = Op.getOperand(0);
10529 SDValue Op1 = Op.getOperand(1);
10531 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10533 // Optimize to BT if possible.
10534 // Lower (X & (1 << N)) == 0 to BT(X, N).
10535 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10536 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10537 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10538 Op1.getOpcode() == ISD::Constant &&
10539 cast<ConstantSDNode>(Op1)->isNullValue() &&
10540 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10541 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10542 if (NewSetCC.getNode())
10546 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10548 if (Op1.getOpcode() == ISD::Constant &&
10549 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10550 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10551 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10553 // If the input is a setcc, then reuse the input setcc or use a new one with
10554 // the inverted condition.
10555 if (Op0.getOpcode() == X86ISD::SETCC) {
10556 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10557 bool Invert = (CC == ISD::SETNE) ^
10558 cast<ConstantSDNode>(Op1)->isNullValue();
10562 CCode = X86::GetOppositeBranchCondition(CCode);
10563 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10564 DAG.getConstant(CCode, MVT::i8),
10565 Op0.getOperand(1));
10567 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10571 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10572 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10573 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10575 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10576 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10579 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10580 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10581 if (X86CC == X86::COND_INVALID)
10584 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10585 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10586 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10587 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10589 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10593 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10594 static bool isX86LogicalCmp(SDValue Op) {
10595 unsigned Opc = Op.getNode()->getOpcode();
10596 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10597 Opc == X86ISD::SAHF)
10599 if (Op.getResNo() == 1 &&
10600 (Opc == X86ISD::ADD ||
10601 Opc == X86ISD::SUB ||
10602 Opc == X86ISD::ADC ||
10603 Opc == X86ISD::SBB ||
10604 Opc == X86ISD::SMUL ||
10605 Opc == X86ISD::UMUL ||
10606 Opc == X86ISD::INC ||
10607 Opc == X86ISD::DEC ||
10608 Opc == X86ISD::OR ||
10609 Opc == X86ISD::XOR ||
10610 Opc == X86ISD::AND))
10613 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10619 static bool isZero(SDValue V) {
10620 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10621 return C && C->isNullValue();
10624 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10625 if (V.getOpcode() != ISD::TRUNCATE)
10628 SDValue VOp0 = V.getOperand(0);
10629 unsigned InBits = VOp0.getValueSizeInBits();
10630 unsigned Bits = V.getValueSizeInBits();
10631 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10634 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10635 bool addTest = true;
10636 SDValue Cond = Op.getOperand(0);
10637 SDValue Op1 = Op.getOperand(1);
10638 SDValue Op2 = Op.getOperand(2);
10640 EVT VT = Op1.getValueType();
10643 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10644 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10645 // sequence later on.
10646 if (Cond.getOpcode() == ISD::SETCC &&
10647 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10648 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10649 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10650 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10651 int SSECC = translateX86FSETCC(
10652 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10655 if (Subtarget->hasAVX512()) {
10656 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10657 DAG.getConstant(SSECC, MVT::i8));
10658 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10660 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10661 DAG.getConstant(SSECC, MVT::i8));
10662 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10663 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10664 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10668 if (Cond.getOpcode() == ISD::SETCC) {
10669 SDValue NewCond = LowerSETCC(Cond, DAG);
10670 if (NewCond.getNode())
10674 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10675 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10676 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10677 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10678 if (Cond.getOpcode() == X86ISD::SETCC &&
10679 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10680 isZero(Cond.getOperand(1).getOperand(1))) {
10681 SDValue Cmp = Cond.getOperand(1);
10683 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10685 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10686 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10687 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10689 SDValue CmpOp0 = Cmp.getOperand(0);
10690 // Apply further optimizations for special cases
10691 // (select (x != 0), -1, 0) -> neg & sbb
10692 // (select (x == 0), 0, -1) -> neg & sbb
10693 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10694 if (YC->isNullValue() &&
10695 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10696 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10697 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10698 DAG.getConstant(0, CmpOp0.getValueType()),
10700 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10701 DAG.getConstant(X86::COND_B, MVT::i8),
10702 SDValue(Neg.getNode(), 1));
10706 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10707 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10708 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10710 SDValue Res = // Res = 0 or -1.
10711 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10712 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10714 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10715 Res = DAG.getNOT(DL, Res, Res.getValueType());
10717 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10718 if (!N2C || !N2C->isNullValue())
10719 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10724 // Look past (and (setcc_carry (cmp ...)), 1).
10725 if (Cond.getOpcode() == ISD::AND &&
10726 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10727 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10728 if (C && C->getAPIntValue() == 1)
10729 Cond = Cond.getOperand(0);
10732 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10733 // setting operand in place of the X86ISD::SETCC.
10734 unsigned CondOpcode = Cond.getOpcode();
10735 if (CondOpcode == X86ISD::SETCC ||
10736 CondOpcode == X86ISD::SETCC_CARRY) {
10737 CC = Cond.getOperand(0);
10739 SDValue Cmp = Cond.getOperand(1);
10740 unsigned Opc = Cmp.getOpcode();
10741 MVT VT = Op.getSimpleValueType();
10743 bool IllegalFPCMov = false;
10744 if (VT.isFloatingPoint() && !VT.isVector() &&
10745 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10746 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10748 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10749 Opc == X86ISD::BT) { // FIXME
10753 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10754 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10755 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10756 Cond.getOperand(0).getValueType() != MVT::i8)) {
10757 SDValue LHS = Cond.getOperand(0);
10758 SDValue RHS = Cond.getOperand(1);
10759 unsigned X86Opcode;
10762 switch (CondOpcode) {
10763 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10764 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10765 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10766 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10767 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10768 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10769 default: llvm_unreachable("unexpected overflowing operator");
10771 if (CondOpcode == ISD::UMULO)
10772 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10775 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10777 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10779 if (CondOpcode == ISD::UMULO)
10780 Cond = X86Op.getValue(2);
10782 Cond = X86Op.getValue(1);
10784 CC = DAG.getConstant(X86Cond, MVT::i8);
10789 // Look pass the truncate if the high bits are known zero.
10790 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10791 Cond = Cond.getOperand(0);
10793 // We know the result of AND is compared against zero. Try to match
10795 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10796 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10797 if (NewSetCC.getNode()) {
10798 CC = NewSetCC.getOperand(0);
10799 Cond = NewSetCC.getOperand(1);
10806 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10807 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10810 // a < b ? -1 : 0 -> RES = ~setcc_carry
10811 // a < b ? 0 : -1 -> RES = setcc_carry
10812 // a >= b ? -1 : 0 -> RES = setcc_carry
10813 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10814 if (Cond.getOpcode() == X86ISD::SUB) {
10815 Cond = ConvertCmpIfNecessary(Cond, DAG);
10816 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10818 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10819 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10820 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10821 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10822 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10823 return DAG.getNOT(DL, Res, Res.getValueType());
10828 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10829 // widen the cmov and push the truncate through. This avoids introducing a new
10830 // branch during isel and doesn't add any extensions.
10831 if (Op.getValueType() == MVT::i8 &&
10832 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10833 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10834 if (T1.getValueType() == T2.getValueType() &&
10835 // Blacklist CopyFromReg to avoid partial register stalls.
10836 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10837 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10838 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10839 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10843 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10844 // condition is true.
10845 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10846 SDValue Ops[] = { Op2, Op1, CC, Cond };
10847 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10850 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10851 MVT VT = Op->getSimpleValueType(0);
10852 SDValue In = Op->getOperand(0);
10853 MVT InVT = In.getSimpleValueType();
10856 unsigned int NumElts = VT.getVectorNumElements();
10857 if (NumElts != 8 && NumElts != 16)
10860 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10861 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10863 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10864 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10866 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10867 Constant *C = ConstantInt::get(*DAG.getContext(),
10868 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10870 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10871 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10872 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10873 MachinePointerInfo::getConstantPool(),
10874 false, false, false, Alignment);
10875 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10876 if (VT.is512BitVector())
10878 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10881 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10882 SelectionDAG &DAG) {
10883 MVT VT = Op->getSimpleValueType(0);
10884 SDValue In = Op->getOperand(0);
10885 MVT InVT = In.getSimpleValueType();
10888 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10889 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10891 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10892 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10893 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10896 if (Subtarget->hasInt256())
10897 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10899 // Optimize vectors in AVX mode
10900 // Sign extend v8i16 to v8i32 and
10903 // Divide input vector into two parts
10904 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10905 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10906 // concat the vectors to original VT
10908 unsigned NumElems = InVT.getVectorNumElements();
10909 SDValue Undef = DAG.getUNDEF(InVT);
10911 SmallVector<int,8> ShufMask1(NumElems, -1);
10912 for (unsigned i = 0; i != NumElems/2; ++i)
10915 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10917 SmallVector<int,8> ShufMask2(NumElems, -1);
10918 for (unsigned i = 0; i != NumElems/2; ++i)
10919 ShufMask2[i] = i + NumElems/2;
10921 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10923 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10924 VT.getVectorNumElements()/2);
10926 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10927 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10929 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10932 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10933 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10934 // from the AND / OR.
10935 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10936 Opc = Op.getOpcode();
10937 if (Opc != ISD::OR && Opc != ISD::AND)
10939 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10940 Op.getOperand(0).hasOneUse() &&
10941 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10942 Op.getOperand(1).hasOneUse());
10945 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10946 // 1 and that the SETCC node has a single use.
10947 static bool isXor1OfSetCC(SDValue Op) {
10948 if (Op.getOpcode() != ISD::XOR)
10950 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10951 if (N1C && N1C->getAPIntValue() == 1) {
10952 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10953 Op.getOperand(0).hasOneUse();
10958 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10959 bool addTest = true;
10960 SDValue Chain = Op.getOperand(0);
10961 SDValue Cond = Op.getOperand(1);
10962 SDValue Dest = Op.getOperand(2);
10965 bool Inverted = false;
10967 if (Cond.getOpcode() == ISD::SETCC) {
10968 // Check for setcc([su]{add,sub,mul}o == 0).
10969 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10970 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10971 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10972 Cond.getOperand(0).getResNo() == 1 &&
10973 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10974 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10975 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10976 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10977 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10978 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10980 Cond = Cond.getOperand(0);
10982 SDValue NewCond = LowerSETCC(Cond, DAG);
10983 if (NewCond.getNode())
10988 // FIXME: LowerXALUO doesn't handle these!!
10989 else if (Cond.getOpcode() == X86ISD::ADD ||
10990 Cond.getOpcode() == X86ISD::SUB ||
10991 Cond.getOpcode() == X86ISD::SMUL ||
10992 Cond.getOpcode() == X86ISD::UMUL)
10993 Cond = LowerXALUO(Cond, DAG);
10996 // Look pass (and (setcc_carry (cmp ...)), 1).
10997 if (Cond.getOpcode() == ISD::AND &&
10998 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10999 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11000 if (C && C->getAPIntValue() == 1)
11001 Cond = Cond.getOperand(0);
11004 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11005 // setting operand in place of the X86ISD::SETCC.
11006 unsigned CondOpcode = Cond.getOpcode();
11007 if (CondOpcode == X86ISD::SETCC ||
11008 CondOpcode == X86ISD::SETCC_CARRY) {
11009 CC = Cond.getOperand(0);
11011 SDValue Cmp = Cond.getOperand(1);
11012 unsigned Opc = Cmp.getOpcode();
11013 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11014 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11018 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11022 // These can only come from an arithmetic instruction with overflow,
11023 // e.g. SADDO, UADDO.
11024 Cond = Cond.getNode()->getOperand(1);
11030 CondOpcode = Cond.getOpcode();
11031 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11032 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11033 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11034 Cond.getOperand(0).getValueType() != MVT::i8)) {
11035 SDValue LHS = Cond.getOperand(0);
11036 SDValue RHS = Cond.getOperand(1);
11037 unsigned X86Opcode;
11040 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11041 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11043 switch (CondOpcode) {
11044 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11046 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11048 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11051 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11052 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11054 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11056 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11059 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11060 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11061 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11062 default: llvm_unreachable("unexpected overflowing operator");
11065 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11066 if (CondOpcode == ISD::UMULO)
11067 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11070 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11072 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11074 if (CondOpcode == ISD::UMULO)
11075 Cond = X86Op.getValue(2);
11077 Cond = X86Op.getValue(1);
11079 CC = DAG.getConstant(X86Cond, MVT::i8);
11083 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11084 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11085 if (CondOpc == ISD::OR) {
11086 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11087 // two branches instead of an explicit OR instruction with a
11089 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11090 isX86LogicalCmp(Cmp)) {
11091 CC = Cond.getOperand(0).getOperand(0);
11092 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11093 Chain, Dest, CC, Cmp);
11094 CC = Cond.getOperand(1).getOperand(0);
11098 } else { // ISD::AND
11099 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11100 // two branches instead of an explicit AND instruction with a
11101 // separate test. However, we only do this if this block doesn't
11102 // have a fall-through edge, because this requires an explicit
11103 // jmp when the condition is false.
11104 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11105 isX86LogicalCmp(Cmp) &&
11106 Op.getNode()->hasOneUse()) {
11107 X86::CondCode CCode =
11108 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11109 CCode = X86::GetOppositeBranchCondition(CCode);
11110 CC = DAG.getConstant(CCode, MVT::i8);
11111 SDNode *User = *Op.getNode()->use_begin();
11112 // Look for an unconditional branch following this conditional branch.
11113 // We need this because we need to reverse the successors in order
11114 // to implement FCMP_OEQ.
11115 if (User->getOpcode() == ISD::BR) {
11116 SDValue FalseBB = User->getOperand(1);
11118 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11119 assert(NewBR == User);
11123 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11124 Chain, Dest, CC, Cmp);
11125 X86::CondCode CCode =
11126 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11127 CCode = X86::GetOppositeBranchCondition(CCode);
11128 CC = DAG.getConstant(CCode, MVT::i8);
11134 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11135 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11136 // It should be transformed during dag combiner except when the condition
11137 // is set by a arithmetics with overflow node.
11138 X86::CondCode CCode =
11139 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11140 CCode = X86::GetOppositeBranchCondition(CCode);
11141 CC = DAG.getConstant(CCode, MVT::i8);
11142 Cond = Cond.getOperand(0).getOperand(1);
11144 } else if (Cond.getOpcode() == ISD::SETCC &&
11145 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11146 // For FCMP_OEQ, we can emit
11147 // two branches instead of an explicit AND instruction with a
11148 // separate test. However, we only do this if this block doesn't
11149 // have a fall-through edge, because this requires an explicit
11150 // jmp when the condition is false.
11151 if (Op.getNode()->hasOneUse()) {
11152 SDNode *User = *Op.getNode()->use_begin();
11153 // Look for an unconditional branch following this conditional branch.
11154 // We need this because we need to reverse the successors in order
11155 // to implement FCMP_OEQ.
11156 if (User->getOpcode() == ISD::BR) {
11157 SDValue FalseBB = User->getOperand(1);
11159 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11160 assert(NewBR == User);
11164 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11165 Cond.getOperand(0), Cond.getOperand(1));
11166 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11167 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11168 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11169 Chain, Dest, CC, Cmp);
11170 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11175 } else if (Cond.getOpcode() == ISD::SETCC &&
11176 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11177 // For FCMP_UNE, we can emit
11178 // two branches instead of an explicit AND instruction with a
11179 // separate test. However, we only do this if this block doesn't
11180 // have a fall-through edge, because this requires an explicit
11181 // jmp when the condition is false.
11182 if (Op.getNode()->hasOneUse()) {
11183 SDNode *User = *Op.getNode()->use_begin();
11184 // Look for an unconditional branch following this conditional branch.
11185 // We need this because we need to reverse the successors in order
11186 // to implement FCMP_UNE.
11187 if (User->getOpcode() == ISD::BR) {
11188 SDValue FalseBB = User->getOperand(1);
11190 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11191 assert(NewBR == User);
11194 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11195 Cond.getOperand(0), Cond.getOperand(1));
11196 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11197 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11198 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11199 Chain, Dest, CC, Cmp);
11200 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11210 // Look pass the truncate if the high bits are known zero.
11211 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11212 Cond = Cond.getOperand(0);
11214 // We know the result of AND is compared against zero. Try to match
11216 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11217 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11218 if (NewSetCC.getNode()) {
11219 CC = NewSetCC.getOperand(0);
11220 Cond = NewSetCC.getOperand(1);
11227 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11228 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11230 Cond = ConvertCmpIfNecessary(Cond, DAG);
11231 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11232 Chain, Dest, CC, Cond);
11235 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11236 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11237 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11238 // that the guard pages used by the OS virtual memory manager are allocated in
11239 // correct sequence.
11241 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11242 SelectionDAG &DAG) const {
11243 MachineFunction &MF = DAG.getMachineFunction();
11244 bool SplitStack = MF.shouldSplitStack();
11245 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11250 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11251 SDNode* Node = Op.getNode();
11253 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11254 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11255 " not tell us which reg is the stack pointer!");
11256 EVT VT = Node->getValueType(0);
11257 SDValue Tmp1 = SDValue(Node, 0);
11258 SDValue Tmp2 = SDValue(Node, 1);
11259 SDValue Tmp3 = Node->getOperand(2);
11260 SDValue Chain = Tmp1.getOperand(0);
11262 // Chain the dynamic stack allocation so that it doesn't modify the stack
11263 // pointer when other instructions are using the stack.
11264 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11267 SDValue Size = Tmp2.getOperand(1);
11268 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11269 Chain = SP.getValue(1);
11270 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11271 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11272 unsigned StackAlign = TFI.getStackAlignment();
11273 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11274 if (Align > StackAlign)
11275 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11276 DAG.getConstant(-(uint64_t)Align, VT));
11277 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11279 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11280 DAG.getIntPtrConstant(0, true), SDValue(),
11283 SDValue Ops[2] = { Tmp1, Tmp2 };
11284 return DAG.getMergeValues(Ops, 2, dl);
11288 SDValue Chain = Op.getOperand(0);
11289 SDValue Size = Op.getOperand(1);
11290 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11291 EVT VT = Op.getNode()->getValueType(0);
11293 bool Is64Bit = Subtarget->is64Bit();
11294 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11297 MachineRegisterInfo &MRI = MF.getRegInfo();
11300 // The 64 bit implementation of segmented stacks needs to clobber both r10
11301 // r11. This makes it impossible to use it along with nested parameters.
11302 const Function *F = MF.getFunction();
11304 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11306 if (I->hasNestAttr())
11307 report_fatal_error("Cannot use segmented stacks with functions that "
11308 "have nested arguments.");
11311 const TargetRegisterClass *AddrRegClass =
11312 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11313 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11314 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11315 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11316 DAG.getRegister(Vreg, SPTy));
11317 SDValue Ops1[2] = { Value, Chain };
11318 return DAG.getMergeValues(Ops1, 2, dl);
11321 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11323 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11324 Flag = Chain.getValue(1);
11325 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11327 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11329 const X86RegisterInfo *RegInfo =
11330 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11331 unsigned SPReg = RegInfo->getStackRegister();
11332 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11333 Chain = SP.getValue(1);
11336 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11337 DAG.getConstant(-(uint64_t)Align, VT));
11338 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11341 SDValue Ops1[2] = { SP, Chain };
11342 return DAG.getMergeValues(Ops1, 2, dl);
11346 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11347 MachineFunction &MF = DAG.getMachineFunction();
11348 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11350 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11353 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11354 // vastart just stores the address of the VarArgsFrameIndex slot into the
11355 // memory location argument.
11356 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11358 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11359 MachinePointerInfo(SV), false, false, 0);
11363 // gp_offset (0 - 6 * 8)
11364 // fp_offset (48 - 48 + 8 * 16)
11365 // overflow_arg_area (point to parameters coming in memory).
11367 SmallVector<SDValue, 8> MemOps;
11368 SDValue FIN = Op.getOperand(1);
11370 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11371 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11373 FIN, MachinePointerInfo(SV), false, false, 0);
11374 MemOps.push_back(Store);
11377 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11378 FIN, DAG.getIntPtrConstant(4));
11379 Store = DAG.getStore(Op.getOperand(0), DL,
11380 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11382 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11383 MemOps.push_back(Store);
11385 // Store ptr to overflow_arg_area
11386 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11387 FIN, DAG.getIntPtrConstant(4));
11388 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11390 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11391 MachinePointerInfo(SV, 8),
11393 MemOps.push_back(Store);
11395 // Store ptr to reg_save_area.
11396 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11397 FIN, DAG.getIntPtrConstant(8));
11398 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11400 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11401 MachinePointerInfo(SV, 16), false, false, 0);
11402 MemOps.push_back(Store);
11403 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11406 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11407 assert(Subtarget->is64Bit() &&
11408 "LowerVAARG only handles 64-bit va_arg!");
11409 assert((Subtarget->isTargetLinux() ||
11410 Subtarget->isTargetDarwin()) &&
11411 "Unhandled target in LowerVAARG");
11412 assert(Op.getNode()->getNumOperands() == 4);
11413 SDValue Chain = Op.getOperand(0);
11414 SDValue SrcPtr = Op.getOperand(1);
11415 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11416 unsigned Align = Op.getConstantOperandVal(3);
11419 EVT ArgVT = Op.getNode()->getValueType(0);
11420 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11421 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11424 // Decide which area this value should be read from.
11425 // TODO: Implement the AMD64 ABI in its entirety. This simple
11426 // selection mechanism works only for the basic types.
11427 if (ArgVT == MVT::f80) {
11428 llvm_unreachable("va_arg for f80 not yet implemented");
11429 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11430 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11431 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11432 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11434 llvm_unreachable("Unhandled argument type in LowerVAARG");
11437 if (ArgMode == 2) {
11438 // Sanity Check: Make sure using fp_offset makes sense.
11439 assert(!getTargetMachine().Options.UseSoftFloat &&
11440 !(DAG.getMachineFunction()
11441 .getFunction()->getAttributes()
11442 .hasAttribute(AttributeSet::FunctionIndex,
11443 Attribute::NoImplicitFloat)) &&
11444 Subtarget->hasSSE1());
11447 // Insert VAARG_64 node into the DAG
11448 // VAARG_64 returns two values: Variable Argument Address, Chain
11449 SmallVector<SDValue, 11> InstOps;
11450 InstOps.push_back(Chain);
11451 InstOps.push_back(SrcPtr);
11452 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11453 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11454 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11455 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11456 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11457 VTs, InstOps, MVT::i64,
11458 MachinePointerInfo(SV),
11460 /*Volatile=*/false,
11462 /*WriteMem=*/true);
11463 Chain = VAARG.getValue(1);
11465 // Load the next argument and return it
11466 return DAG.getLoad(ArgVT, dl,
11469 MachinePointerInfo(),
11470 false, false, false, 0);
11473 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11474 SelectionDAG &DAG) {
11475 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11476 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11477 SDValue Chain = Op.getOperand(0);
11478 SDValue DstPtr = Op.getOperand(1);
11479 SDValue SrcPtr = Op.getOperand(2);
11480 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11481 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11484 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11485 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11487 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11490 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11491 // amount is a constant. Takes immediate version of shift as input.
11492 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11493 SDValue SrcOp, uint64_t ShiftAmt,
11494 SelectionDAG &DAG) {
11495 MVT ElementType = VT.getVectorElementType();
11497 // Check for ShiftAmt >= element width
11498 if (ShiftAmt >= ElementType.getSizeInBits()) {
11499 if (Opc == X86ISD::VSRAI)
11500 ShiftAmt = ElementType.getSizeInBits() - 1;
11502 return DAG.getConstant(0, VT);
11505 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11506 && "Unknown target vector shift-by-constant node");
11508 // Fold this packed vector shift into a build vector if SrcOp is a
11509 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11510 if (VT == SrcOp.getSimpleValueType() &&
11511 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11512 SmallVector<SDValue, 8> Elts;
11513 unsigned NumElts = SrcOp->getNumOperands();
11514 ConstantSDNode *ND;
11517 default: llvm_unreachable(0);
11518 case X86ISD::VSHLI:
11519 for (unsigned i=0; i!=NumElts; ++i) {
11520 SDValue CurrentOp = SrcOp->getOperand(i);
11521 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11522 Elts.push_back(CurrentOp);
11525 ND = cast<ConstantSDNode>(CurrentOp);
11526 const APInt &C = ND->getAPIntValue();
11527 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11530 case X86ISD::VSRLI:
11531 for (unsigned i=0; i!=NumElts; ++i) {
11532 SDValue CurrentOp = SrcOp->getOperand(i);
11533 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11534 Elts.push_back(CurrentOp);
11537 ND = cast<ConstantSDNode>(CurrentOp);
11538 const APInt &C = ND->getAPIntValue();
11539 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11542 case X86ISD::VSRAI:
11543 for (unsigned i=0; i!=NumElts; ++i) {
11544 SDValue CurrentOp = SrcOp->getOperand(i);
11545 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11546 Elts.push_back(CurrentOp);
11549 ND = cast<ConstantSDNode>(CurrentOp);
11550 const APInt &C = ND->getAPIntValue();
11551 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11556 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11559 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11562 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11563 // may or may not be a constant. Takes immediate version of shift as input.
11564 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11565 SDValue SrcOp, SDValue ShAmt,
11566 SelectionDAG &DAG) {
11567 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11569 // Catch shift-by-constant.
11570 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11571 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11572 CShAmt->getZExtValue(), DAG);
11574 // Change opcode to non-immediate version
11576 default: llvm_unreachable("Unknown target vector shift node");
11577 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11578 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11579 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11582 // Need to build a vector containing shift amount
11583 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11586 ShOps[1] = DAG.getConstant(0, MVT::i32);
11587 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11588 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11590 // The return type has to be a 128-bit type with the same element
11591 // type as the input type.
11592 MVT EltVT = VT.getVectorElementType();
11593 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11595 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11596 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11599 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11601 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11603 default: return SDValue(); // Don't custom lower most intrinsics.
11604 // Comparison intrinsics.
11605 case Intrinsic::x86_sse_comieq_ss:
11606 case Intrinsic::x86_sse_comilt_ss:
11607 case Intrinsic::x86_sse_comile_ss:
11608 case Intrinsic::x86_sse_comigt_ss:
11609 case Intrinsic::x86_sse_comige_ss:
11610 case Intrinsic::x86_sse_comineq_ss:
11611 case Intrinsic::x86_sse_ucomieq_ss:
11612 case Intrinsic::x86_sse_ucomilt_ss:
11613 case Intrinsic::x86_sse_ucomile_ss:
11614 case Intrinsic::x86_sse_ucomigt_ss:
11615 case Intrinsic::x86_sse_ucomige_ss:
11616 case Intrinsic::x86_sse_ucomineq_ss:
11617 case Intrinsic::x86_sse2_comieq_sd:
11618 case Intrinsic::x86_sse2_comilt_sd:
11619 case Intrinsic::x86_sse2_comile_sd:
11620 case Intrinsic::x86_sse2_comigt_sd:
11621 case Intrinsic::x86_sse2_comige_sd:
11622 case Intrinsic::x86_sse2_comineq_sd:
11623 case Intrinsic::x86_sse2_ucomieq_sd:
11624 case Intrinsic::x86_sse2_ucomilt_sd:
11625 case Intrinsic::x86_sse2_ucomile_sd:
11626 case Intrinsic::x86_sse2_ucomigt_sd:
11627 case Intrinsic::x86_sse2_ucomige_sd:
11628 case Intrinsic::x86_sse2_ucomineq_sd: {
11632 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11633 case Intrinsic::x86_sse_comieq_ss:
11634 case Intrinsic::x86_sse2_comieq_sd:
11635 Opc = X86ISD::COMI;
11638 case Intrinsic::x86_sse_comilt_ss:
11639 case Intrinsic::x86_sse2_comilt_sd:
11640 Opc = X86ISD::COMI;
11643 case Intrinsic::x86_sse_comile_ss:
11644 case Intrinsic::x86_sse2_comile_sd:
11645 Opc = X86ISD::COMI;
11648 case Intrinsic::x86_sse_comigt_ss:
11649 case Intrinsic::x86_sse2_comigt_sd:
11650 Opc = X86ISD::COMI;
11653 case Intrinsic::x86_sse_comige_ss:
11654 case Intrinsic::x86_sse2_comige_sd:
11655 Opc = X86ISD::COMI;
11658 case Intrinsic::x86_sse_comineq_ss:
11659 case Intrinsic::x86_sse2_comineq_sd:
11660 Opc = X86ISD::COMI;
11663 case Intrinsic::x86_sse_ucomieq_ss:
11664 case Intrinsic::x86_sse2_ucomieq_sd:
11665 Opc = X86ISD::UCOMI;
11668 case Intrinsic::x86_sse_ucomilt_ss:
11669 case Intrinsic::x86_sse2_ucomilt_sd:
11670 Opc = X86ISD::UCOMI;
11673 case Intrinsic::x86_sse_ucomile_ss:
11674 case Intrinsic::x86_sse2_ucomile_sd:
11675 Opc = X86ISD::UCOMI;
11678 case Intrinsic::x86_sse_ucomigt_ss:
11679 case Intrinsic::x86_sse2_ucomigt_sd:
11680 Opc = X86ISD::UCOMI;
11683 case Intrinsic::x86_sse_ucomige_ss:
11684 case Intrinsic::x86_sse2_ucomige_sd:
11685 Opc = X86ISD::UCOMI;
11688 case Intrinsic::x86_sse_ucomineq_ss:
11689 case Intrinsic::x86_sse2_ucomineq_sd:
11690 Opc = X86ISD::UCOMI;
11695 SDValue LHS = Op.getOperand(1);
11696 SDValue RHS = Op.getOperand(2);
11697 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11698 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11699 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11700 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11701 DAG.getConstant(X86CC, MVT::i8), Cond);
11702 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11705 // Arithmetic intrinsics.
11706 case Intrinsic::x86_sse2_pmulu_dq:
11707 case Intrinsic::x86_avx2_pmulu_dq:
11708 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11709 Op.getOperand(1), Op.getOperand(2));
11711 case Intrinsic::x86_sse41_pmuldq:
11712 case Intrinsic::x86_avx2_pmul_dq:
11713 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11714 Op.getOperand(1), Op.getOperand(2));
11716 case Intrinsic::x86_sse2_pmulhu_w:
11717 case Intrinsic::x86_avx2_pmulhu_w:
11718 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11719 Op.getOperand(1), Op.getOperand(2));
11721 case Intrinsic::x86_sse2_pmulh_w:
11722 case Intrinsic::x86_avx2_pmulh_w:
11723 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11724 Op.getOperand(1), Op.getOperand(2));
11726 // SSE2/AVX2 sub with unsigned saturation intrinsics
11727 case Intrinsic::x86_sse2_psubus_b:
11728 case Intrinsic::x86_sse2_psubus_w:
11729 case Intrinsic::x86_avx2_psubus_b:
11730 case Intrinsic::x86_avx2_psubus_w:
11731 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11732 Op.getOperand(1), Op.getOperand(2));
11734 // SSE3/AVX horizontal add/sub intrinsics
11735 case Intrinsic::x86_sse3_hadd_ps:
11736 case Intrinsic::x86_sse3_hadd_pd:
11737 case Intrinsic::x86_avx_hadd_ps_256:
11738 case Intrinsic::x86_avx_hadd_pd_256:
11739 case Intrinsic::x86_sse3_hsub_ps:
11740 case Intrinsic::x86_sse3_hsub_pd:
11741 case Intrinsic::x86_avx_hsub_ps_256:
11742 case Intrinsic::x86_avx_hsub_pd_256:
11743 case Intrinsic::x86_ssse3_phadd_w_128:
11744 case Intrinsic::x86_ssse3_phadd_d_128:
11745 case Intrinsic::x86_avx2_phadd_w:
11746 case Intrinsic::x86_avx2_phadd_d:
11747 case Intrinsic::x86_ssse3_phsub_w_128:
11748 case Intrinsic::x86_ssse3_phsub_d_128:
11749 case Intrinsic::x86_avx2_phsub_w:
11750 case Intrinsic::x86_avx2_phsub_d: {
11753 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11754 case Intrinsic::x86_sse3_hadd_ps:
11755 case Intrinsic::x86_sse3_hadd_pd:
11756 case Intrinsic::x86_avx_hadd_ps_256:
11757 case Intrinsic::x86_avx_hadd_pd_256:
11758 Opcode = X86ISD::FHADD;
11760 case Intrinsic::x86_sse3_hsub_ps:
11761 case Intrinsic::x86_sse3_hsub_pd:
11762 case Intrinsic::x86_avx_hsub_ps_256:
11763 case Intrinsic::x86_avx_hsub_pd_256:
11764 Opcode = X86ISD::FHSUB;
11766 case Intrinsic::x86_ssse3_phadd_w_128:
11767 case Intrinsic::x86_ssse3_phadd_d_128:
11768 case Intrinsic::x86_avx2_phadd_w:
11769 case Intrinsic::x86_avx2_phadd_d:
11770 Opcode = X86ISD::HADD;
11772 case Intrinsic::x86_ssse3_phsub_w_128:
11773 case Intrinsic::x86_ssse3_phsub_d_128:
11774 case Intrinsic::x86_avx2_phsub_w:
11775 case Intrinsic::x86_avx2_phsub_d:
11776 Opcode = X86ISD::HSUB;
11779 return DAG.getNode(Opcode, dl, Op.getValueType(),
11780 Op.getOperand(1), Op.getOperand(2));
11783 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11784 case Intrinsic::x86_sse2_pmaxu_b:
11785 case Intrinsic::x86_sse41_pmaxuw:
11786 case Intrinsic::x86_sse41_pmaxud:
11787 case Intrinsic::x86_avx2_pmaxu_b:
11788 case Intrinsic::x86_avx2_pmaxu_w:
11789 case Intrinsic::x86_avx2_pmaxu_d:
11790 case Intrinsic::x86_sse2_pminu_b:
11791 case Intrinsic::x86_sse41_pminuw:
11792 case Intrinsic::x86_sse41_pminud:
11793 case Intrinsic::x86_avx2_pminu_b:
11794 case Intrinsic::x86_avx2_pminu_w:
11795 case Intrinsic::x86_avx2_pminu_d:
11796 case Intrinsic::x86_sse41_pmaxsb:
11797 case Intrinsic::x86_sse2_pmaxs_w:
11798 case Intrinsic::x86_sse41_pmaxsd:
11799 case Intrinsic::x86_avx2_pmaxs_b:
11800 case Intrinsic::x86_avx2_pmaxs_w:
11801 case Intrinsic::x86_avx2_pmaxs_d:
11802 case Intrinsic::x86_sse41_pminsb:
11803 case Intrinsic::x86_sse2_pmins_w:
11804 case Intrinsic::x86_sse41_pminsd:
11805 case Intrinsic::x86_avx2_pmins_b:
11806 case Intrinsic::x86_avx2_pmins_w:
11807 case Intrinsic::x86_avx2_pmins_d: {
11810 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11811 case Intrinsic::x86_sse2_pmaxu_b:
11812 case Intrinsic::x86_sse41_pmaxuw:
11813 case Intrinsic::x86_sse41_pmaxud:
11814 case Intrinsic::x86_avx2_pmaxu_b:
11815 case Intrinsic::x86_avx2_pmaxu_w:
11816 case Intrinsic::x86_avx2_pmaxu_d:
11817 Opcode = X86ISD::UMAX;
11819 case Intrinsic::x86_sse2_pminu_b:
11820 case Intrinsic::x86_sse41_pminuw:
11821 case Intrinsic::x86_sse41_pminud:
11822 case Intrinsic::x86_avx2_pminu_b:
11823 case Intrinsic::x86_avx2_pminu_w:
11824 case Intrinsic::x86_avx2_pminu_d:
11825 Opcode = X86ISD::UMIN;
11827 case Intrinsic::x86_sse41_pmaxsb:
11828 case Intrinsic::x86_sse2_pmaxs_w:
11829 case Intrinsic::x86_sse41_pmaxsd:
11830 case Intrinsic::x86_avx2_pmaxs_b:
11831 case Intrinsic::x86_avx2_pmaxs_w:
11832 case Intrinsic::x86_avx2_pmaxs_d:
11833 Opcode = X86ISD::SMAX;
11835 case Intrinsic::x86_sse41_pminsb:
11836 case Intrinsic::x86_sse2_pmins_w:
11837 case Intrinsic::x86_sse41_pminsd:
11838 case Intrinsic::x86_avx2_pmins_b:
11839 case Intrinsic::x86_avx2_pmins_w:
11840 case Intrinsic::x86_avx2_pmins_d:
11841 Opcode = X86ISD::SMIN;
11844 return DAG.getNode(Opcode, dl, Op.getValueType(),
11845 Op.getOperand(1), Op.getOperand(2));
11848 // SSE/SSE2/AVX floating point max/min intrinsics.
11849 case Intrinsic::x86_sse_max_ps:
11850 case Intrinsic::x86_sse2_max_pd:
11851 case Intrinsic::x86_avx_max_ps_256:
11852 case Intrinsic::x86_avx_max_pd_256:
11853 case Intrinsic::x86_sse_min_ps:
11854 case Intrinsic::x86_sse2_min_pd:
11855 case Intrinsic::x86_avx_min_ps_256:
11856 case Intrinsic::x86_avx_min_pd_256: {
11859 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11860 case Intrinsic::x86_sse_max_ps:
11861 case Intrinsic::x86_sse2_max_pd:
11862 case Intrinsic::x86_avx_max_ps_256:
11863 case Intrinsic::x86_avx_max_pd_256:
11864 Opcode = X86ISD::FMAX;
11866 case Intrinsic::x86_sse_min_ps:
11867 case Intrinsic::x86_sse2_min_pd:
11868 case Intrinsic::x86_avx_min_ps_256:
11869 case Intrinsic::x86_avx_min_pd_256:
11870 Opcode = X86ISD::FMIN;
11873 return DAG.getNode(Opcode, dl, Op.getValueType(),
11874 Op.getOperand(1), Op.getOperand(2));
11877 // AVX2 variable shift intrinsics
11878 case Intrinsic::x86_avx2_psllv_d:
11879 case Intrinsic::x86_avx2_psllv_q:
11880 case Intrinsic::x86_avx2_psllv_d_256:
11881 case Intrinsic::x86_avx2_psllv_q_256:
11882 case Intrinsic::x86_avx2_psrlv_d:
11883 case Intrinsic::x86_avx2_psrlv_q:
11884 case Intrinsic::x86_avx2_psrlv_d_256:
11885 case Intrinsic::x86_avx2_psrlv_q_256:
11886 case Intrinsic::x86_avx2_psrav_d:
11887 case Intrinsic::x86_avx2_psrav_d_256: {
11890 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11891 case Intrinsic::x86_avx2_psllv_d:
11892 case Intrinsic::x86_avx2_psllv_q:
11893 case Intrinsic::x86_avx2_psllv_d_256:
11894 case Intrinsic::x86_avx2_psllv_q_256:
11897 case Intrinsic::x86_avx2_psrlv_d:
11898 case Intrinsic::x86_avx2_psrlv_q:
11899 case Intrinsic::x86_avx2_psrlv_d_256:
11900 case Intrinsic::x86_avx2_psrlv_q_256:
11903 case Intrinsic::x86_avx2_psrav_d:
11904 case Intrinsic::x86_avx2_psrav_d_256:
11908 return DAG.getNode(Opcode, dl, Op.getValueType(),
11909 Op.getOperand(1), Op.getOperand(2));
11912 case Intrinsic::x86_ssse3_pshuf_b_128:
11913 case Intrinsic::x86_avx2_pshuf_b:
11914 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11915 Op.getOperand(1), Op.getOperand(2));
11917 case Intrinsic::x86_ssse3_psign_b_128:
11918 case Intrinsic::x86_ssse3_psign_w_128:
11919 case Intrinsic::x86_ssse3_psign_d_128:
11920 case Intrinsic::x86_avx2_psign_b:
11921 case Intrinsic::x86_avx2_psign_w:
11922 case Intrinsic::x86_avx2_psign_d:
11923 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11924 Op.getOperand(1), Op.getOperand(2));
11926 case Intrinsic::x86_sse41_insertps:
11927 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11928 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11930 case Intrinsic::x86_avx_vperm2f128_ps_256:
11931 case Intrinsic::x86_avx_vperm2f128_pd_256:
11932 case Intrinsic::x86_avx_vperm2f128_si_256:
11933 case Intrinsic::x86_avx2_vperm2i128:
11934 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11935 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11937 case Intrinsic::x86_avx2_permd:
11938 case Intrinsic::x86_avx2_permps:
11939 // Operands intentionally swapped. Mask is last operand to intrinsic,
11940 // but second operand for node/instruction.
11941 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11942 Op.getOperand(2), Op.getOperand(1));
11944 case Intrinsic::x86_sse_sqrt_ps:
11945 case Intrinsic::x86_sse2_sqrt_pd:
11946 case Intrinsic::x86_avx_sqrt_ps_256:
11947 case Intrinsic::x86_avx_sqrt_pd_256:
11948 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11950 // ptest and testp intrinsics. The intrinsic these come from are designed to
11951 // return an integer value, not just an instruction so lower it to the ptest
11952 // or testp pattern and a setcc for the result.
11953 case Intrinsic::x86_sse41_ptestz:
11954 case Intrinsic::x86_sse41_ptestc:
11955 case Intrinsic::x86_sse41_ptestnzc:
11956 case Intrinsic::x86_avx_ptestz_256:
11957 case Intrinsic::x86_avx_ptestc_256:
11958 case Intrinsic::x86_avx_ptestnzc_256:
11959 case Intrinsic::x86_avx_vtestz_ps:
11960 case Intrinsic::x86_avx_vtestc_ps:
11961 case Intrinsic::x86_avx_vtestnzc_ps:
11962 case Intrinsic::x86_avx_vtestz_pd:
11963 case Intrinsic::x86_avx_vtestc_pd:
11964 case Intrinsic::x86_avx_vtestnzc_pd:
11965 case Intrinsic::x86_avx_vtestz_ps_256:
11966 case Intrinsic::x86_avx_vtestc_ps_256:
11967 case Intrinsic::x86_avx_vtestnzc_ps_256:
11968 case Intrinsic::x86_avx_vtestz_pd_256:
11969 case Intrinsic::x86_avx_vtestc_pd_256:
11970 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11971 bool IsTestPacked = false;
11974 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11975 case Intrinsic::x86_avx_vtestz_ps:
11976 case Intrinsic::x86_avx_vtestz_pd:
11977 case Intrinsic::x86_avx_vtestz_ps_256:
11978 case Intrinsic::x86_avx_vtestz_pd_256:
11979 IsTestPacked = true; // Fallthrough
11980 case Intrinsic::x86_sse41_ptestz:
11981 case Intrinsic::x86_avx_ptestz_256:
11983 X86CC = X86::COND_E;
11985 case Intrinsic::x86_avx_vtestc_ps:
11986 case Intrinsic::x86_avx_vtestc_pd:
11987 case Intrinsic::x86_avx_vtestc_ps_256:
11988 case Intrinsic::x86_avx_vtestc_pd_256:
11989 IsTestPacked = true; // Fallthrough
11990 case Intrinsic::x86_sse41_ptestc:
11991 case Intrinsic::x86_avx_ptestc_256:
11993 X86CC = X86::COND_B;
11995 case Intrinsic::x86_avx_vtestnzc_ps:
11996 case Intrinsic::x86_avx_vtestnzc_pd:
11997 case Intrinsic::x86_avx_vtestnzc_ps_256:
11998 case Intrinsic::x86_avx_vtestnzc_pd_256:
11999 IsTestPacked = true; // Fallthrough
12000 case Intrinsic::x86_sse41_ptestnzc:
12001 case Intrinsic::x86_avx_ptestnzc_256:
12003 X86CC = X86::COND_A;
12007 SDValue LHS = Op.getOperand(1);
12008 SDValue RHS = Op.getOperand(2);
12009 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12010 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12011 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12012 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12013 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12015 case Intrinsic::x86_avx512_kortestz_w:
12016 case Intrinsic::x86_avx512_kortestc_w: {
12017 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12018 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12019 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12020 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12021 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12022 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12023 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12026 // SSE/AVX shift intrinsics
12027 case Intrinsic::x86_sse2_psll_w:
12028 case Intrinsic::x86_sse2_psll_d:
12029 case Intrinsic::x86_sse2_psll_q:
12030 case Intrinsic::x86_avx2_psll_w:
12031 case Intrinsic::x86_avx2_psll_d:
12032 case Intrinsic::x86_avx2_psll_q:
12033 case Intrinsic::x86_sse2_psrl_w:
12034 case Intrinsic::x86_sse2_psrl_d:
12035 case Intrinsic::x86_sse2_psrl_q:
12036 case Intrinsic::x86_avx2_psrl_w:
12037 case Intrinsic::x86_avx2_psrl_d:
12038 case Intrinsic::x86_avx2_psrl_q:
12039 case Intrinsic::x86_sse2_psra_w:
12040 case Intrinsic::x86_sse2_psra_d:
12041 case Intrinsic::x86_avx2_psra_w:
12042 case Intrinsic::x86_avx2_psra_d: {
12045 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12046 case Intrinsic::x86_sse2_psll_w:
12047 case Intrinsic::x86_sse2_psll_d:
12048 case Intrinsic::x86_sse2_psll_q:
12049 case Intrinsic::x86_avx2_psll_w:
12050 case Intrinsic::x86_avx2_psll_d:
12051 case Intrinsic::x86_avx2_psll_q:
12052 Opcode = X86ISD::VSHL;
12054 case Intrinsic::x86_sse2_psrl_w:
12055 case Intrinsic::x86_sse2_psrl_d:
12056 case Intrinsic::x86_sse2_psrl_q:
12057 case Intrinsic::x86_avx2_psrl_w:
12058 case Intrinsic::x86_avx2_psrl_d:
12059 case Intrinsic::x86_avx2_psrl_q:
12060 Opcode = X86ISD::VSRL;
12062 case Intrinsic::x86_sse2_psra_w:
12063 case Intrinsic::x86_sse2_psra_d:
12064 case Intrinsic::x86_avx2_psra_w:
12065 case Intrinsic::x86_avx2_psra_d:
12066 Opcode = X86ISD::VSRA;
12069 return DAG.getNode(Opcode, dl, Op.getValueType(),
12070 Op.getOperand(1), Op.getOperand(2));
12073 // SSE/AVX immediate shift intrinsics
12074 case Intrinsic::x86_sse2_pslli_w:
12075 case Intrinsic::x86_sse2_pslli_d:
12076 case Intrinsic::x86_sse2_pslli_q:
12077 case Intrinsic::x86_avx2_pslli_w:
12078 case Intrinsic::x86_avx2_pslli_d:
12079 case Intrinsic::x86_avx2_pslli_q:
12080 case Intrinsic::x86_sse2_psrli_w:
12081 case Intrinsic::x86_sse2_psrli_d:
12082 case Intrinsic::x86_sse2_psrli_q:
12083 case Intrinsic::x86_avx2_psrli_w:
12084 case Intrinsic::x86_avx2_psrli_d:
12085 case Intrinsic::x86_avx2_psrli_q:
12086 case Intrinsic::x86_sse2_psrai_w:
12087 case Intrinsic::x86_sse2_psrai_d:
12088 case Intrinsic::x86_avx2_psrai_w:
12089 case Intrinsic::x86_avx2_psrai_d: {
12092 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12093 case Intrinsic::x86_sse2_pslli_w:
12094 case Intrinsic::x86_sse2_pslli_d:
12095 case Intrinsic::x86_sse2_pslli_q:
12096 case Intrinsic::x86_avx2_pslli_w:
12097 case Intrinsic::x86_avx2_pslli_d:
12098 case Intrinsic::x86_avx2_pslli_q:
12099 Opcode = X86ISD::VSHLI;
12101 case Intrinsic::x86_sse2_psrli_w:
12102 case Intrinsic::x86_sse2_psrli_d:
12103 case Intrinsic::x86_sse2_psrli_q:
12104 case Intrinsic::x86_avx2_psrli_w:
12105 case Intrinsic::x86_avx2_psrli_d:
12106 case Intrinsic::x86_avx2_psrli_q:
12107 Opcode = X86ISD::VSRLI;
12109 case Intrinsic::x86_sse2_psrai_w:
12110 case Intrinsic::x86_sse2_psrai_d:
12111 case Intrinsic::x86_avx2_psrai_w:
12112 case Intrinsic::x86_avx2_psrai_d:
12113 Opcode = X86ISD::VSRAI;
12116 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12117 Op.getOperand(1), Op.getOperand(2), DAG);
12120 case Intrinsic::x86_sse42_pcmpistria128:
12121 case Intrinsic::x86_sse42_pcmpestria128:
12122 case Intrinsic::x86_sse42_pcmpistric128:
12123 case Intrinsic::x86_sse42_pcmpestric128:
12124 case Intrinsic::x86_sse42_pcmpistrio128:
12125 case Intrinsic::x86_sse42_pcmpestrio128:
12126 case Intrinsic::x86_sse42_pcmpistris128:
12127 case Intrinsic::x86_sse42_pcmpestris128:
12128 case Intrinsic::x86_sse42_pcmpistriz128:
12129 case Intrinsic::x86_sse42_pcmpestriz128: {
12133 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12134 case Intrinsic::x86_sse42_pcmpistria128:
12135 Opcode = X86ISD::PCMPISTRI;
12136 X86CC = X86::COND_A;
12138 case Intrinsic::x86_sse42_pcmpestria128:
12139 Opcode = X86ISD::PCMPESTRI;
12140 X86CC = X86::COND_A;
12142 case Intrinsic::x86_sse42_pcmpistric128:
12143 Opcode = X86ISD::PCMPISTRI;
12144 X86CC = X86::COND_B;
12146 case Intrinsic::x86_sse42_pcmpestric128:
12147 Opcode = X86ISD::PCMPESTRI;
12148 X86CC = X86::COND_B;
12150 case Intrinsic::x86_sse42_pcmpistrio128:
12151 Opcode = X86ISD::PCMPISTRI;
12152 X86CC = X86::COND_O;
12154 case Intrinsic::x86_sse42_pcmpestrio128:
12155 Opcode = X86ISD::PCMPESTRI;
12156 X86CC = X86::COND_O;
12158 case Intrinsic::x86_sse42_pcmpistris128:
12159 Opcode = X86ISD::PCMPISTRI;
12160 X86CC = X86::COND_S;
12162 case Intrinsic::x86_sse42_pcmpestris128:
12163 Opcode = X86ISD::PCMPESTRI;
12164 X86CC = X86::COND_S;
12166 case Intrinsic::x86_sse42_pcmpistriz128:
12167 Opcode = X86ISD::PCMPISTRI;
12168 X86CC = X86::COND_E;
12170 case Intrinsic::x86_sse42_pcmpestriz128:
12171 Opcode = X86ISD::PCMPESTRI;
12172 X86CC = X86::COND_E;
12175 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12176 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12177 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12178 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12179 DAG.getConstant(X86CC, MVT::i8),
12180 SDValue(PCMP.getNode(), 1));
12181 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12184 case Intrinsic::x86_sse42_pcmpistri128:
12185 case Intrinsic::x86_sse42_pcmpestri128: {
12187 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12188 Opcode = X86ISD::PCMPISTRI;
12190 Opcode = X86ISD::PCMPESTRI;
12192 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12193 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12194 return DAG.getNode(Opcode, dl, VTs, NewOps);
12196 case Intrinsic::x86_fma_vfmadd_ps:
12197 case Intrinsic::x86_fma_vfmadd_pd:
12198 case Intrinsic::x86_fma_vfmsub_ps:
12199 case Intrinsic::x86_fma_vfmsub_pd:
12200 case Intrinsic::x86_fma_vfnmadd_ps:
12201 case Intrinsic::x86_fma_vfnmadd_pd:
12202 case Intrinsic::x86_fma_vfnmsub_ps:
12203 case Intrinsic::x86_fma_vfnmsub_pd:
12204 case Intrinsic::x86_fma_vfmaddsub_ps:
12205 case Intrinsic::x86_fma_vfmaddsub_pd:
12206 case Intrinsic::x86_fma_vfmsubadd_ps:
12207 case Intrinsic::x86_fma_vfmsubadd_pd:
12208 case Intrinsic::x86_fma_vfmadd_ps_256:
12209 case Intrinsic::x86_fma_vfmadd_pd_256:
12210 case Intrinsic::x86_fma_vfmsub_ps_256:
12211 case Intrinsic::x86_fma_vfmsub_pd_256:
12212 case Intrinsic::x86_fma_vfnmadd_ps_256:
12213 case Intrinsic::x86_fma_vfnmadd_pd_256:
12214 case Intrinsic::x86_fma_vfnmsub_ps_256:
12215 case Intrinsic::x86_fma_vfnmsub_pd_256:
12216 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12217 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12218 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12219 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12220 case Intrinsic::x86_fma_vfmadd_ps_512:
12221 case Intrinsic::x86_fma_vfmadd_pd_512:
12222 case Intrinsic::x86_fma_vfmsub_ps_512:
12223 case Intrinsic::x86_fma_vfmsub_pd_512:
12224 case Intrinsic::x86_fma_vfnmadd_ps_512:
12225 case Intrinsic::x86_fma_vfnmadd_pd_512:
12226 case Intrinsic::x86_fma_vfnmsub_ps_512:
12227 case Intrinsic::x86_fma_vfnmsub_pd_512:
12228 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12229 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12230 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12231 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12234 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12235 case Intrinsic::x86_fma_vfmadd_ps:
12236 case Intrinsic::x86_fma_vfmadd_pd:
12237 case Intrinsic::x86_fma_vfmadd_ps_256:
12238 case Intrinsic::x86_fma_vfmadd_pd_256:
12239 case Intrinsic::x86_fma_vfmadd_ps_512:
12240 case Intrinsic::x86_fma_vfmadd_pd_512:
12241 Opc = X86ISD::FMADD;
12243 case Intrinsic::x86_fma_vfmsub_ps:
12244 case Intrinsic::x86_fma_vfmsub_pd:
12245 case Intrinsic::x86_fma_vfmsub_ps_256:
12246 case Intrinsic::x86_fma_vfmsub_pd_256:
12247 case Intrinsic::x86_fma_vfmsub_ps_512:
12248 case Intrinsic::x86_fma_vfmsub_pd_512:
12249 Opc = X86ISD::FMSUB;
12251 case Intrinsic::x86_fma_vfnmadd_ps:
12252 case Intrinsic::x86_fma_vfnmadd_pd:
12253 case Intrinsic::x86_fma_vfnmadd_ps_256:
12254 case Intrinsic::x86_fma_vfnmadd_pd_256:
12255 case Intrinsic::x86_fma_vfnmadd_ps_512:
12256 case Intrinsic::x86_fma_vfnmadd_pd_512:
12257 Opc = X86ISD::FNMADD;
12259 case Intrinsic::x86_fma_vfnmsub_ps:
12260 case Intrinsic::x86_fma_vfnmsub_pd:
12261 case Intrinsic::x86_fma_vfnmsub_ps_256:
12262 case Intrinsic::x86_fma_vfnmsub_pd_256:
12263 case Intrinsic::x86_fma_vfnmsub_ps_512:
12264 case Intrinsic::x86_fma_vfnmsub_pd_512:
12265 Opc = X86ISD::FNMSUB;
12267 case Intrinsic::x86_fma_vfmaddsub_ps:
12268 case Intrinsic::x86_fma_vfmaddsub_pd:
12269 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12270 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12271 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12272 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12273 Opc = X86ISD::FMADDSUB;
12275 case Intrinsic::x86_fma_vfmsubadd_ps:
12276 case Intrinsic::x86_fma_vfmsubadd_pd:
12277 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12278 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12279 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12280 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12281 Opc = X86ISD::FMSUBADD;
12285 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12286 Op.getOperand(2), Op.getOperand(3));
12291 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12292 SDValue Base, SDValue Index,
12293 SDValue ScaleOp, SDValue Chain,
12294 const X86Subtarget * Subtarget) {
12296 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12297 assert(C && "Invalid scale type");
12298 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12299 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12300 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12301 Index.getSimpleValueType().getVectorNumElements());
12302 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12303 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12304 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12305 SDValue Segment = DAG.getRegister(0, MVT::i32);
12306 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12307 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12308 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12309 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12312 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12313 SDValue Src, SDValue Mask, SDValue Base,
12314 SDValue Index, SDValue ScaleOp, SDValue Chain,
12315 const X86Subtarget * Subtarget) {
12317 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12318 assert(C && "Invalid scale type");
12319 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12320 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12321 Index.getSimpleValueType().getVectorNumElements());
12322 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12323 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12324 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12325 SDValue Segment = DAG.getRegister(0, MVT::i32);
12326 if (Src.getOpcode() == ISD::UNDEF)
12327 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12328 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12329 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12330 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12331 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12334 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12335 SDValue Src, SDValue Base, SDValue Index,
12336 SDValue ScaleOp, SDValue Chain) {
12338 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12339 assert(C && "Invalid scale type");
12340 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12341 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12342 SDValue Segment = DAG.getRegister(0, MVT::i32);
12343 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12344 Index.getSimpleValueType().getVectorNumElements());
12345 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12346 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12347 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12348 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12349 return SDValue(Res, 1);
12352 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12353 SDValue Src, SDValue Mask, SDValue Base,
12354 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12356 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12357 assert(C && "Invalid scale type");
12358 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12359 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12360 SDValue Segment = DAG.getRegister(0, MVT::i32);
12361 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12362 Index.getSimpleValueType().getVectorNumElements());
12363 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12364 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12365 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12366 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12367 return SDValue(Res, 1);
12370 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12371 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12372 // also used to custom lower READCYCLECOUNTER nodes.
12373 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12374 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12375 SmallVectorImpl<SDValue> &Results) {
12376 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12377 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12380 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12381 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12382 // and the EAX register is loaded with the low-order 32 bits.
12383 if (Subtarget->is64Bit()) {
12384 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12385 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12388 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12389 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12392 SDValue Chain = HI.getValue(1);
12394 if (Opcode == X86ISD::RDTSCP_DAG) {
12395 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12397 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12398 // the ECX register. Add 'ecx' explicitly to the chain.
12399 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12401 // Explicitly store the content of ECX at the location passed in input
12402 // to the 'rdtscp' intrinsic.
12403 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12404 MachinePointerInfo(), false, false, 0);
12407 if (Subtarget->is64Bit()) {
12408 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12409 // the EAX register is loaded with the low-order 32 bits.
12410 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12411 DAG.getConstant(32, MVT::i8));
12412 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12413 Results.push_back(Chain);
12417 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12418 SDValue Ops[] = { LO, HI };
12419 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12420 Results.push_back(Pair);
12421 Results.push_back(Chain);
12424 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12425 SelectionDAG &DAG) {
12426 SmallVector<SDValue, 2> Results;
12428 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12430 return DAG.getMergeValues(&Results[0], Results.size(), DL);
12433 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12434 SelectionDAG &DAG) {
12436 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12438 default: return SDValue(); // Don't custom lower most intrinsics.
12440 // RDRAND/RDSEED intrinsics.
12441 case Intrinsic::x86_rdrand_16:
12442 case Intrinsic::x86_rdrand_32:
12443 case Intrinsic::x86_rdrand_64:
12444 case Intrinsic::x86_rdseed_16:
12445 case Intrinsic::x86_rdseed_32:
12446 case Intrinsic::x86_rdseed_64: {
12447 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12448 IntNo == Intrinsic::x86_rdseed_32 ||
12449 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12451 // Emit the node with the right value type.
12452 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12453 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12455 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12456 // Otherwise return the value from Rand, which is always 0, casted to i32.
12457 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12458 DAG.getConstant(1, Op->getValueType(1)),
12459 DAG.getConstant(X86::COND_B, MVT::i32),
12460 SDValue(Result.getNode(), 1) };
12461 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12462 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12465 // Return { result, isValid, chain }.
12466 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12467 SDValue(Result.getNode(), 2));
12469 //int_gather(index, base, scale);
12470 case Intrinsic::x86_avx512_gather_qpd_512:
12471 case Intrinsic::x86_avx512_gather_qps_512:
12472 case Intrinsic::x86_avx512_gather_dpd_512:
12473 case Intrinsic::x86_avx512_gather_qpi_512:
12474 case Intrinsic::x86_avx512_gather_qpq_512:
12475 case Intrinsic::x86_avx512_gather_dpq_512:
12476 case Intrinsic::x86_avx512_gather_dps_512:
12477 case Intrinsic::x86_avx512_gather_dpi_512: {
12480 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12481 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12482 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12483 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12484 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12485 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12486 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12487 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12488 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12490 SDValue Chain = Op.getOperand(0);
12491 SDValue Index = Op.getOperand(2);
12492 SDValue Base = Op.getOperand(3);
12493 SDValue Scale = Op.getOperand(4);
12494 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12496 //int_gather_mask(v1, mask, index, base, scale);
12497 case Intrinsic::x86_avx512_gather_qps_mask_512:
12498 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12499 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12500 case Intrinsic::x86_avx512_gather_dps_mask_512:
12501 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12502 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12503 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12504 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12507 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12508 case Intrinsic::x86_avx512_gather_qps_mask_512:
12509 Opc = X86::VGATHERQPSZrm; break;
12510 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12511 Opc = X86::VGATHERQPDZrm; break;
12512 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12513 Opc = X86::VGATHERDPDZrm; break;
12514 case Intrinsic::x86_avx512_gather_dps_mask_512:
12515 Opc = X86::VGATHERDPSZrm; break;
12516 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12517 Opc = X86::VPGATHERQDZrm; break;
12518 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12519 Opc = X86::VPGATHERQQZrm; break;
12520 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12521 Opc = X86::VPGATHERDDZrm; break;
12522 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12523 Opc = X86::VPGATHERDQZrm; break;
12525 SDValue Chain = Op.getOperand(0);
12526 SDValue Src = Op.getOperand(2);
12527 SDValue Mask = Op.getOperand(3);
12528 SDValue Index = Op.getOperand(4);
12529 SDValue Base = Op.getOperand(5);
12530 SDValue Scale = Op.getOperand(6);
12531 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12534 //int_scatter(base, index, v1, scale);
12535 case Intrinsic::x86_avx512_scatter_qpd_512:
12536 case Intrinsic::x86_avx512_scatter_qps_512:
12537 case Intrinsic::x86_avx512_scatter_dpd_512:
12538 case Intrinsic::x86_avx512_scatter_qpi_512:
12539 case Intrinsic::x86_avx512_scatter_qpq_512:
12540 case Intrinsic::x86_avx512_scatter_dpq_512:
12541 case Intrinsic::x86_avx512_scatter_dps_512:
12542 case Intrinsic::x86_avx512_scatter_dpi_512: {
12545 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12546 case Intrinsic::x86_avx512_scatter_qpd_512:
12547 Opc = X86::VSCATTERQPDZmr; break;
12548 case Intrinsic::x86_avx512_scatter_qps_512:
12549 Opc = X86::VSCATTERQPSZmr; break;
12550 case Intrinsic::x86_avx512_scatter_dpd_512:
12551 Opc = X86::VSCATTERDPDZmr; break;
12552 case Intrinsic::x86_avx512_scatter_dps_512:
12553 Opc = X86::VSCATTERDPSZmr; break;
12554 case Intrinsic::x86_avx512_scatter_qpi_512:
12555 Opc = X86::VPSCATTERQDZmr; break;
12556 case Intrinsic::x86_avx512_scatter_qpq_512:
12557 Opc = X86::VPSCATTERQQZmr; break;
12558 case Intrinsic::x86_avx512_scatter_dpq_512:
12559 Opc = X86::VPSCATTERDQZmr; break;
12560 case Intrinsic::x86_avx512_scatter_dpi_512:
12561 Opc = X86::VPSCATTERDDZmr; break;
12563 SDValue Chain = Op.getOperand(0);
12564 SDValue Base = Op.getOperand(2);
12565 SDValue Index = Op.getOperand(3);
12566 SDValue Src = Op.getOperand(4);
12567 SDValue Scale = Op.getOperand(5);
12568 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12570 //int_scatter_mask(base, mask, index, v1, scale);
12571 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12572 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12573 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12574 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12575 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12576 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12577 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12578 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12581 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12582 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12583 Opc = X86::VSCATTERQPDZmr; break;
12584 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12585 Opc = X86::VSCATTERQPSZmr; break;
12586 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12587 Opc = X86::VSCATTERDPDZmr; break;
12588 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12589 Opc = X86::VSCATTERDPSZmr; break;
12590 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12591 Opc = X86::VPSCATTERQDZmr; break;
12592 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12593 Opc = X86::VPSCATTERQQZmr; break;
12594 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12595 Opc = X86::VPSCATTERDQZmr; break;
12596 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12597 Opc = X86::VPSCATTERDDZmr; break;
12599 SDValue Chain = Op.getOperand(0);
12600 SDValue Base = Op.getOperand(2);
12601 SDValue Mask = Op.getOperand(3);
12602 SDValue Index = Op.getOperand(4);
12603 SDValue Src = Op.getOperand(5);
12604 SDValue Scale = Op.getOperand(6);
12605 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12607 // Read Time Stamp Counter (RDTSC).
12608 case Intrinsic::x86_rdtsc:
12609 // Read Time Stamp Counter and Processor ID (RDTSCP).
12610 case Intrinsic::x86_rdtscp: {
12613 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12614 case Intrinsic::x86_rdtsc:
12615 Opc = X86ISD::RDTSC_DAG; break;
12616 case Intrinsic::x86_rdtscp:
12617 Opc = X86ISD::RDTSCP_DAG; break;
12619 SmallVector<SDValue, 2> Results;
12620 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12621 return DAG.getMergeValues(&Results[0], Results.size(), dl);
12623 // XTEST intrinsics.
12624 case Intrinsic::x86_xtest: {
12625 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12626 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12627 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12628 DAG.getConstant(X86::COND_NE, MVT::i8),
12630 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12631 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12632 Ret, SDValue(InTrans.getNode(), 1));
12637 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12638 SelectionDAG &DAG) const {
12639 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12640 MFI->setReturnAddressIsTaken(true);
12642 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12645 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12647 EVT PtrVT = getPointerTy();
12650 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12651 const X86RegisterInfo *RegInfo =
12652 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12653 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12654 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12655 DAG.getNode(ISD::ADD, dl, PtrVT,
12656 FrameAddr, Offset),
12657 MachinePointerInfo(), false, false, false, 0);
12660 // Just load the return address.
12661 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12662 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12663 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12666 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12667 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12668 MFI->setFrameAddressIsTaken(true);
12670 EVT VT = Op.getValueType();
12671 SDLoc dl(Op); // FIXME probably not meaningful
12672 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12673 const X86RegisterInfo *RegInfo =
12674 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12675 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12676 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12677 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12678 "Invalid Frame Register!");
12679 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12681 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12682 MachinePointerInfo(),
12683 false, false, false, 0);
12687 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12688 SelectionDAG &DAG) const {
12689 const X86RegisterInfo *RegInfo =
12690 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12691 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12694 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12695 SDValue Chain = Op.getOperand(0);
12696 SDValue Offset = Op.getOperand(1);
12697 SDValue Handler = Op.getOperand(2);
12700 EVT PtrVT = getPointerTy();
12701 const X86RegisterInfo *RegInfo =
12702 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12703 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12704 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12705 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12706 "Invalid Frame Register!");
12707 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12708 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12710 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12711 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12712 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12713 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12715 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12717 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12718 DAG.getRegister(StoreAddrReg, PtrVT));
12721 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12722 SelectionDAG &DAG) const {
12724 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12725 DAG.getVTList(MVT::i32, MVT::Other),
12726 Op.getOperand(0), Op.getOperand(1));
12729 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12730 SelectionDAG &DAG) const {
12732 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12733 Op.getOperand(0), Op.getOperand(1));
12736 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12737 return Op.getOperand(0);
12740 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12741 SelectionDAG &DAG) const {
12742 SDValue Root = Op.getOperand(0);
12743 SDValue Trmp = Op.getOperand(1); // trampoline
12744 SDValue FPtr = Op.getOperand(2); // nested function
12745 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12748 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12749 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12751 if (Subtarget->is64Bit()) {
12752 SDValue OutChains[6];
12754 // Large code-model.
12755 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12756 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12758 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12759 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12761 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12763 // Load the pointer to the nested function into R11.
12764 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12765 SDValue Addr = Trmp;
12766 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12767 Addr, MachinePointerInfo(TrmpAddr),
12770 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12771 DAG.getConstant(2, MVT::i64));
12772 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12773 MachinePointerInfo(TrmpAddr, 2),
12776 // Load the 'nest' parameter value into R10.
12777 // R10 is specified in X86CallingConv.td
12778 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12779 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12780 DAG.getConstant(10, MVT::i64));
12781 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12782 Addr, MachinePointerInfo(TrmpAddr, 10),
12785 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12786 DAG.getConstant(12, MVT::i64));
12787 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12788 MachinePointerInfo(TrmpAddr, 12),
12791 // Jump to the nested function.
12792 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12793 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12794 DAG.getConstant(20, MVT::i64));
12795 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12796 Addr, MachinePointerInfo(TrmpAddr, 20),
12799 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12800 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12801 DAG.getConstant(22, MVT::i64));
12802 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12803 MachinePointerInfo(TrmpAddr, 22),
12806 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12808 const Function *Func =
12809 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12810 CallingConv::ID CC = Func->getCallingConv();
12815 llvm_unreachable("Unsupported calling convention");
12816 case CallingConv::C:
12817 case CallingConv::X86_StdCall: {
12818 // Pass 'nest' parameter in ECX.
12819 // Must be kept in sync with X86CallingConv.td
12820 NestReg = X86::ECX;
12822 // Check that ECX wasn't needed by an 'inreg' parameter.
12823 FunctionType *FTy = Func->getFunctionType();
12824 const AttributeSet &Attrs = Func->getAttributes();
12826 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12827 unsigned InRegCount = 0;
12830 for (FunctionType::param_iterator I = FTy->param_begin(),
12831 E = FTy->param_end(); I != E; ++I, ++Idx)
12832 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12833 // FIXME: should only count parameters that are lowered to integers.
12834 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12836 if (InRegCount > 2) {
12837 report_fatal_error("Nest register in use - reduce number of inreg"
12843 case CallingConv::X86_FastCall:
12844 case CallingConv::X86_ThisCall:
12845 case CallingConv::Fast:
12846 // Pass 'nest' parameter in EAX.
12847 // Must be kept in sync with X86CallingConv.td
12848 NestReg = X86::EAX;
12852 SDValue OutChains[4];
12853 SDValue Addr, Disp;
12855 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12856 DAG.getConstant(10, MVT::i32));
12857 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12859 // This is storing the opcode for MOV32ri.
12860 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12861 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12862 OutChains[0] = DAG.getStore(Root, dl,
12863 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12864 Trmp, MachinePointerInfo(TrmpAddr),
12867 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12868 DAG.getConstant(1, MVT::i32));
12869 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12870 MachinePointerInfo(TrmpAddr, 1),
12873 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12874 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12875 DAG.getConstant(5, MVT::i32));
12876 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12877 MachinePointerInfo(TrmpAddr, 5),
12880 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12881 DAG.getConstant(6, MVT::i32));
12882 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12883 MachinePointerInfo(TrmpAddr, 6),
12886 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12890 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12891 SelectionDAG &DAG) const {
12893 The rounding mode is in bits 11:10 of FPSR, and has the following
12895 00 Round to nearest
12900 FLT_ROUNDS, on the other hand, expects the following:
12907 To perform the conversion, we do:
12908 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12911 MachineFunction &MF = DAG.getMachineFunction();
12912 const TargetMachine &TM = MF.getTarget();
12913 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12914 unsigned StackAlignment = TFI.getStackAlignment();
12915 MVT VT = Op.getSimpleValueType();
12918 // Save FP Control Word to stack slot
12919 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12920 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12922 MachineMemOperand *MMO =
12923 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12924 MachineMemOperand::MOStore, 2, 2);
12926 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12927 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12928 DAG.getVTList(MVT::Other),
12929 Ops, MVT::i16, MMO);
12931 // Load FP Control Word from stack slot
12932 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12933 MachinePointerInfo(), false, false, false, 0);
12935 // Transform as necessary
12937 DAG.getNode(ISD::SRL, DL, MVT::i16,
12938 DAG.getNode(ISD::AND, DL, MVT::i16,
12939 CWD, DAG.getConstant(0x800, MVT::i16)),
12940 DAG.getConstant(11, MVT::i8));
12942 DAG.getNode(ISD::SRL, DL, MVT::i16,
12943 DAG.getNode(ISD::AND, DL, MVT::i16,
12944 CWD, DAG.getConstant(0x400, MVT::i16)),
12945 DAG.getConstant(9, MVT::i8));
12948 DAG.getNode(ISD::AND, DL, MVT::i16,
12949 DAG.getNode(ISD::ADD, DL, MVT::i16,
12950 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12951 DAG.getConstant(1, MVT::i16)),
12952 DAG.getConstant(3, MVT::i16));
12954 return DAG.getNode((VT.getSizeInBits() < 16 ?
12955 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12958 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12959 MVT VT = Op.getSimpleValueType();
12961 unsigned NumBits = VT.getSizeInBits();
12964 Op = Op.getOperand(0);
12965 if (VT == MVT::i8) {
12966 // Zero extend to i32 since there is not an i8 bsr.
12968 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12971 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12972 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12973 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12975 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12978 DAG.getConstant(NumBits+NumBits-1, OpVT),
12979 DAG.getConstant(X86::COND_E, MVT::i8),
12982 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
12984 // Finally xor with NumBits-1.
12985 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12988 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12992 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12993 MVT VT = Op.getSimpleValueType();
12995 unsigned NumBits = VT.getSizeInBits();
12998 Op = Op.getOperand(0);
12999 if (VT == MVT::i8) {
13000 // Zero extend to i32 since there is not an i8 bsr.
13002 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13005 // Issue a bsr (scan bits in reverse).
13006 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13007 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13009 // And xor with NumBits-1.
13010 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13013 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13017 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13018 MVT VT = Op.getSimpleValueType();
13019 unsigned NumBits = VT.getSizeInBits();
13021 Op = Op.getOperand(0);
13023 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13024 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13025 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13027 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13030 DAG.getConstant(NumBits, VT),
13031 DAG.getConstant(X86::COND_E, MVT::i8),
13034 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13037 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13038 // ones, and then concatenate the result back.
13039 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13040 MVT VT = Op.getSimpleValueType();
13042 assert(VT.is256BitVector() && VT.isInteger() &&
13043 "Unsupported value type for operation");
13045 unsigned NumElems = VT.getVectorNumElements();
13048 // Extract the LHS vectors
13049 SDValue LHS = Op.getOperand(0);
13050 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13051 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13053 // Extract the RHS vectors
13054 SDValue RHS = Op.getOperand(1);
13055 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13056 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13058 MVT EltVT = VT.getVectorElementType();
13059 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13061 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13062 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13063 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13066 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13067 assert(Op.getSimpleValueType().is256BitVector() &&
13068 Op.getSimpleValueType().isInteger() &&
13069 "Only handle AVX 256-bit vector integer operation");
13070 return Lower256IntArith(Op, DAG);
13073 static SDValue LowerSUB(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 LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13081 SelectionDAG &DAG) {
13083 MVT VT = Op.getSimpleValueType();
13085 // Decompose 256-bit ops into smaller 128-bit ops.
13086 if (VT.is256BitVector() && !Subtarget->hasInt256())
13087 return Lower256IntArith(Op, DAG);
13089 SDValue A = Op.getOperand(0);
13090 SDValue B = Op.getOperand(1);
13092 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13093 if (VT == MVT::v4i32) {
13094 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13095 "Should not custom lower when pmuldq is available!");
13097 // Extract the odd parts.
13098 static const int UnpackMask[] = { 1, -1, 3, -1 };
13099 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13100 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13102 // Multiply the even parts.
13103 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13104 // Now multiply odd parts.
13105 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13107 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13108 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13110 // Merge the two vectors back together with a shuffle. This expands into 2
13112 static const int ShufMask[] = { 0, 4, 2, 6 };
13113 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13116 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13117 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13119 // Ahi = psrlqi(a, 32);
13120 // Bhi = psrlqi(b, 32);
13122 // AloBlo = pmuludq(a, b);
13123 // AloBhi = pmuludq(a, Bhi);
13124 // AhiBlo = pmuludq(Ahi, b);
13126 // AloBhi = psllqi(AloBhi, 32);
13127 // AhiBlo = psllqi(AhiBlo, 32);
13128 // return AloBlo + AloBhi + AhiBlo;
13130 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13131 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13133 // Bit cast to 32-bit vectors for MULUDQ
13134 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13135 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13136 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13137 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13138 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13139 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13141 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13142 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13143 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13145 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13146 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13148 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13149 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13152 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13153 SelectionDAG &DAG) {
13154 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13155 EVT VT = Op0.getValueType();
13158 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13159 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13161 // Get the high parts.
13162 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13163 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13164 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13166 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13168 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13170 Op->getOpcode() == ISD::UMUL_LOHI ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13171 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13172 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13173 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13174 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13176 // Shuffle it back into the right order.
13177 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13178 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13179 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13180 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13182 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13185 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13186 const X86Subtarget *Subtarget) {
13187 MVT VT = Op.getSimpleValueType();
13189 SDValue R = Op.getOperand(0);
13190 SDValue Amt = Op.getOperand(1);
13192 // Optimize shl/srl/sra with constant shift amount.
13193 if (isSplatVector(Amt.getNode())) {
13194 SDValue SclrAmt = Amt->getOperand(0);
13195 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13196 uint64_t ShiftAmt = C->getZExtValue();
13198 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13199 (Subtarget->hasInt256() &&
13200 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13201 (Subtarget->hasAVX512() &&
13202 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13203 if (Op.getOpcode() == ISD::SHL)
13204 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13206 if (Op.getOpcode() == ISD::SRL)
13207 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13209 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13210 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13214 if (VT == MVT::v16i8) {
13215 if (Op.getOpcode() == ISD::SHL) {
13216 // Make a large shift.
13217 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13218 MVT::v8i16, R, ShiftAmt,
13220 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13221 // Zero out the rightmost bits.
13222 SmallVector<SDValue, 16> V(16,
13223 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13225 return DAG.getNode(ISD::AND, dl, VT, SHL,
13226 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13228 if (Op.getOpcode() == ISD::SRL) {
13229 // Make a large shift.
13230 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13231 MVT::v8i16, R, ShiftAmt,
13233 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13234 // Zero out the leftmost bits.
13235 SmallVector<SDValue, 16> V(16,
13236 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13238 return DAG.getNode(ISD::AND, dl, VT, SRL,
13239 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13241 if (Op.getOpcode() == ISD::SRA) {
13242 if (ShiftAmt == 7) {
13243 // R s>> 7 === R s< 0
13244 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13245 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13248 // R s>> a === ((R u>> a) ^ m) - m
13249 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13250 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13252 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13253 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13254 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13257 llvm_unreachable("Unknown shift opcode.");
13260 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13261 if (Op.getOpcode() == ISD::SHL) {
13262 // Make a large shift.
13263 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13264 MVT::v16i16, R, ShiftAmt,
13266 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13267 // Zero out the rightmost bits.
13268 SmallVector<SDValue, 32> V(32,
13269 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13271 return DAG.getNode(ISD::AND, dl, VT, SHL,
13272 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13274 if (Op.getOpcode() == ISD::SRL) {
13275 // Make a large shift.
13276 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13277 MVT::v16i16, R, ShiftAmt,
13279 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13280 // Zero out the leftmost bits.
13281 SmallVector<SDValue, 32> V(32,
13282 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13284 return DAG.getNode(ISD::AND, dl, VT, SRL,
13285 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13287 if (Op.getOpcode() == ISD::SRA) {
13288 if (ShiftAmt == 7) {
13289 // R s>> 7 === R s< 0
13290 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13291 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13294 // R s>> a === ((R u>> a) ^ m) - m
13295 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13296 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13298 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13299 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13300 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13303 llvm_unreachable("Unknown shift opcode.");
13308 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13309 if (!Subtarget->is64Bit() &&
13310 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13311 Amt.getOpcode() == ISD::BITCAST &&
13312 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13313 Amt = Amt.getOperand(0);
13314 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13315 VT.getVectorNumElements();
13316 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13317 uint64_t ShiftAmt = 0;
13318 for (unsigned i = 0; i != Ratio; ++i) {
13319 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13323 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13325 // Check remaining shift amounts.
13326 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13327 uint64_t ShAmt = 0;
13328 for (unsigned j = 0; j != Ratio; ++j) {
13329 ConstantSDNode *C =
13330 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13334 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13336 if (ShAmt != ShiftAmt)
13339 switch (Op.getOpcode()) {
13341 llvm_unreachable("Unknown shift opcode!");
13343 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13346 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13349 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13357 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13358 const X86Subtarget* Subtarget) {
13359 MVT VT = Op.getSimpleValueType();
13361 SDValue R = Op.getOperand(0);
13362 SDValue Amt = Op.getOperand(1);
13364 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13365 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13366 (Subtarget->hasInt256() &&
13367 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13368 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13369 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13371 EVT EltVT = VT.getVectorElementType();
13373 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13374 unsigned NumElts = VT.getVectorNumElements();
13376 for (i = 0; i != NumElts; ++i) {
13377 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13381 for (j = i; j != NumElts; ++j) {
13382 SDValue Arg = Amt.getOperand(j);
13383 if (Arg.getOpcode() == ISD::UNDEF) continue;
13384 if (Arg != Amt.getOperand(i))
13387 if (i != NumElts && j == NumElts)
13388 BaseShAmt = Amt.getOperand(i);
13390 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13391 Amt = Amt.getOperand(0);
13392 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13393 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13394 SDValue InVec = Amt.getOperand(0);
13395 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13396 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13398 for (; i != NumElts; ++i) {
13399 SDValue Arg = InVec.getOperand(i);
13400 if (Arg.getOpcode() == ISD::UNDEF) continue;
13404 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13405 if (ConstantSDNode *C =
13406 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13407 unsigned SplatIdx =
13408 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13409 if (C->getZExtValue() == SplatIdx)
13410 BaseShAmt = InVec.getOperand(1);
13413 if (!BaseShAmt.getNode())
13414 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13415 DAG.getIntPtrConstant(0));
13419 if (BaseShAmt.getNode()) {
13420 if (EltVT.bitsGT(MVT::i32))
13421 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13422 else if (EltVT.bitsLT(MVT::i32))
13423 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13425 switch (Op.getOpcode()) {
13427 llvm_unreachable("Unknown shift opcode!");
13429 switch (VT.SimpleTy) {
13430 default: return SDValue();
13439 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13442 switch (VT.SimpleTy) {
13443 default: return SDValue();
13450 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13453 switch (VT.SimpleTy) {
13454 default: return SDValue();
13463 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13469 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13470 if (!Subtarget->is64Bit() &&
13471 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13472 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13473 Amt.getOpcode() == ISD::BITCAST &&
13474 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13475 Amt = Amt.getOperand(0);
13476 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13477 VT.getVectorNumElements();
13478 std::vector<SDValue> Vals(Ratio);
13479 for (unsigned i = 0; i != Ratio; ++i)
13480 Vals[i] = Amt.getOperand(i);
13481 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13482 for (unsigned j = 0; j != Ratio; ++j)
13483 if (Vals[j] != Amt.getOperand(i + j))
13486 switch (Op.getOpcode()) {
13488 llvm_unreachable("Unknown shift opcode!");
13490 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13492 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13494 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13501 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13502 SelectionDAG &DAG) {
13504 MVT VT = Op.getSimpleValueType();
13506 SDValue R = Op.getOperand(0);
13507 SDValue Amt = Op.getOperand(1);
13510 if (!Subtarget->hasSSE2())
13513 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13517 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13521 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13523 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13524 if (Subtarget->hasInt256()) {
13525 if (Op.getOpcode() == ISD::SRL &&
13526 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13527 VT == MVT::v4i64 || VT == MVT::v8i32))
13529 if (Op.getOpcode() == ISD::SHL &&
13530 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13531 VT == MVT::v4i64 || VT == MVT::v8i32))
13533 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13537 // If possible, lower this packed shift into a vector multiply instead of
13538 // expanding it into a sequence of scalar shifts.
13539 // Do this only if the vector shift count is a constant build_vector.
13540 if (Op.getOpcode() == ISD::SHL &&
13541 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13542 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13543 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13544 SmallVector<SDValue, 8> Elts;
13545 EVT SVT = VT.getScalarType();
13546 unsigned SVTBits = SVT.getSizeInBits();
13547 const APInt &One = APInt(SVTBits, 1);
13548 unsigned NumElems = VT.getVectorNumElements();
13550 for (unsigned i=0; i !=NumElems; ++i) {
13551 SDValue Op = Amt->getOperand(i);
13552 if (Op->getOpcode() == ISD::UNDEF) {
13553 Elts.push_back(Op);
13557 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13558 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13559 uint64_t ShAmt = C.getZExtValue();
13560 if (ShAmt >= SVTBits) {
13561 Elts.push_back(DAG.getUNDEF(SVT));
13564 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13566 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13567 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13570 // Lower SHL with variable shift amount.
13571 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13572 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13574 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13575 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13576 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13577 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13580 // If possible, lower this shift as a sequence of two shifts by
13581 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13583 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13585 // Could be rewritten as:
13586 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13588 // The advantage is that the two shifts from the example would be
13589 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13590 // the vector shift into four scalar shifts plus four pairs of vector
13592 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13593 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13594 unsigned TargetOpcode = X86ISD::MOVSS;
13595 bool CanBeSimplified;
13596 // The splat value for the first packed shift (the 'X' from the example).
13597 SDValue Amt1 = Amt->getOperand(0);
13598 // The splat value for the second packed shift (the 'Y' from the example).
13599 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13600 Amt->getOperand(2);
13602 // See if it is possible to replace this node with a sequence of
13603 // two shifts followed by a MOVSS/MOVSD
13604 if (VT == MVT::v4i32) {
13605 // Check if it is legal to use a MOVSS.
13606 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13607 Amt2 == Amt->getOperand(3);
13608 if (!CanBeSimplified) {
13609 // Otherwise, check if we can still simplify this node using a MOVSD.
13610 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13611 Amt->getOperand(2) == Amt->getOperand(3);
13612 TargetOpcode = X86ISD::MOVSD;
13613 Amt2 = Amt->getOperand(2);
13616 // Do similar checks for the case where the machine value type
13618 CanBeSimplified = Amt1 == Amt->getOperand(1);
13619 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13620 CanBeSimplified = Amt2 == Amt->getOperand(i);
13622 if (!CanBeSimplified) {
13623 TargetOpcode = X86ISD::MOVSD;
13624 CanBeSimplified = true;
13625 Amt2 = Amt->getOperand(4);
13626 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13627 CanBeSimplified = Amt1 == Amt->getOperand(i);
13628 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13629 CanBeSimplified = Amt2 == Amt->getOperand(j);
13633 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13634 isa<ConstantSDNode>(Amt2)) {
13635 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13636 EVT CastVT = MVT::v4i32;
13638 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13639 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13641 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13642 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13643 if (TargetOpcode == X86ISD::MOVSD)
13644 CastVT = MVT::v2i64;
13645 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13646 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13647 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13649 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13653 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13654 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13657 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13658 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13660 // Turn 'a' into a mask suitable for VSELECT
13661 SDValue VSelM = DAG.getConstant(0x80, VT);
13662 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13663 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13665 SDValue CM1 = DAG.getConstant(0x0f, VT);
13666 SDValue CM2 = DAG.getConstant(0x3f, VT);
13668 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13669 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13670 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13671 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13672 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13675 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13676 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13677 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13679 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13680 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13681 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13682 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13683 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13686 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13687 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13688 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13690 // return VSELECT(r, r+r, a);
13691 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13692 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13696 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13697 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13698 // solution better.
13699 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13700 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13702 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13703 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13704 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13705 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13706 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13709 // Decompose 256-bit shifts into smaller 128-bit shifts.
13710 if (VT.is256BitVector()) {
13711 unsigned NumElems = VT.getVectorNumElements();
13712 MVT EltVT = VT.getVectorElementType();
13713 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13715 // Extract the two vectors
13716 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13717 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13719 // Recreate the shift amount vectors
13720 SDValue Amt1, Amt2;
13721 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13722 // Constant shift amount
13723 SmallVector<SDValue, 4> Amt1Csts;
13724 SmallVector<SDValue, 4> Amt2Csts;
13725 for (unsigned i = 0; i != NumElems/2; ++i)
13726 Amt1Csts.push_back(Amt->getOperand(i));
13727 for (unsigned i = NumElems/2; i != NumElems; ++i)
13728 Amt2Csts.push_back(Amt->getOperand(i));
13730 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13731 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13733 // Variable shift amount
13734 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13735 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13738 // Issue new vector shifts for the smaller types
13739 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13740 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13742 // Concatenate the result back
13743 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13749 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13750 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13751 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13752 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13753 // has only one use.
13754 SDNode *N = Op.getNode();
13755 SDValue LHS = N->getOperand(0);
13756 SDValue RHS = N->getOperand(1);
13757 unsigned BaseOp = 0;
13760 switch (Op.getOpcode()) {
13761 default: llvm_unreachable("Unknown ovf instruction!");
13763 // A subtract of one will be selected as a INC. Note that INC doesn't
13764 // set CF, so we can't do this for UADDO.
13765 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13767 BaseOp = X86ISD::INC;
13768 Cond = X86::COND_O;
13771 BaseOp = X86ISD::ADD;
13772 Cond = X86::COND_O;
13775 BaseOp = X86ISD::ADD;
13776 Cond = X86::COND_B;
13779 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13780 // set CF, so we can't do this for USUBO.
13781 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13783 BaseOp = X86ISD::DEC;
13784 Cond = X86::COND_O;
13787 BaseOp = X86ISD::SUB;
13788 Cond = X86::COND_O;
13791 BaseOp = X86ISD::SUB;
13792 Cond = X86::COND_B;
13795 BaseOp = X86ISD::SMUL;
13796 Cond = X86::COND_O;
13798 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13799 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13801 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13804 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13805 DAG.getConstant(X86::COND_O, MVT::i32),
13806 SDValue(Sum.getNode(), 2));
13808 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13812 // Also sets EFLAGS.
13813 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13814 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13817 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13818 DAG.getConstant(Cond, MVT::i32),
13819 SDValue(Sum.getNode(), 1));
13821 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13824 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13825 SelectionDAG &DAG) const {
13827 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13828 MVT VT = Op.getSimpleValueType();
13830 if (!Subtarget->hasSSE2() || !VT.isVector())
13833 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13834 ExtraVT.getScalarType().getSizeInBits();
13836 switch (VT.SimpleTy) {
13837 default: return SDValue();
13840 if (!Subtarget->hasFp256())
13842 if (!Subtarget->hasInt256()) {
13843 // needs to be split
13844 unsigned NumElems = VT.getVectorNumElements();
13846 // Extract the LHS vectors
13847 SDValue LHS = Op.getOperand(0);
13848 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13849 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13851 MVT EltVT = VT.getVectorElementType();
13852 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13854 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13855 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13856 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13858 SDValue Extra = DAG.getValueType(ExtraVT);
13860 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13861 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13863 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13868 SDValue Op0 = Op.getOperand(0);
13869 SDValue Op00 = Op0.getOperand(0);
13871 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13872 if (Op0.getOpcode() == ISD::BITCAST &&
13873 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13874 // (sext (vzext x)) -> (vsext x)
13875 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13876 if (Tmp1.getNode()) {
13877 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13878 // This folding is only valid when the in-reg type is a vector of i8,
13880 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13881 ExtraEltVT == MVT::i32) {
13882 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13883 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13884 "This optimization is invalid without a VZEXT.");
13885 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13891 // If the above didn't work, then just use Shift-Left + Shift-Right.
13892 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13894 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13900 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13901 SelectionDAG &DAG) {
13903 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13904 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13905 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13906 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13908 // The only fence that needs an instruction is a sequentially-consistent
13909 // cross-thread fence.
13910 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13911 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13912 // no-sse2). There isn't any reason to disable it if the target processor
13914 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13915 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13917 SDValue Chain = Op.getOperand(0);
13918 SDValue Zero = DAG.getConstant(0, MVT::i32);
13920 DAG.getRegister(X86::ESP, MVT::i32), // Base
13921 DAG.getTargetConstant(1, MVT::i8), // Scale
13922 DAG.getRegister(0, MVT::i32), // Index
13923 DAG.getTargetConstant(0, MVT::i32), // Disp
13924 DAG.getRegister(0, MVT::i32), // Segment.
13928 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13929 return SDValue(Res, 0);
13932 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13933 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13936 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13937 SelectionDAG &DAG) {
13938 MVT T = Op.getSimpleValueType();
13942 switch(T.SimpleTy) {
13943 default: llvm_unreachable("Invalid value type!");
13944 case MVT::i8: Reg = X86::AL; size = 1; break;
13945 case MVT::i16: Reg = X86::AX; size = 2; break;
13946 case MVT::i32: Reg = X86::EAX; size = 4; break;
13948 assert(Subtarget->is64Bit() && "Node not type legal!");
13949 Reg = X86::RAX; size = 8;
13952 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13953 Op.getOperand(2), SDValue());
13954 SDValue Ops[] = { cpIn.getValue(0),
13957 DAG.getTargetConstant(size, MVT::i8),
13958 cpIn.getValue(1) };
13959 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13960 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13961 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13964 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13968 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13969 SelectionDAG &DAG) {
13970 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13971 MVT DstVT = Op.getSimpleValueType();
13972 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13973 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13974 assert((DstVT == MVT::i64 ||
13975 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13976 "Unexpected custom BITCAST");
13977 // i64 <=> MMX conversions are Legal.
13978 if (SrcVT==MVT::i64 && DstVT.isVector())
13980 if (DstVT==MVT::i64 && SrcVT.isVector())
13982 // MMX <=> MMX conversions are Legal.
13983 if (SrcVT.isVector() && DstVT.isVector())
13985 // All other conversions need to be expanded.
13989 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13990 SDNode *Node = Op.getNode();
13992 EVT T = Node->getValueType(0);
13993 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13994 DAG.getConstant(0, T), Node->getOperand(2));
13995 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13996 cast<AtomicSDNode>(Node)->getMemoryVT(),
13997 Node->getOperand(0),
13998 Node->getOperand(1), negOp,
13999 cast<AtomicSDNode>(Node)->getMemOperand(),
14000 cast<AtomicSDNode>(Node)->getOrdering(),
14001 cast<AtomicSDNode>(Node)->getSynchScope());
14004 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14005 SDNode *Node = Op.getNode();
14007 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14009 // Convert seq_cst store -> xchg
14010 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14011 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14012 // (The only way to get a 16-byte store is cmpxchg16b)
14013 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14014 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14015 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14016 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14017 cast<AtomicSDNode>(Node)->getMemoryVT(),
14018 Node->getOperand(0),
14019 Node->getOperand(1), Node->getOperand(2),
14020 cast<AtomicSDNode>(Node)->getMemOperand(),
14021 cast<AtomicSDNode>(Node)->getOrdering(),
14022 cast<AtomicSDNode>(Node)->getSynchScope());
14023 return Swap.getValue(1);
14025 // Other atomic stores have a simple pattern.
14029 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14030 EVT VT = Op.getNode()->getSimpleValueType(0);
14032 // Let legalize expand this if it isn't a legal type yet.
14033 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14036 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14039 bool ExtraOp = false;
14040 switch (Op.getOpcode()) {
14041 default: llvm_unreachable("Invalid code");
14042 case ISD::ADDC: Opc = X86ISD::ADD; break;
14043 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14044 case ISD::SUBC: Opc = X86ISD::SUB; break;
14045 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14049 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14051 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14052 Op.getOperand(1), Op.getOperand(2));
14055 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14056 SelectionDAG &DAG) {
14057 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14059 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14060 // which returns the values as { float, float } (in XMM0) or
14061 // { double, double } (which is returned in XMM0, XMM1).
14063 SDValue Arg = Op.getOperand(0);
14064 EVT ArgVT = Arg.getValueType();
14065 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14067 TargetLowering::ArgListTy Args;
14068 TargetLowering::ArgListEntry Entry;
14072 Entry.isSExt = false;
14073 Entry.isZExt = false;
14074 Args.push_back(Entry);
14076 bool isF64 = ArgVT == MVT::f64;
14077 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14078 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14079 // the results are returned via SRet in memory.
14080 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14081 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14082 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14084 Type *RetTy = isF64
14085 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14086 : (Type*)VectorType::get(ArgTy, 4);
14088 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14089 false, false, false, false, 0,
14090 CallingConv::C, /*isTaillCall=*/false,
14091 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14092 Callee, Args, DAG, dl);
14093 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14096 // Returned in xmm0 and xmm1.
14097 return CallResult.first;
14099 // Returned in bits 0:31 and 32:64 xmm0.
14100 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14101 CallResult.first, DAG.getIntPtrConstant(0));
14102 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14103 CallResult.first, DAG.getIntPtrConstant(1));
14104 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14105 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14108 /// LowerOperation - Provide custom lowering hooks for some operations.
14110 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14111 switch (Op.getOpcode()) {
14112 default: llvm_unreachable("Should not custom lower this!");
14113 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14114 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14115 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14116 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14117 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14118 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14119 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14120 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14121 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14122 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14123 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14124 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14125 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14126 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14127 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14128 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14129 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14130 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14131 case ISD::SHL_PARTS:
14132 case ISD::SRA_PARTS:
14133 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14134 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14135 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14136 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14137 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14138 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14139 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14140 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14141 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14142 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14143 case ISD::FABS: return LowerFABS(Op, DAG);
14144 case ISD::FNEG: return LowerFNEG(Op, DAG);
14145 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14146 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14147 case ISD::SETCC: return LowerSETCC(Op, DAG);
14148 case ISD::SELECT: return LowerSELECT(Op, DAG);
14149 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14150 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14151 case ISD::VASTART: return LowerVASTART(Op, DAG);
14152 case ISD::VAARG: return LowerVAARG(Op, DAG);
14153 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14154 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14155 case ISD::INTRINSIC_VOID:
14156 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14157 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14158 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14159 case ISD::FRAME_TO_ARGS_OFFSET:
14160 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14161 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14162 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14163 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14164 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14165 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14166 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14167 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14168 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14169 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14170 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14171 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14172 case ISD::UMUL_LOHI:
14173 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14176 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14182 case ISD::UMULO: return LowerXALUO(Op, DAG);
14183 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14184 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14188 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14189 case ISD::ADD: return LowerADD(Op, DAG);
14190 case ISD::SUB: return LowerSUB(Op, DAG);
14191 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14195 static void ReplaceATOMIC_LOAD(SDNode *Node,
14196 SmallVectorImpl<SDValue> &Results,
14197 SelectionDAG &DAG) {
14199 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14201 // Convert wide load -> cmpxchg8b/cmpxchg16b
14202 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14203 // (The only way to get a 16-byte load is cmpxchg16b)
14204 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14205 SDValue Zero = DAG.getConstant(0, VT);
14206 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14207 Node->getOperand(0),
14208 Node->getOperand(1), Zero, Zero,
14209 cast<AtomicSDNode>(Node)->getMemOperand(),
14210 cast<AtomicSDNode>(Node)->getOrdering(),
14211 cast<AtomicSDNode>(Node)->getOrdering(),
14212 cast<AtomicSDNode>(Node)->getSynchScope());
14213 Results.push_back(Swap.getValue(0));
14214 Results.push_back(Swap.getValue(1));
14218 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14219 SelectionDAG &DAG, unsigned NewOp) {
14221 assert (Node->getValueType(0) == MVT::i64 &&
14222 "Only know how to expand i64 atomics");
14224 SDValue Chain = Node->getOperand(0);
14225 SDValue In1 = Node->getOperand(1);
14226 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14227 Node->getOperand(2), DAG.getIntPtrConstant(0));
14228 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14229 Node->getOperand(2), DAG.getIntPtrConstant(1));
14230 SDValue Ops[] = { Chain, In1, In2L, In2H };
14231 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14233 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14234 cast<MemSDNode>(Node)->getMemOperand());
14235 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14236 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14237 Results.push_back(Result.getValue(2));
14240 /// ReplaceNodeResults - Replace a node with an illegal result type
14241 /// with a new node built out of custom code.
14242 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14243 SmallVectorImpl<SDValue>&Results,
14244 SelectionDAG &DAG) const {
14246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14247 switch (N->getOpcode()) {
14249 llvm_unreachable("Do not know how to custom type legalize this operation!");
14250 case ISD::SIGN_EXTEND_INREG:
14255 // We don't want to expand or promote these.
14257 case ISD::FP_TO_SINT:
14258 case ISD::FP_TO_UINT: {
14259 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14261 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14264 std::pair<SDValue,SDValue> Vals =
14265 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14266 SDValue FIST = Vals.first, StackSlot = Vals.second;
14267 if (FIST.getNode()) {
14268 EVT VT = N->getValueType(0);
14269 // Return a load from the stack slot.
14270 if (StackSlot.getNode())
14271 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14272 MachinePointerInfo(),
14273 false, false, false, 0));
14275 Results.push_back(FIST);
14279 case ISD::UINT_TO_FP: {
14280 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14281 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14282 N->getValueType(0) != MVT::v2f32)
14284 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14286 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14288 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14289 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14290 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14291 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14292 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14293 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14296 case ISD::FP_ROUND: {
14297 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14299 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14300 Results.push_back(V);
14303 case ISD::INTRINSIC_W_CHAIN: {
14304 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14306 default : llvm_unreachable("Do not know how to custom type "
14307 "legalize this intrinsic operation!");
14308 case Intrinsic::x86_rdtsc:
14309 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14311 case Intrinsic::x86_rdtscp:
14312 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14316 case ISD::READCYCLECOUNTER: {
14317 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14320 case ISD::ATOMIC_CMP_SWAP: {
14321 EVT T = N->getValueType(0);
14322 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14323 bool Regs64bit = T == MVT::i128;
14324 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14325 SDValue cpInL, cpInH;
14326 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14327 DAG.getConstant(0, HalfT));
14328 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14329 DAG.getConstant(1, HalfT));
14330 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14331 Regs64bit ? X86::RAX : X86::EAX,
14333 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14334 Regs64bit ? X86::RDX : X86::EDX,
14335 cpInH, cpInL.getValue(1));
14336 SDValue swapInL, swapInH;
14337 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14338 DAG.getConstant(0, HalfT));
14339 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14340 DAG.getConstant(1, HalfT));
14341 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14342 Regs64bit ? X86::RBX : X86::EBX,
14343 swapInL, cpInH.getValue(1));
14344 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14345 Regs64bit ? X86::RCX : X86::ECX,
14346 swapInH, swapInL.getValue(1));
14347 SDValue Ops[] = { swapInH.getValue(0),
14349 swapInH.getValue(1) };
14350 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14351 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14352 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14353 X86ISD::LCMPXCHG8_DAG;
14354 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14355 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14356 Regs64bit ? X86::RAX : X86::EAX,
14357 HalfT, Result.getValue(1));
14358 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14359 Regs64bit ? X86::RDX : X86::EDX,
14360 HalfT, cpOutL.getValue(2));
14361 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14362 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14363 Results.push_back(cpOutH.getValue(1));
14366 case ISD::ATOMIC_LOAD_ADD:
14367 case ISD::ATOMIC_LOAD_AND:
14368 case ISD::ATOMIC_LOAD_NAND:
14369 case ISD::ATOMIC_LOAD_OR:
14370 case ISD::ATOMIC_LOAD_SUB:
14371 case ISD::ATOMIC_LOAD_XOR:
14372 case ISD::ATOMIC_LOAD_MAX:
14373 case ISD::ATOMIC_LOAD_MIN:
14374 case ISD::ATOMIC_LOAD_UMAX:
14375 case ISD::ATOMIC_LOAD_UMIN:
14376 case ISD::ATOMIC_SWAP: {
14378 switch (N->getOpcode()) {
14379 default: llvm_unreachable("Unexpected opcode");
14380 case ISD::ATOMIC_LOAD_ADD:
14381 Opc = X86ISD::ATOMADD64_DAG;
14383 case ISD::ATOMIC_LOAD_AND:
14384 Opc = X86ISD::ATOMAND64_DAG;
14386 case ISD::ATOMIC_LOAD_NAND:
14387 Opc = X86ISD::ATOMNAND64_DAG;
14389 case ISD::ATOMIC_LOAD_OR:
14390 Opc = X86ISD::ATOMOR64_DAG;
14392 case ISD::ATOMIC_LOAD_SUB:
14393 Opc = X86ISD::ATOMSUB64_DAG;
14395 case ISD::ATOMIC_LOAD_XOR:
14396 Opc = X86ISD::ATOMXOR64_DAG;
14398 case ISD::ATOMIC_LOAD_MAX:
14399 Opc = X86ISD::ATOMMAX64_DAG;
14401 case ISD::ATOMIC_LOAD_MIN:
14402 Opc = X86ISD::ATOMMIN64_DAG;
14404 case ISD::ATOMIC_LOAD_UMAX:
14405 Opc = X86ISD::ATOMUMAX64_DAG;
14407 case ISD::ATOMIC_LOAD_UMIN:
14408 Opc = X86ISD::ATOMUMIN64_DAG;
14410 case ISD::ATOMIC_SWAP:
14411 Opc = X86ISD::ATOMSWAP64_DAG;
14414 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14417 case ISD::ATOMIC_LOAD:
14418 ReplaceATOMIC_LOAD(N, Results, DAG);
14422 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14424 default: return nullptr;
14425 case X86ISD::BSF: return "X86ISD::BSF";
14426 case X86ISD::BSR: return "X86ISD::BSR";
14427 case X86ISD::SHLD: return "X86ISD::SHLD";
14428 case X86ISD::SHRD: return "X86ISD::SHRD";
14429 case X86ISD::FAND: return "X86ISD::FAND";
14430 case X86ISD::FANDN: return "X86ISD::FANDN";
14431 case X86ISD::FOR: return "X86ISD::FOR";
14432 case X86ISD::FXOR: return "X86ISD::FXOR";
14433 case X86ISD::FSRL: return "X86ISD::FSRL";
14434 case X86ISD::FILD: return "X86ISD::FILD";
14435 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14436 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14437 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14438 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14439 case X86ISD::FLD: return "X86ISD::FLD";
14440 case X86ISD::FST: return "X86ISD::FST";
14441 case X86ISD::CALL: return "X86ISD::CALL";
14442 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14443 case X86ISD::BT: return "X86ISD::BT";
14444 case X86ISD::CMP: return "X86ISD::CMP";
14445 case X86ISD::COMI: return "X86ISD::COMI";
14446 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14447 case X86ISD::CMPM: return "X86ISD::CMPM";
14448 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14449 case X86ISD::SETCC: return "X86ISD::SETCC";
14450 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14451 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14452 case X86ISD::CMOV: return "X86ISD::CMOV";
14453 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14454 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14455 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14456 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14457 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14458 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14459 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14460 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14461 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14462 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14463 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14464 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14465 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14466 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14467 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14468 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14469 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14470 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14471 case X86ISD::HADD: return "X86ISD::HADD";
14472 case X86ISD::HSUB: return "X86ISD::HSUB";
14473 case X86ISD::FHADD: return "X86ISD::FHADD";
14474 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14475 case X86ISD::UMAX: return "X86ISD::UMAX";
14476 case X86ISD::UMIN: return "X86ISD::UMIN";
14477 case X86ISD::SMAX: return "X86ISD::SMAX";
14478 case X86ISD::SMIN: return "X86ISD::SMIN";
14479 case X86ISD::FMAX: return "X86ISD::FMAX";
14480 case X86ISD::FMIN: return "X86ISD::FMIN";
14481 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14482 case X86ISD::FMINC: return "X86ISD::FMINC";
14483 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14484 case X86ISD::FRCP: return "X86ISD::FRCP";
14485 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14486 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14487 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14488 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14489 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14490 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14491 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14492 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14493 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14494 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14495 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14496 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14497 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14498 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14499 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14500 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14501 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14502 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14503 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14504 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14505 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14506 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14507 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14508 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14509 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14510 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14511 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14512 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14513 case X86ISD::VSHL: return "X86ISD::VSHL";
14514 case X86ISD::VSRL: return "X86ISD::VSRL";
14515 case X86ISD::VSRA: return "X86ISD::VSRA";
14516 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14517 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14518 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14519 case X86ISD::CMPP: return "X86ISD::CMPP";
14520 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14521 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14522 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14523 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14524 case X86ISD::ADD: return "X86ISD::ADD";
14525 case X86ISD::SUB: return "X86ISD::SUB";
14526 case X86ISD::ADC: return "X86ISD::ADC";
14527 case X86ISD::SBB: return "X86ISD::SBB";
14528 case X86ISD::SMUL: return "X86ISD::SMUL";
14529 case X86ISD::UMUL: return "X86ISD::UMUL";
14530 case X86ISD::INC: return "X86ISD::INC";
14531 case X86ISD::DEC: return "X86ISD::DEC";
14532 case X86ISD::OR: return "X86ISD::OR";
14533 case X86ISD::XOR: return "X86ISD::XOR";
14534 case X86ISD::AND: return "X86ISD::AND";
14535 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14536 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14537 case X86ISD::PTEST: return "X86ISD::PTEST";
14538 case X86ISD::TESTP: return "X86ISD::TESTP";
14539 case X86ISD::TESTM: return "X86ISD::TESTM";
14540 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14541 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14542 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14543 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14544 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14545 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14546 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14547 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14548 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14549 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14550 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14551 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14552 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14553 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14554 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14555 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14556 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14557 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14558 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14559 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14560 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14561 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14562 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14563 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14564 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14565 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14566 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14567 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14568 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14569 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14570 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14571 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14572 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14573 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14574 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14575 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14576 case X86ISD::SAHF: return "X86ISD::SAHF";
14577 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14578 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14579 case X86ISD::FMADD: return "X86ISD::FMADD";
14580 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14581 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14582 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14583 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14584 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14585 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14586 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14587 case X86ISD::XTEST: return "X86ISD::XTEST";
14591 // isLegalAddressingMode - Return true if the addressing mode represented
14592 // by AM is legal for this target, for a load/store of the specified type.
14593 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14595 // X86 supports extremely general addressing modes.
14596 CodeModel::Model M = getTargetMachine().getCodeModel();
14597 Reloc::Model R = getTargetMachine().getRelocationModel();
14599 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14600 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14605 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14607 // If a reference to this global requires an extra load, we can't fold it.
14608 if (isGlobalStubReference(GVFlags))
14611 // If BaseGV requires a register for the PIC base, we cannot also have a
14612 // BaseReg specified.
14613 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14616 // If lower 4G is not available, then we must use rip-relative addressing.
14617 if ((M != CodeModel::Small || R != Reloc::Static) &&
14618 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14622 switch (AM.Scale) {
14628 // These scales always work.
14633 // These scales are formed with basereg+scalereg. Only accept if there is
14638 default: // Other stuff never works.
14645 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14646 unsigned Bits = Ty->getScalarSizeInBits();
14648 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14649 // particularly cheaper than those without.
14653 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14654 // variable shifts just as cheap as scalar ones.
14655 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14658 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14659 // fully general vector.
14663 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14664 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14666 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14667 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14668 return NumBits1 > NumBits2;
14671 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14672 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14675 if (!isTypeLegal(EVT::getEVT(Ty1)))
14678 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14680 // Assuming the caller doesn't have a zeroext or signext return parameter,
14681 // truncation all the way down to i1 is valid.
14685 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14686 return isInt<32>(Imm);
14689 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14690 // Can also use sub to handle negated immediates.
14691 return isInt<32>(Imm);
14694 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14695 if (!VT1.isInteger() || !VT2.isInteger())
14697 unsigned NumBits1 = VT1.getSizeInBits();
14698 unsigned NumBits2 = VT2.getSizeInBits();
14699 return NumBits1 > NumBits2;
14702 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14703 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14704 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14707 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14708 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14709 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14712 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14713 EVT VT1 = Val.getValueType();
14714 if (isZExtFree(VT1, VT2))
14717 if (Val.getOpcode() != ISD::LOAD)
14720 if (!VT1.isSimple() || !VT1.isInteger() ||
14721 !VT2.isSimple() || !VT2.isInteger())
14724 switch (VT1.getSimpleVT().SimpleTy) {
14729 // X86 has 8, 16, and 32-bit zero-extending loads.
14737 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14738 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14741 VT = VT.getScalarType();
14743 if (!VT.isSimple())
14746 switch (VT.getSimpleVT().SimpleTy) {
14757 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14758 // i16 instructions are longer (0x66 prefix) and potentially slower.
14759 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14762 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14763 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14764 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14765 /// are assumed to be legal.
14767 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14769 if (!VT.isSimple())
14772 MVT SVT = VT.getSimpleVT();
14774 // Very little shuffling can be done for 64-bit vectors right now.
14775 if (VT.getSizeInBits() == 64)
14778 // FIXME: pshufb, blends, shifts.
14779 return (SVT.getVectorNumElements() == 2 ||
14780 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14781 isMOVLMask(M, SVT) ||
14782 isSHUFPMask(M, SVT) ||
14783 isPSHUFDMask(M, SVT) ||
14784 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14785 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14786 isPALIGNRMask(M, SVT, Subtarget) ||
14787 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14788 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14789 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14790 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14794 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14796 if (!VT.isSimple())
14799 MVT SVT = VT.getSimpleVT();
14800 unsigned NumElts = SVT.getVectorNumElements();
14801 // FIXME: This collection of masks seems suspect.
14804 if (NumElts == 4 && SVT.is128BitVector()) {
14805 return (isMOVLMask(Mask, SVT) ||
14806 isCommutedMOVLMask(Mask, SVT, true) ||
14807 isSHUFPMask(Mask, SVT) ||
14808 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14813 //===----------------------------------------------------------------------===//
14814 // X86 Scheduler Hooks
14815 //===----------------------------------------------------------------------===//
14817 /// Utility function to emit xbegin specifying the start of an RTM region.
14818 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14819 const TargetInstrInfo *TII) {
14820 DebugLoc DL = MI->getDebugLoc();
14822 const BasicBlock *BB = MBB->getBasicBlock();
14823 MachineFunction::iterator I = MBB;
14826 // For the v = xbegin(), we generate
14837 MachineBasicBlock *thisMBB = MBB;
14838 MachineFunction *MF = MBB->getParent();
14839 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14840 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14841 MF->insert(I, mainMBB);
14842 MF->insert(I, sinkMBB);
14844 // Transfer the remainder of BB and its successor edges to sinkMBB.
14845 sinkMBB->splice(sinkMBB->begin(), MBB,
14846 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14847 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14851 // # fallthrough to mainMBB
14852 // # abortion to sinkMBB
14853 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14854 thisMBB->addSuccessor(mainMBB);
14855 thisMBB->addSuccessor(sinkMBB);
14859 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14860 mainMBB->addSuccessor(sinkMBB);
14863 // EAX is live into the sinkMBB
14864 sinkMBB->addLiveIn(X86::EAX);
14865 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14866 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14869 MI->eraseFromParent();
14873 // Get CMPXCHG opcode for the specified data type.
14874 static unsigned getCmpXChgOpcode(EVT VT) {
14875 switch (VT.getSimpleVT().SimpleTy) {
14876 case MVT::i8: return X86::LCMPXCHG8;
14877 case MVT::i16: return X86::LCMPXCHG16;
14878 case MVT::i32: return X86::LCMPXCHG32;
14879 case MVT::i64: return X86::LCMPXCHG64;
14883 llvm_unreachable("Invalid operand size!");
14886 // Get LOAD opcode for the specified data type.
14887 static unsigned getLoadOpcode(EVT VT) {
14888 switch (VT.getSimpleVT().SimpleTy) {
14889 case MVT::i8: return X86::MOV8rm;
14890 case MVT::i16: return X86::MOV16rm;
14891 case MVT::i32: return X86::MOV32rm;
14892 case MVT::i64: return X86::MOV64rm;
14896 llvm_unreachable("Invalid operand size!");
14899 // Get opcode of the non-atomic one from the specified atomic instruction.
14900 static unsigned getNonAtomicOpcode(unsigned Opc) {
14902 case X86::ATOMAND8: return X86::AND8rr;
14903 case X86::ATOMAND16: return X86::AND16rr;
14904 case X86::ATOMAND32: return X86::AND32rr;
14905 case X86::ATOMAND64: return X86::AND64rr;
14906 case X86::ATOMOR8: return X86::OR8rr;
14907 case X86::ATOMOR16: return X86::OR16rr;
14908 case X86::ATOMOR32: return X86::OR32rr;
14909 case X86::ATOMOR64: return X86::OR64rr;
14910 case X86::ATOMXOR8: return X86::XOR8rr;
14911 case X86::ATOMXOR16: return X86::XOR16rr;
14912 case X86::ATOMXOR32: return X86::XOR32rr;
14913 case X86::ATOMXOR64: return X86::XOR64rr;
14915 llvm_unreachable("Unhandled atomic-load-op opcode!");
14918 // Get opcode of the non-atomic one from the specified atomic instruction with
14920 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14921 unsigned &ExtraOpc) {
14923 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14924 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14925 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14926 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14927 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14928 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14929 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14930 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14931 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14932 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14933 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14934 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14935 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14936 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14937 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14938 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14939 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14940 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14941 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14942 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14944 llvm_unreachable("Unhandled atomic-load-op opcode!");
14947 // Get opcode of the non-atomic one from the specified atomic instruction for
14948 // 64-bit data type on 32-bit target.
14949 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14951 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14952 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14953 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14954 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14955 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14956 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14957 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14958 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14959 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14960 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14962 llvm_unreachable("Unhandled atomic-load-op opcode!");
14965 // Get opcode of the non-atomic one from the specified atomic instruction for
14966 // 64-bit data type on 32-bit target with extra opcode.
14967 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14969 unsigned &ExtraOpc) {
14971 case X86::ATOMNAND6432:
14972 ExtraOpc = X86::NOT32r;
14973 HiOpc = X86::AND32rr;
14974 return X86::AND32rr;
14976 llvm_unreachable("Unhandled atomic-load-op opcode!");
14979 // Get pseudo CMOV opcode from the specified data type.
14980 static unsigned getPseudoCMOVOpc(EVT VT) {
14981 switch (VT.getSimpleVT().SimpleTy) {
14982 case MVT::i8: return X86::CMOV_GR8;
14983 case MVT::i16: return X86::CMOV_GR16;
14984 case MVT::i32: return X86::CMOV_GR32;
14988 llvm_unreachable("Unknown CMOV opcode!");
14991 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14992 // They will be translated into a spin-loop or compare-exchange loop from
14995 // dst = atomic-fetch-op MI.addr, MI.val
15001 // t1 = LOAD MI.addr
15003 // t4 = phi(t1, t3 / loop)
15004 // t2 = OP MI.val, t4
15006 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15012 MachineBasicBlock *
15013 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15014 MachineBasicBlock *MBB) const {
15015 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15016 DebugLoc DL = MI->getDebugLoc();
15018 MachineFunction *MF = MBB->getParent();
15019 MachineRegisterInfo &MRI = MF->getRegInfo();
15021 const BasicBlock *BB = MBB->getBasicBlock();
15022 MachineFunction::iterator I = MBB;
15025 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15026 "Unexpected number of operands");
15028 assert(MI->hasOneMemOperand() &&
15029 "Expected atomic-load-op to have one memoperand");
15031 // Memory Reference
15032 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15033 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15035 unsigned DstReg, SrcReg;
15036 unsigned MemOpndSlot;
15038 unsigned CurOp = 0;
15040 DstReg = MI->getOperand(CurOp++).getReg();
15041 MemOpndSlot = CurOp;
15042 CurOp += X86::AddrNumOperands;
15043 SrcReg = MI->getOperand(CurOp++).getReg();
15045 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15046 MVT::SimpleValueType VT = *RC->vt_begin();
15047 unsigned t1 = MRI.createVirtualRegister(RC);
15048 unsigned t2 = MRI.createVirtualRegister(RC);
15049 unsigned t3 = MRI.createVirtualRegister(RC);
15050 unsigned t4 = MRI.createVirtualRegister(RC);
15051 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15053 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15054 unsigned LOADOpc = getLoadOpcode(VT);
15056 // For the atomic load-arith operator, we generate
15059 // t1 = LOAD [MI.addr]
15061 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15062 // t1 = OP MI.val, EAX
15064 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15070 MachineBasicBlock *thisMBB = MBB;
15071 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15072 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15073 MF->insert(I, mainMBB);
15074 MF->insert(I, sinkMBB);
15076 MachineInstrBuilder MIB;
15078 // Transfer the remainder of BB and its successor edges to sinkMBB.
15079 sinkMBB->splice(sinkMBB->begin(), MBB,
15080 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15081 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15084 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15085 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15086 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15088 NewMO.setIsKill(false);
15089 MIB.addOperand(NewMO);
15091 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15092 unsigned flags = (*MMOI)->getFlags();
15093 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15094 MachineMemOperand *MMO =
15095 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15096 (*MMOI)->getSize(),
15097 (*MMOI)->getBaseAlignment(),
15098 (*MMOI)->getTBAAInfo(),
15099 (*MMOI)->getRanges());
15100 MIB.addMemOperand(MMO);
15103 thisMBB->addSuccessor(mainMBB);
15106 MachineBasicBlock *origMainMBB = mainMBB;
15109 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15110 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15112 unsigned Opc = MI->getOpcode();
15115 llvm_unreachable("Unhandled atomic-load-op opcode!");
15116 case X86::ATOMAND8:
15117 case X86::ATOMAND16:
15118 case X86::ATOMAND32:
15119 case X86::ATOMAND64:
15121 case X86::ATOMOR16:
15122 case X86::ATOMOR32:
15123 case X86::ATOMOR64:
15124 case X86::ATOMXOR8:
15125 case X86::ATOMXOR16:
15126 case X86::ATOMXOR32:
15127 case X86::ATOMXOR64: {
15128 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15129 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15133 case X86::ATOMNAND8:
15134 case X86::ATOMNAND16:
15135 case X86::ATOMNAND32:
15136 case X86::ATOMNAND64: {
15137 unsigned Tmp = MRI.createVirtualRegister(RC);
15139 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15140 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15142 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15145 case X86::ATOMMAX8:
15146 case X86::ATOMMAX16:
15147 case X86::ATOMMAX32:
15148 case X86::ATOMMAX64:
15149 case X86::ATOMMIN8:
15150 case X86::ATOMMIN16:
15151 case X86::ATOMMIN32:
15152 case X86::ATOMMIN64:
15153 case X86::ATOMUMAX8:
15154 case X86::ATOMUMAX16:
15155 case X86::ATOMUMAX32:
15156 case X86::ATOMUMAX64:
15157 case X86::ATOMUMIN8:
15158 case X86::ATOMUMIN16:
15159 case X86::ATOMUMIN32:
15160 case X86::ATOMUMIN64: {
15162 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15164 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15168 if (Subtarget->hasCMov()) {
15169 if (VT != MVT::i8) {
15171 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15175 // Promote i8 to i32 to use CMOV32
15176 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15177 const TargetRegisterClass *RC32 =
15178 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15179 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15180 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15181 unsigned Tmp = MRI.createVirtualRegister(RC32);
15183 unsigned Undef = MRI.createVirtualRegister(RC32);
15184 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15186 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15189 .addImm(X86::sub_8bit);
15190 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15193 .addImm(X86::sub_8bit);
15195 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15199 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15200 .addReg(Tmp, 0, X86::sub_8bit);
15203 // Use pseudo select and lower them.
15204 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15205 "Invalid atomic-load-op transformation!");
15206 unsigned SelOpc = getPseudoCMOVOpc(VT);
15207 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15208 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15209 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15210 .addReg(SrcReg).addReg(t4)
15212 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15213 // Replace the original PHI node as mainMBB is changed after CMOV
15215 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15216 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15217 Phi->eraseFromParent();
15223 // Copy PhyReg back from virtual register.
15224 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15227 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15228 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15229 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15231 NewMO.setIsKill(false);
15232 MIB.addOperand(NewMO);
15235 MIB.setMemRefs(MMOBegin, MMOEnd);
15237 // Copy PhyReg back to virtual register.
15238 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15241 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15243 mainMBB->addSuccessor(origMainMBB);
15244 mainMBB->addSuccessor(sinkMBB);
15247 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15248 TII->get(TargetOpcode::COPY), DstReg)
15251 MI->eraseFromParent();
15255 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15256 // instructions. They will be translated into a spin-loop or compare-exchange
15260 // dst = atomic-fetch-op MI.addr, MI.val
15266 // t1L = LOAD [MI.addr + 0]
15267 // t1H = LOAD [MI.addr + 4]
15269 // t4L = phi(t1L, t3L / loop)
15270 // t4H = phi(t1H, t3H / loop)
15271 // t2L = OP MI.val.lo, t4L
15272 // t2H = OP MI.val.hi, t4H
15277 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15285 MachineBasicBlock *
15286 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15287 MachineBasicBlock *MBB) const {
15288 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15289 DebugLoc DL = MI->getDebugLoc();
15291 MachineFunction *MF = MBB->getParent();
15292 MachineRegisterInfo &MRI = MF->getRegInfo();
15294 const BasicBlock *BB = MBB->getBasicBlock();
15295 MachineFunction::iterator I = MBB;
15298 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15299 "Unexpected number of operands");
15301 assert(MI->hasOneMemOperand() &&
15302 "Expected atomic-load-op32 to have one memoperand");
15304 // Memory Reference
15305 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15306 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15308 unsigned DstLoReg, DstHiReg;
15309 unsigned SrcLoReg, SrcHiReg;
15310 unsigned MemOpndSlot;
15312 unsigned CurOp = 0;
15314 DstLoReg = MI->getOperand(CurOp++).getReg();
15315 DstHiReg = MI->getOperand(CurOp++).getReg();
15316 MemOpndSlot = CurOp;
15317 CurOp += X86::AddrNumOperands;
15318 SrcLoReg = MI->getOperand(CurOp++).getReg();
15319 SrcHiReg = MI->getOperand(CurOp++).getReg();
15321 const TargetRegisterClass *RC = &X86::GR32RegClass;
15322 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15324 unsigned t1L = MRI.createVirtualRegister(RC);
15325 unsigned t1H = MRI.createVirtualRegister(RC);
15326 unsigned t2L = MRI.createVirtualRegister(RC);
15327 unsigned t2H = MRI.createVirtualRegister(RC);
15328 unsigned t3L = MRI.createVirtualRegister(RC);
15329 unsigned t3H = MRI.createVirtualRegister(RC);
15330 unsigned t4L = MRI.createVirtualRegister(RC);
15331 unsigned t4H = MRI.createVirtualRegister(RC);
15333 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15334 unsigned LOADOpc = X86::MOV32rm;
15336 // For the atomic load-arith operator, we generate
15339 // t1L = LOAD [MI.addr + 0]
15340 // t1H = LOAD [MI.addr + 4]
15342 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15343 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15344 // t2L = OP MI.val.lo, t4L
15345 // t2H = OP MI.val.hi, t4H
15348 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15356 MachineBasicBlock *thisMBB = MBB;
15357 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15358 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15359 MF->insert(I, mainMBB);
15360 MF->insert(I, sinkMBB);
15362 MachineInstrBuilder MIB;
15364 // Transfer the remainder of BB and its successor edges to sinkMBB.
15365 sinkMBB->splice(sinkMBB->begin(), MBB,
15366 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15367 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15371 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15372 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15373 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15375 NewMO.setIsKill(false);
15376 MIB.addOperand(NewMO);
15378 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15379 unsigned flags = (*MMOI)->getFlags();
15380 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15381 MachineMemOperand *MMO =
15382 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15383 (*MMOI)->getSize(),
15384 (*MMOI)->getBaseAlignment(),
15385 (*MMOI)->getTBAAInfo(),
15386 (*MMOI)->getRanges());
15387 MIB.addMemOperand(MMO);
15389 MachineInstr *LowMI = MIB;
15392 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15393 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15394 if (i == X86::AddrDisp) {
15395 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15397 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15399 NewMO.setIsKill(false);
15400 MIB.addOperand(NewMO);
15403 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15405 thisMBB->addSuccessor(mainMBB);
15408 MachineBasicBlock *origMainMBB = mainMBB;
15411 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15412 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15413 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15414 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15416 unsigned Opc = MI->getOpcode();
15419 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15420 case X86::ATOMAND6432:
15421 case X86::ATOMOR6432:
15422 case X86::ATOMXOR6432:
15423 case X86::ATOMADD6432:
15424 case X86::ATOMSUB6432: {
15426 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15427 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15429 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15433 case X86::ATOMNAND6432: {
15434 unsigned HiOpc, NOTOpc;
15435 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15436 unsigned TmpL = MRI.createVirtualRegister(RC);
15437 unsigned TmpH = MRI.createVirtualRegister(RC);
15438 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15440 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15442 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15443 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15446 case X86::ATOMMAX6432:
15447 case X86::ATOMMIN6432:
15448 case X86::ATOMUMAX6432:
15449 case X86::ATOMUMIN6432: {
15451 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15452 unsigned cL = MRI.createVirtualRegister(RC8);
15453 unsigned cH = MRI.createVirtualRegister(RC8);
15454 unsigned cL32 = MRI.createVirtualRegister(RC);
15455 unsigned cH32 = MRI.createVirtualRegister(RC);
15456 unsigned cc = MRI.createVirtualRegister(RC);
15457 // cl := cmp src_lo, lo
15458 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15459 .addReg(SrcLoReg).addReg(t4L);
15460 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15461 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15462 // ch := cmp src_hi, hi
15463 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15464 .addReg(SrcHiReg).addReg(t4H);
15465 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15466 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15467 // cc := if (src_hi == hi) ? cl : ch;
15468 if (Subtarget->hasCMov()) {
15469 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15470 .addReg(cH32).addReg(cL32);
15472 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15473 .addReg(cH32).addReg(cL32)
15474 .addImm(X86::COND_E);
15475 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15477 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15478 if (Subtarget->hasCMov()) {
15479 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15480 .addReg(SrcLoReg).addReg(t4L);
15481 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15482 .addReg(SrcHiReg).addReg(t4H);
15484 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15485 .addReg(SrcLoReg).addReg(t4L)
15486 .addImm(X86::COND_NE);
15487 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15488 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15489 // 2nd CMOV lowering.
15490 mainMBB->addLiveIn(X86::EFLAGS);
15491 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15492 .addReg(SrcHiReg).addReg(t4H)
15493 .addImm(X86::COND_NE);
15494 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15495 // Replace the original PHI node as mainMBB is changed after CMOV
15497 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15498 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15499 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15500 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15501 PhiL->eraseFromParent();
15502 PhiH->eraseFromParent();
15506 case X86::ATOMSWAP6432: {
15508 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15509 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15510 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15515 // Copy EDX:EAX back from HiReg:LoReg
15516 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15517 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15518 // Copy ECX:EBX from t1H:t1L
15519 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15520 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15522 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15523 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15524 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15526 NewMO.setIsKill(false);
15527 MIB.addOperand(NewMO);
15529 MIB.setMemRefs(MMOBegin, MMOEnd);
15531 // Copy EDX:EAX back to t3H:t3L
15532 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15533 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15535 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15537 mainMBB->addSuccessor(origMainMBB);
15538 mainMBB->addSuccessor(sinkMBB);
15541 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15542 TII->get(TargetOpcode::COPY), DstLoReg)
15544 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15545 TII->get(TargetOpcode::COPY), DstHiReg)
15548 MI->eraseFromParent();
15552 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15553 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15554 // in the .td file.
15555 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15556 const TargetInstrInfo *TII) {
15558 switch (MI->getOpcode()) {
15559 default: llvm_unreachable("illegal opcode!");
15560 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15561 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15562 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15563 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15564 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15565 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15566 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15567 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15570 DebugLoc dl = MI->getDebugLoc();
15571 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15573 unsigned NumArgs = MI->getNumOperands();
15574 for (unsigned i = 1; i < NumArgs; ++i) {
15575 MachineOperand &Op = MI->getOperand(i);
15576 if (!(Op.isReg() && Op.isImplicit()))
15577 MIB.addOperand(Op);
15579 if (MI->hasOneMemOperand())
15580 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15582 BuildMI(*BB, MI, dl,
15583 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15584 .addReg(X86::XMM0);
15586 MI->eraseFromParent();
15590 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15591 // defs in an instruction pattern
15592 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15593 const TargetInstrInfo *TII) {
15595 switch (MI->getOpcode()) {
15596 default: llvm_unreachable("illegal opcode!");
15597 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15598 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15599 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15600 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15601 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15602 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15603 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15604 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15607 DebugLoc dl = MI->getDebugLoc();
15608 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15610 unsigned NumArgs = MI->getNumOperands(); // remove the results
15611 for (unsigned i = 1; i < NumArgs; ++i) {
15612 MachineOperand &Op = MI->getOperand(i);
15613 if (!(Op.isReg() && Op.isImplicit()))
15614 MIB.addOperand(Op);
15616 if (MI->hasOneMemOperand())
15617 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15619 BuildMI(*BB, MI, dl,
15620 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15623 MI->eraseFromParent();
15627 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15628 const TargetInstrInfo *TII,
15629 const X86Subtarget* Subtarget) {
15630 DebugLoc dl = MI->getDebugLoc();
15632 // Address into RAX/EAX, other two args into ECX, EDX.
15633 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15634 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15635 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15636 for (int i = 0; i < X86::AddrNumOperands; ++i)
15637 MIB.addOperand(MI->getOperand(i));
15639 unsigned ValOps = X86::AddrNumOperands;
15640 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15641 .addReg(MI->getOperand(ValOps).getReg());
15642 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15643 .addReg(MI->getOperand(ValOps+1).getReg());
15645 // The instruction doesn't actually take any operands though.
15646 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15648 MI->eraseFromParent(); // The pseudo is gone now.
15652 MachineBasicBlock *
15653 X86TargetLowering::EmitVAARG64WithCustomInserter(
15655 MachineBasicBlock *MBB) const {
15656 // Emit va_arg instruction on X86-64.
15658 // Operands to this pseudo-instruction:
15659 // 0 ) Output : destination address (reg)
15660 // 1-5) Input : va_list address (addr, i64mem)
15661 // 6 ) ArgSize : Size (in bytes) of vararg type
15662 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15663 // 8 ) Align : Alignment of type
15664 // 9 ) EFLAGS (implicit-def)
15666 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15667 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15669 unsigned DestReg = MI->getOperand(0).getReg();
15670 MachineOperand &Base = MI->getOperand(1);
15671 MachineOperand &Scale = MI->getOperand(2);
15672 MachineOperand &Index = MI->getOperand(3);
15673 MachineOperand &Disp = MI->getOperand(4);
15674 MachineOperand &Segment = MI->getOperand(5);
15675 unsigned ArgSize = MI->getOperand(6).getImm();
15676 unsigned ArgMode = MI->getOperand(7).getImm();
15677 unsigned Align = MI->getOperand(8).getImm();
15679 // Memory Reference
15680 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15681 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15682 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15684 // Machine Information
15685 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15686 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15687 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15688 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15689 DebugLoc DL = MI->getDebugLoc();
15691 // struct va_list {
15694 // i64 overflow_area (address)
15695 // i64 reg_save_area (address)
15697 // sizeof(va_list) = 24
15698 // alignment(va_list) = 8
15700 unsigned TotalNumIntRegs = 6;
15701 unsigned TotalNumXMMRegs = 8;
15702 bool UseGPOffset = (ArgMode == 1);
15703 bool UseFPOffset = (ArgMode == 2);
15704 unsigned MaxOffset = TotalNumIntRegs * 8 +
15705 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15707 /* Align ArgSize to a multiple of 8 */
15708 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15709 bool NeedsAlign = (Align > 8);
15711 MachineBasicBlock *thisMBB = MBB;
15712 MachineBasicBlock *overflowMBB;
15713 MachineBasicBlock *offsetMBB;
15714 MachineBasicBlock *endMBB;
15716 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15717 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15718 unsigned OffsetReg = 0;
15720 if (!UseGPOffset && !UseFPOffset) {
15721 // If we only pull from the overflow region, we don't create a branch.
15722 // We don't need to alter control flow.
15723 OffsetDestReg = 0; // unused
15724 OverflowDestReg = DestReg;
15726 offsetMBB = nullptr;
15727 overflowMBB = thisMBB;
15730 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15731 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15732 // If not, pull from overflow_area. (branch to overflowMBB)
15737 // offsetMBB overflowMBB
15742 // Registers for the PHI in endMBB
15743 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15744 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15746 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15747 MachineFunction *MF = MBB->getParent();
15748 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15749 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15750 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15752 MachineFunction::iterator MBBIter = MBB;
15755 // Insert the new basic blocks
15756 MF->insert(MBBIter, offsetMBB);
15757 MF->insert(MBBIter, overflowMBB);
15758 MF->insert(MBBIter, endMBB);
15760 // Transfer the remainder of MBB and its successor edges to endMBB.
15761 endMBB->splice(endMBB->begin(), thisMBB,
15762 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15763 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15765 // Make offsetMBB and overflowMBB successors of thisMBB
15766 thisMBB->addSuccessor(offsetMBB);
15767 thisMBB->addSuccessor(overflowMBB);
15769 // endMBB is a successor of both offsetMBB and overflowMBB
15770 offsetMBB->addSuccessor(endMBB);
15771 overflowMBB->addSuccessor(endMBB);
15773 // Load the offset value into a register
15774 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15775 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15779 .addDisp(Disp, UseFPOffset ? 4 : 0)
15780 .addOperand(Segment)
15781 .setMemRefs(MMOBegin, MMOEnd);
15783 // Check if there is enough room left to pull this argument.
15784 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15786 .addImm(MaxOffset + 8 - ArgSizeA8);
15788 // Branch to "overflowMBB" if offset >= max
15789 // Fall through to "offsetMBB" otherwise
15790 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15791 .addMBB(overflowMBB);
15794 // In offsetMBB, emit code to use the reg_save_area.
15796 assert(OffsetReg != 0);
15798 // Read the reg_save_area address.
15799 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15800 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15805 .addOperand(Segment)
15806 .setMemRefs(MMOBegin, MMOEnd);
15808 // Zero-extend the offset
15809 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15810 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15813 .addImm(X86::sub_32bit);
15815 // Add the offset to the reg_save_area to get the final address.
15816 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15817 .addReg(OffsetReg64)
15818 .addReg(RegSaveReg);
15820 // Compute the offset for the next argument
15821 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15822 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15824 .addImm(UseFPOffset ? 16 : 8);
15826 // Store it back into the va_list.
15827 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15831 .addDisp(Disp, UseFPOffset ? 4 : 0)
15832 .addOperand(Segment)
15833 .addReg(NextOffsetReg)
15834 .setMemRefs(MMOBegin, MMOEnd);
15837 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15842 // Emit code to use overflow area
15845 // Load the overflow_area address into a register.
15846 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15847 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15852 .addOperand(Segment)
15853 .setMemRefs(MMOBegin, MMOEnd);
15855 // If we need to align it, do so. Otherwise, just copy the address
15856 // to OverflowDestReg.
15858 // Align the overflow address
15859 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15860 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15862 // aligned_addr = (addr + (align-1)) & ~(align-1)
15863 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15864 .addReg(OverflowAddrReg)
15867 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15869 .addImm(~(uint64_t)(Align-1));
15871 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15872 .addReg(OverflowAddrReg);
15875 // Compute the next overflow address after this argument.
15876 // (the overflow address should be kept 8-byte aligned)
15877 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15878 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15879 .addReg(OverflowDestReg)
15880 .addImm(ArgSizeA8);
15882 // Store the new overflow address.
15883 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15888 .addOperand(Segment)
15889 .addReg(NextAddrReg)
15890 .setMemRefs(MMOBegin, MMOEnd);
15892 // If we branched, emit the PHI to the front of endMBB.
15894 BuildMI(*endMBB, endMBB->begin(), DL,
15895 TII->get(X86::PHI), DestReg)
15896 .addReg(OffsetDestReg).addMBB(offsetMBB)
15897 .addReg(OverflowDestReg).addMBB(overflowMBB);
15900 // Erase the pseudo instruction
15901 MI->eraseFromParent();
15906 MachineBasicBlock *
15907 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15909 MachineBasicBlock *MBB) const {
15910 // Emit code to save XMM registers to the stack. The ABI says that the
15911 // number of registers to save is given in %al, so it's theoretically
15912 // possible to do an indirect jump trick to avoid saving all of them,
15913 // however this code takes a simpler approach and just executes all
15914 // of the stores if %al is non-zero. It's less code, and it's probably
15915 // easier on the hardware branch predictor, and stores aren't all that
15916 // expensive anyway.
15918 // Create the new basic blocks. One block contains all the XMM stores,
15919 // and one block is the final destination regardless of whether any
15920 // stores were performed.
15921 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15922 MachineFunction *F = MBB->getParent();
15923 MachineFunction::iterator MBBIter = MBB;
15925 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15926 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15927 F->insert(MBBIter, XMMSaveMBB);
15928 F->insert(MBBIter, EndMBB);
15930 // Transfer the remainder of MBB and its successor edges to EndMBB.
15931 EndMBB->splice(EndMBB->begin(), MBB,
15932 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15933 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15935 // The original block will now fall through to the XMM save block.
15936 MBB->addSuccessor(XMMSaveMBB);
15937 // The XMMSaveMBB will fall through to the end block.
15938 XMMSaveMBB->addSuccessor(EndMBB);
15940 // Now add the instructions.
15941 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15942 DebugLoc DL = MI->getDebugLoc();
15944 unsigned CountReg = MI->getOperand(0).getReg();
15945 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15946 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15948 if (!Subtarget->isTargetWin64()) {
15949 // If %al is 0, branch around the XMM save block.
15950 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15951 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15952 MBB->addSuccessor(EndMBB);
15955 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15956 // that was just emitted, but clearly shouldn't be "saved".
15957 assert((MI->getNumOperands() <= 3 ||
15958 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15959 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15960 && "Expected last argument to be EFLAGS");
15961 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15962 // In the XMM save block, save all the XMM argument registers.
15963 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15964 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15965 MachineMemOperand *MMO =
15966 F->getMachineMemOperand(
15967 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15968 MachineMemOperand::MOStore,
15969 /*Size=*/16, /*Align=*/16);
15970 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15971 .addFrameIndex(RegSaveFrameIndex)
15972 .addImm(/*Scale=*/1)
15973 .addReg(/*IndexReg=*/0)
15974 .addImm(/*Disp=*/Offset)
15975 .addReg(/*Segment=*/0)
15976 .addReg(MI->getOperand(i).getReg())
15977 .addMemOperand(MMO);
15980 MI->eraseFromParent(); // The pseudo instruction is gone now.
15985 // The EFLAGS operand of SelectItr might be missing a kill marker
15986 // because there were multiple uses of EFLAGS, and ISel didn't know
15987 // which to mark. Figure out whether SelectItr should have had a
15988 // kill marker, and set it if it should. Returns the correct kill
15990 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15991 MachineBasicBlock* BB,
15992 const TargetRegisterInfo* TRI) {
15993 // Scan forward through BB for a use/def of EFLAGS.
15994 MachineBasicBlock::iterator miI(std::next(SelectItr));
15995 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15996 const MachineInstr& mi = *miI;
15997 if (mi.readsRegister(X86::EFLAGS))
15999 if (mi.definesRegister(X86::EFLAGS))
16000 break; // Should have kill-flag - update below.
16003 // If we hit the end of the block, check whether EFLAGS is live into a
16005 if (miI == BB->end()) {
16006 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16007 sEnd = BB->succ_end();
16008 sItr != sEnd; ++sItr) {
16009 MachineBasicBlock* succ = *sItr;
16010 if (succ->isLiveIn(X86::EFLAGS))
16015 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16016 // out. SelectMI should have a kill flag on EFLAGS.
16017 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16021 MachineBasicBlock *
16022 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16023 MachineBasicBlock *BB) const {
16024 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16025 DebugLoc DL = MI->getDebugLoc();
16027 // To "insert" a SELECT_CC instruction, we actually have to insert the
16028 // diamond control-flow pattern. The incoming instruction knows the
16029 // destination vreg to set, the condition code register to branch on, the
16030 // true/false values to select between, and a branch opcode to use.
16031 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16032 MachineFunction::iterator It = BB;
16038 // cmpTY ccX, r1, r2
16040 // fallthrough --> copy0MBB
16041 MachineBasicBlock *thisMBB = BB;
16042 MachineFunction *F = BB->getParent();
16043 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16044 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16045 F->insert(It, copy0MBB);
16046 F->insert(It, sinkMBB);
16048 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16049 // live into the sink and copy blocks.
16050 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16051 if (!MI->killsRegister(X86::EFLAGS) &&
16052 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16053 copy0MBB->addLiveIn(X86::EFLAGS);
16054 sinkMBB->addLiveIn(X86::EFLAGS);
16057 // Transfer the remainder of BB and its successor edges to sinkMBB.
16058 sinkMBB->splice(sinkMBB->begin(), BB,
16059 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16060 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16062 // Add the true and fallthrough blocks as its successors.
16063 BB->addSuccessor(copy0MBB);
16064 BB->addSuccessor(sinkMBB);
16066 // Create the conditional branch instruction.
16068 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16069 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16072 // %FalseValue = ...
16073 // # fallthrough to sinkMBB
16074 copy0MBB->addSuccessor(sinkMBB);
16077 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16079 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16080 TII->get(X86::PHI), MI->getOperand(0).getReg())
16081 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16082 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16084 MI->eraseFromParent(); // The pseudo instruction is gone now.
16088 MachineBasicBlock *
16089 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16090 bool Is64Bit) const {
16091 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16092 DebugLoc DL = MI->getDebugLoc();
16093 MachineFunction *MF = BB->getParent();
16094 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16096 assert(MF->shouldSplitStack());
16098 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16099 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16102 // ... [Till the alloca]
16103 // If stacklet is not large enough, jump to mallocMBB
16106 // Allocate by subtracting from RSP
16107 // Jump to continueMBB
16110 // Allocate by call to runtime
16114 // [rest of original BB]
16117 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16118 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16119 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16121 MachineRegisterInfo &MRI = MF->getRegInfo();
16122 const TargetRegisterClass *AddrRegClass =
16123 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16125 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16126 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16127 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16128 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16129 sizeVReg = MI->getOperand(1).getReg(),
16130 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16132 MachineFunction::iterator MBBIter = BB;
16135 MF->insert(MBBIter, bumpMBB);
16136 MF->insert(MBBIter, mallocMBB);
16137 MF->insert(MBBIter, continueMBB);
16139 continueMBB->splice(continueMBB->begin(), BB,
16140 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16141 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16143 // Add code to the main basic block to check if the stack limit has been hit,
16144 // and if so, jump to mallocMBB otherwise to bumpMBB.
16145 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16146 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16147 .addReg(tmpSPVReg).addReg(sizeVReg);
16148 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16149 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16150 .addReg(SPLimitVReg);
16151 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16153 // bumpMBB simply decreases the stack pointer, since we know the current
16154 // stacklet has enough space.
16155 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16156 .addReg(SPLimitVReg);
16157 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16158 .addReg(SPLimitVReg);
16159 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16161 // Calls into a routine in libgcc to allocate more space from the heap.
16162 const uint32_t *RegMask =
16163 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16165 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16167 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16168 .addExternalSymbol("__morestack_allocate_stack_space")
16169 .addRegMask(RegMask)
16170 .addReg(X86::RDI, RegState::Implicit)
16171 .addReg(X86::RAX, RegState::ImplicitDefine);
16173 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16175 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16176 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16177 .addExternalSymbol("__morestack_allocate_stack_space")
16178 .addRegMask(RegMask)
16179 .addReg(X86::EAX, RegState::ImplicitDefine);
16183 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16186 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16187 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16188 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16190 // Set up the CFG correctly.
16191 BB->addSuccessor(bumpMBB);
16192 BB->addSuccessor(mallocMBB);
16193 mallocMBB->addSuccessor(continueMBB);
16194 bumpMBB->addSuccessor(continueMBB);
16196 // Take care of the PHI nodes.
16197 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16198 MI->getOperand(0).getReg())
16199 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16200 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16202 // Delete the original pseudo instruction.
16203 MI->eraseFromParent();
16206 return continueMBB;
16209 MachineBasicBlock *
16210 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16211 MachineBasicBlock *BB) const {
16212 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16213 DebugLoc DL = MI->getDebugLoc();
16215 assert(!Subtarget->isTargetMacho());
16217 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16218 // non-trivial part is impdef of ESP.
16220 if (Subtarget->isTargetWin64()) {
16221 if (Subtarget->isTargetCygMing()) {
16222 // ___chkstk(Mingw64):
16223 // Clobbers R10, R11, RAX and EFLAGS.
16225 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16226 .addExternalSymbol("___chkstk")
16227 .addReg(X86::RAX, RegState::Implicit)
16228 .addReg(X86::RSP, RegState::Implicit)
16229 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16230 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16231 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16233 // __chkstk(MSVCRT): does not update stack pointer.
16234 // Clobbers R10, R11 and EFLAGS.
16235 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16236 .addExternalSymbol("__chkstk")
16237 .addReg(X86::RAX, RegState::Implicit)
16238 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16239 // RAX has the offset to be subtracted from RSP.
16240 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16245 const char *StackProbeSymbol =
16246 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16248 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16249 .addExternalSymbol(StackProbeSymbol)
16250 .addReg(X86::EAX, RegState::Implicit)
16251 .addReg(X86::ESP, RegState::Implicit)
16252 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16253 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16254 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16257 MI->eraseFromParent(); // The pseudo instruction is gone now.
16261 MachineBasicBlock *
16262 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16263 MachineBasicBlock *BB) const {
16264 // This is pretty easy. We're taking the value that we received from
16265 // our load from the relocation, sticking it in either RDI (x86-64)
16266 // or EAX and doing an indirect call. The return value will then
16267 // be in the normal return register.
16268 const X86InstrInfo *TII
16269 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16270 DebugLoc DL = MI->getDebugLoc();
16271 MachineFunction *F = BB->getParent();
16273 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16274 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16276 // Get a register mask for the lowered call.
16277 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16278 // proper register mask.
16279 const uint32_t *RegMask =
16280 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16281 if (Subtarget->is64Bit()) {
16282 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16283 TII->get(X86::MOV64rm), X86::RDI)
16285 .addImm(0).addReg(0)
16286 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16287 MI->getOperand(3).getTargetFlags())
16289 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16290 addDirectMem(MIB, X86::RDI);
16291 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16292 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16293 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16294 TII->get(X86::MOV32rm), X86::EAX)
16296 .addImm(0).addReg(0)
16297 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16298 MI->getOperand(3).getTargetFlags())
16300 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16301 addDirectMem(MIB, X86::EAX);
16302 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16304 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16305 TII->get(X86::MOV32rm), X86::EAX)
16306 .addReg(TII->getGlobalBaseReg(F))
16307 .addImm(0).addReg(0)
16308 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16309 MI->getOperand(3).getTargetFlags())
16311 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16312 addDirectMem(MIB, X86::EAX);
16313 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16316 MI->eraseFromParent(); // The pseudo instruction is gone now.
16320 MachineBasicBlock *
16321 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16322 MachineBasicBlock *MBB) const {
16323 DebugLoc DL = MI->getDebugLoc();
16324 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16326 MachineFunction *MF = MBB->getParent();
16327 MachineRegisterInfo &MRI = MF->getRegInfo();
16329 const BasicBlock *BB = MBB->getBasicBlock();
16330 MachineFunction::iterator I = MBB;
16333 // Memory Reference
16334 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16335 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16338 unsigned MemOpndSlot = 0;
16340 unsigned CurOp = 0;
16342 DstReg = MI->getOperand(CurOp++).getReg();
16343 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16344 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16345 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16346 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16348 MemOpndSlot = CurOp;
16350 MVT PVT = getPointerTy();
16351 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16352 "Invalid Pointer Size!");
16354 // For v = setjmp(buf), we generate
16357 // buf[LabelOffset] = restoreMBB
16358 // SjLjSetup restoreMBB
16364 // v = phi(main, restore)
16369 MachineBasicBlock *thisMBB = MBB;
16370 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16371 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16372 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16373 MF->insert(I, mainMBB);
16374 MF->insert(I, sinkMBB);
16375 MF->push_back(restoreMBB);
16377 MachineInstrBuilder MIB;
16379 // Transfer the remainder of BB and its successor edges to sinkMBB.
16380 sinkMBB->splice(sinkMBB->begin(), MBB,
16381 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16382 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16385 unsigned PtrStoreOpc = 0;
16386 unsigned LabelReg = 0;
16387 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16388 Reloc::Model RM = getTargetMachine().getRelocationModel();
16389 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16390 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16392 // Prepare IP either in reg or imm.
16393 if (!UseImmLabel) {
16394 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16395 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16396 LabelReg = MRI.createVirtualRegister(PtrRC);
16397 if (Subtarget->is64Bit()) {
16398 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16402 .addMBB(restoreMBB)
16405 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16406 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16407 .addReg(XII->getGlobalBaseReg(MF))
16410 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16414 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16416 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16417 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16418 if (i == X86::AddrDisp)
16419 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16421 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16424 MIB.addReg(LabelReg);
16426 MIB.addMBB(restoreMBB);
16427 MIB.setMemRefs(MMOBegin, MMOEnd);
16429 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16430 .addMBB(restoreMBB);
16432 const X86RegisterInfo *RegInfo =
16433 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16434 MIB.addRegMask(RegInfo->getNoPreservedMask());
16435 thisMBB->addSuccessor(mainMBB);
16436 thisMBB->addSuccessor(restoreMBB);
16440 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16441 mainMBB->addSuccessor(sinkMBB);
16444 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16445 TII->get(X86::PHI), DstReg)
16446 .addReg(mainDstReg).addMBB(mainMBB)
16447 .addReg(restoreDstReg).addMBB(restoreMBB);
16450 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16451 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16452 restoreMBB->addSuccessor(sinkMBB);
16454 MI->eraseFromParent();
16458 MachineBasicBlock *
16459 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16460 MachineBasicBlock *MBB) const {
16461 DebugLoc DL = MI->getDebugLoc();
16462 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16464 MachineFunction *MF = MBB->getParent();
16465 MachineRegisterInfo &MRI = MF->getRegInfo();
16467 // Memory Reference
16468 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16469 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16471 MVT PVT = getPointerTy();
16472 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16473 "Invalid Pointer Size!");
16475 const TargetRegisterClass *RC =
16476 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16477 unsigned Tmp = MRI.createVirtualRegister(RC);
16478 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16479 const X86RegisterInfo *RegInfo =
16480 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16481 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16482 unsigned SP = RegInfo->getStackRegister();
16484 MachineInstrBuilder MIB;
16486 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16487 const int64_t SPOffset = 2 * PVT.getStoreSize();
16489 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16490 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16493 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16494 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16495 MIB.addOperand(MI->getOperand(i));
16496 MIB.setMemRefs(MMOBegin, MMOEnd);
16498 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16499 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16500 if (i == X86::AddrDisp)
16501 MIB.addDisp(MI->getOperand(i), LabelOffset);
16503 MIB.addOperand(MI->getOperand(i));
16505 MIB.setMemRefs(MMOBegin, MMOEnd);
16507 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16508 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16509 if (i == X86::AddrDisp)
16510 MIB.addDisp(MI->getOperand(i), SPOffset);
16512 MIB.addOperand(MI->getOperand(i));
16514 MIB.setMemRefs(MMOBegin, MMOEnd);
16516 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16518 MI->eraseFromParent();
16522 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16523 // accumulator loops. Writing back to the accumulator allows the coalescer
16524 // to remove extra copies in the loop.
16525 MachineBasicBlock *
16526 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16527 MachineBasicBlock *MBB) const {
16528 MachineOperand &AddendOp = MI->getOperand(3);
16530 // Bail out early if the addend isn't a register - we can't switch these.
16531 if (!AddendOp.isReg())
16534 MachineFunction &MF = *MBB->getParent();
16535 MachineRegisterInfo &MRI = MF.getRegInfo();
16537 // Check whether the addend is defined by a PHI:
16538 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16539 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16540 if (!AddendDef.isPHI())
16543 // Look for the following pattern:
16545 // %addend = phi [%entry, 0], [%loop, %result]
16547 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16551 // %addend = phi [%entry, 0], [%loop, %result]
16553 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16555 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16556 assert(AddendDef.getOperand(i).isReg());
16557 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16558 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16559 if (&PHISrcInst == MI) {
16560 // Found a matching instruction.
16561 unsigned NewFMAOpc = 0;
16562 switch (MI->getOpcode()) {
16563 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16564 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16565 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16566 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16567 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16568 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16569 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16570 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16571 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16572 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16573 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16574 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16575 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16576 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16577 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16578 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16579 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16580 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16581 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16582 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16583 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16584 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16585 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16586 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16587 default: llvm_unreachable("Unrecognized FMA variant.");
16590 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16591 MachineInstrBuilder MIB =
16592 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16593 .addOperand(MI->getOperand(0))
16594 .addOperand(MI->getOperand(3))
16595 .addOperand(MI->getOperand(2))
16596 .addOperand(MI->getOperand(1));
16597 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16598 MI->eraseFromParent();
16605 MachineBasicBlock *
16606 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16607 MachineBasicBlock *BB) const {
16608 switch (MI->getOpcode()) {
16609 default: llvm_unreachable("Unexpected instr type to insert");
16610 case X86::TAILJMPd64:
16611 case X86::TAILJMPr64:
16612 case X86::TAILJMPm64:
16613 llvm_unreachable("TAILJMP64 would not be touched here.");
16614 case X86::TCRETURNdi64:
16615 case X86::TCRETURNri64:
16616 case X86::TCRETURNmi64:
16618 case X86::WIN_ALLOCA:
16619 return EmitLoweredWinAlloca(MI, BB);
16620 case X86::SEG_ALLOCA_32:
16621 return EmitLoweredSegAlloca(MI, BB, false);
16622 case X86::SEG_ALLOCA_64:
16623 return EmitLoweredSegAlloca(MI, BB, true);
16624 case X86::TLSCall_32:
16625 case X86::TLSCall_64:
16626 return EmitLoweredTLSCall(MI, BB);
16627 case X86::CMOV_GR8:
16628 case X86::CMOV_FR32:
16629 case X86::CMOV_FR64:
16630 case X86::CMOV_V4F32:
16631 case X86::CMOV_V2F64:
16632 case X86::CMOV_V2I64:
16633 case X86::CMOV_V8F32:
16634 case X86::CMOV_V4F64:
16635 case X86::CMOV_V4I64:
16636 case X86::CMOV_V16F32:
16637 case X86::CMOV_V8F64:
16638 case X86::CMOV_V8I64:
16639 case X86::CMOV_GR16:
16640 case X86::CMOV_GR32:
16641 case X86::CMOV_RFP32:
16642 case X86::CMOV_RFP64:
16643 case X86::CMOV_RFP80:
16644 return EmitLoweredSelect(MI, BB);
16646 case X86::FP32_TO_INT16_IN_MEM:
16647 case X86::FP32_TO_INT32_IN_MEM:
16648 case X86::FP32_TO_INT64_IN_MEM:
16649 case X86::FP64_TO_INT16_IN_MEM:
16650 case X86::FP64_TO_INT32_IN_MEM:
16651 case X86::FP64_TO_INT64_IN_MEM:
16652 case X86::FP80_TO_INT16_IN_MEM:
16653 case X86::FP80_TO_INT32_IN_MEM:
16654 case X86::FP80_TO_INT64_IN_MEM: {
16655 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16656 DebugLoc DL = MI->getDebugLoc();
16658 // Change the floating point control register to use "round towards zero"
16659 // mode when truncating to an integer value.
16660 MachineFunction *F = BB->getParent();
16661 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16662 addFrameReference(BuildMI(*BB, MI, DL,
16663 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16665 // Load the old value of the high byte of the control word...
16667 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16668 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16671 // Set the high part to be round to zero...
16672 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16675 // Reload the modified control word now...
16676 addFrameReference(BuildMI(*BB, MI, DL,
16677 TII->get(X86::FLDCW16m)), CWFrameIdx);
16679 // Restore the memory image of control word to original value
16680 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16683 // Get the X86 opcode to use.
16685 switch (MI->getOpcode()) {
16686 default: llvm_unreachable("illegal opcode!");
16687 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16688 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16689 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16690 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16691 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16692 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16693 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16694 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16695 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16699 MachineOperand &Op = MI->getOperand(0);
16701 AM.BaseType = X86AddressMode::RegBase;
16702 AM.Base.Reg = Op.getReg();
16704 AM.BaseType = X86AddressMode::FrameIndexBase;
16705 AM.Base.FrameIndex = Op.getIndex();
16707 Op = MI->getOperand(1);
16709 AM.Scale = Op.getImm();
16710 Op = MI->getOperand(2);
16712 AM.IndexReg = Op.getImm();
16713 Op = MI->getOperand(3);
16714 if (Op.isGlobal()) {
16715 AM.GV = Op.getGlobal();
16717 AM.Disp = Op.getImm();
16719 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16720 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16722 // Reload the original control word now.
16723 addFrameReference(BuildMI(*BB, MI, DL,
16724 TII->get(X86::FLDCW16m)), CWFrameIdx);
16726 MI->eraseFromParent(); // The pseudo instruction is gone now.
16729 // String/text processing lowering.
16730 case X86::PCMPISTRM128REG:
16731 case X86::VPCMPISTRM128REG:
16732 case X86::PCMPISTRM128MEM:
16733 case X86::VPCMPISTRM128MEM:
16734 case X86::PCMPESTRM128REG:
16735 case X86::VPCMPESTRM128REG:
16736 case X86::PCMPESTRM128MEM:
16737 case X86::VPCMPESTRM128MEM:
16738 assert(Subtarget->hasSSE42() &&
16739 "Target must have SSE4.2 or AVX features enabled");
16740 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16742 // String/text processing lowering.
16743 case X86::PCMPISTRIREG:
16744 case X86::VPCMPISTRIREG:
16745 case X86::PCMPISTRIMEM:
16746 case X86::VPCMPISTRIMEM:
16747 case X86::PCMPESTRIREG:
16748 case X86::VPCMPESTRIREG:
16749 case X86::PCMPESTRIMEM:
16750 case X86::VPCMPESTRIMEM:
16751 assert(Subtarget->hasSSE42() &&
16752 "Target must have SSE4.2 or AVX features enabled");
16753 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16755 // Thread synchronization.
16757 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16761 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16763 // Atomic Lowering.
16764 case X86::ATOMAND8:
16765 case X86::ATOMAND16:
16766 case X86::ATOMAND32:
16767 case X86::ATOMAND64:
16770 case X86::ATOMOR16:
16771 case X86::ATOMOR32:
16772 case X86::ATOMOR64:
16774 case X86::ATOMXOR16:
16775 case X86::ATOMXOR8:
16776 case X86::ATOMXOR32:
16777 case X86::ATOMXOR64:
16779 case X86::ATOMNAND8:
16780 case X86::ATOMNAND16:
16781 case X86::ATOMNAND32:
16782 case X86::ATOMNAND64:
16784 case X86::ATOMMAX8:
16785 case X86::ATOMMAX16:
16786 case X86::ATOMMAX32:
16787 case X86::ATOMMAX64:
16789 case X86::ATOMMIN8:
16790 case X86::ATOMMIN16:
16791 case X86::ATOMMIN32:
16792 case X86::ATOMMIN64:
16794 case X86::ATOMUMAX8:
16795 case X86::ATOMUMAX16:
16796 case X86::ATOMUMAX32:
16797 case X86::ATOMUMAX64:
16799 case X86::ATOMUMIN8:
16800 case X86::ATOMUMIN16:
16801 case X86::ATOMUMIN32:
16802 case X86::ATOMUMIN64:
16803 return EmitAtomicLoadArith(MI, BB);
16805 // This group does 64-bit operations on a 32-bit host.
16806 case X86::ATOMAND6432:
16807 case X86::ATOMOR6432:
16808 case X86::ATOMXOR6432:
16809 case X86::ATOMNAND6432:
16810 case X86::ATOMADD6432:
16811 case X86::ATOMSUB6432:
16812 case X86::ATOMMAX6432:
16813 case X86::ATOMMIN6432:
16814 case X86::ATOMUMAX6432:
16815 case X86::ATOMUMIN6432:
16816 case X86::ATOMSWAP6432:
16817 return EmitAtomicLoadArith6432(MI, BB);
16819 case X86::VASTART_SAVE_XMM_REGS:
16820 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16822 case X86::VAARG_64:
16823 return EmitVAARG64WithCustomInserter(MI, BB);
16825 case X86::EH_SjLj_SetJmp32:
16826 case X86::EH_SjLj_SetJmp64:
16827 return emitEHSjLjSetJmp(MI, BB);
16829 case X86::EH_SjLj_LongJmp32:
16830 case X86::EH_SjLj_LongJmp64:
16831 return emitEHSjLjLongJmp(MI, BB);
16833 case TargetOpcode::STACKMAP:
16834 case TargetOpcode::PATCHPOINT:
16835 return emitPatchPoint(MI, BB);
16837 case X86::VFMADDPDr213r:
16838 case X86::VFMADDPSr213r:
16839 case X86::VFMADDSDr213r:
16840 case X86::VFMADDSSr213r:
16841 case X86::VFMSUBPDr213r:
16842 case X86::VFMSUBPSr213r:
16843 case X86::VFMSUBSDr213r:
16844 case X86::VFMSUBSSr213r:
16845 case X86::VFNMADDPDr213r:
16846 case X86::VFNMADDPSr213r:
16847 case X86::VFNMADDSDr213r:
16848 case X86::VFNMADDSSr213r:
16849 case X86::VFNMSUBPDr213r:
16850 case X86::VFNMSUBPSr213r:
16851 case X86::VFNMSUBSDr213r:
16852 case X86::VFNMSUBSSr213r:
16853 case X86::VFMADDPDr213rY:
16854 case X86::VFMADDPSr213rY:
16855 case X86::VFMSUBPDr213rY:
16856 case X86::VFMSUBPSr213rY:
16857 case X86::VFNMADDPDr213rY:
16858 case X86::VFNMADDPSr213rY:
16859 case X86::VFNMSUBPDr213rY:
16860 case X86::VFNMSUBPSr213rY:
16861 return emitFMA3Instr(MI, BB);
16865 //===----------------------------------------------------------------------===//
16866 // X86 Optimization Hooks
16867 //===----------------------------------------------------------------------===//
16869 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16872 const SelectionDAG &DAG,
16873 unsigned Depth) const {
16874 unsigned BitWidth = KnownZero.getBitWidth();
16875 unsigned Opc = Op.getOpcode();
16876 assert((Opc >= ISD::BUILTIN_OP_END ||
16877 Opc == ISD::INTRINSIC_WO_CHAIN ||
16878 Opc == ISD::INTRINSIC_W_CHAIN ||
16879 Opc == ISD::INTRINSIC_VOID) &&
16880 "Should use MaskedValueIsZero if you don't know whether Op"
16881 " is a target node!");
16883 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16897 // These nodes' second result is a boolean.
16898 if (Op.getResNo() == 0)
16901 case X86ISD::SETCC:
16902 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16904 case ISD::INTRINSIC_WO_CHAIN: {
16905 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16906 unsigned NumLoBits = 0;
16909 case Intrinsic::x86_sse_movmsk_ps:
16910 case Intrinsic::x86_avx_movmsk_ps_256:
16911 case Intrinsic::x86_sse2_movmsk_pd:
16912 case Intrinsic::x86_avx_movmsk_pd_256:
16913 case Intrinsic::x86_mmx_pmovmskb:
16914 case Intrinsic::x86_sse2_pmovmskb_128:
16915 case Intrinsic::x86_avx2_pmovmskb: {
16916 // High bits of movmskp{s|d}, pmovmskb are known zero.
16918 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16919 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16920 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16921 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16922 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16923 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16924 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16925 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16927 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16936 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16938 const SelectionDAG &,
16939 unsigned Depth) const {
16940 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16941 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16942 return Op.getValueType().getScalarType().getSizeInBits();
16948 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16949 /// node is a GlobalAddress + offset.
16950 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16951 const GlobalValue* &GA,
16952 int64_t &Offset) const {
16953 if (N->getOpcode() == X86ISD::Wrapper) {
16954 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16955 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16956 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16960 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16963 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16964 /// same as extracting the high 128-bit part of 256-bit vector and then
16965 /// inserting the result into the low part of a new 256-bit vector
16966 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16967 EVT VT = SVOp->getValueType(0);
16968 unsigned NumElems = VT.getVectorNumElements();
16970 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16971 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16972 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16973 SVOp->getMaskElt(j) >= 0)
16979 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16980 /// same as extracting the low 128-bit part of 256-bit vector and then
16981 /// inserting the result into the high part of a new 256-bit vector
16982 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16983 EVT VT = SVOp->getValueType(0);
16984 unsigned NumElems = VT.getVectorNumElements();
16986 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16987 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16988 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16989 SVOp->getMaskElt(j) >= 0)
16995 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16996 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16997 TargetLowering::DAGCombinerInfo &DCI,
16998 const X86Subtarget* Subtarget) {
17000 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17001 SDValue V1 = SVOp->getOperand(0);
17002 SDValue V2 = SVOp->getOperand(1);
17003 EVT VT = SVOp->getValueType(0);
17004 unsigned NumElems = VT.getVectorNumElements();
17006 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17007 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17011 // V UNDEF BUILD_VECTOR UNDEF
17013 // CONCAT_VECTOR CONCAT_VECTOR
17016 // RESULT: V + zero extended
17018 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17019 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17020 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17023 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17026 // To match the shuffle mask, the first half of the mask should
17027 // be exactly the first vector, and all the rest a splat with the
17028 // first element of the second one.
17029 for (unsigned i = 0; i != NumElems/2; ++i)
17030 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17031 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17034 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17035 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17036 if (Ld->hasNUsesOfValue(1, 0)) {
17037 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17038 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17040 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17042 Ld->getPointerInfo(),
17043 Ld->getAlignment(),
17044 false/*isVolatile*/, true/*ReadMem*/,
17045 false/*WriteMem*/);
17047 // Make sure the newly-created LOAD is in the same position as Ld in
17048 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17049 // and update uses of Ld's output chain to use the TokenFactor.
17050 if (Ld->hasAnyUseOfValue(1)) {
17051 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17052 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17053 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17054 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17055 SDValue(ResNode.getNode(), 1));
17058 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17062 // Emit a zeroed vector and insert the desired subvector on its
17064 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17065 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17066 return DCI.CombineTo(N, InsV);
17069 //===--------------------------------------------------------------------===//
17070 // Combine some shuffles into subvector extracts and inserts:
17073 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17074 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17075 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17076 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17077 return DCI.CombineTo(N, InsV);
17080 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17081 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17082 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17083 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17084 return DCI.CombineTo(N, InsV);
17090 /// PerformShuffleCombine - Performs several different shuffle combines.
17091 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17092 TargetLowering::DAGCombinerInfo &DCI,
17093 const X86Subtarget *Subtarget) {
17095 EVT VT = N->getValueType(0);
17097 // Don't create instructions with illegal types after legalize types has run.
17098 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17099 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17102 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17103 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17104 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17105 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17107 // Only handle 128 wide vector from here on.
17108 if (!VT.is128BitVector())
17111 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17112 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17113 // consecutive, non-overlapping, and in the right order.
17114 SmallVector<SDValue, 16> Elts;
17115 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17116 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17118 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17121 /// PerformTruncateCombine - Converts truncate operation to
17122 /// a sequence of vector shuffle operations.
17123 /// It is possible when we truncate 256-bit vector to 128-bit vector
17124 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17125 TargetLowering::DAGCombinerInfo &DCI,
17126 const X86Subtarget *Subtarget) {
17130 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17131 /// specific shuffle of a load can be folded into a single element load.
17132 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17133 /// shuffles have been customed lowered so we need to handle those here.
17134 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17135 TargetLowering::DAGCombinerInfo &DCI) {
17136 if (DCI.isBeforeLegalizeOps())
17139 SDValue InVec = N->getOperand(0);
17140 SDValue EltNo = N->getOperand(1);
17142 if (!isa<ConstantSDNode>(EltNo))
17145 EVT VT = InVec.getValueType();
17147 bool HasShuffleIntoBitcast = false;
17148 if (InVec.getOpcode() == ISD::BITCAST) {
17149 // Don't duplicate a load with other uses.
17150 if (!InVec.hasOneUse())
17152 EVT BCVT = InVec.getOperand(0).getValueType();
17153 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17155 InVec = InVec.getOperand(0);
17156 HasShuffleIntoBitcast = true;
17159 if (!isTargetShuffle(InVec.getOpcode()))
17162 // Don't duplicate a load with other uses.
17163 if (!InVec.hasOneUse())
17166 SmallVector<int, 16> ShuffleMask;
17168 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17172 // Select the input vector, guarding against out of range extract vector.
17173 unsigned NumElems = VT.getVectorNumElements();
17174 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17175 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17176 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17177 : InVec.getOperand(1);
17179 // If inputs to shuffle are the same for both ops, then allow 2 uses
17180 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17182 if (LdNode.getOpcode() == ISD::BITCAST) {
17183 // Don't duplicate a load with other uses.
17184 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17187 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17188 LdNode = LdNode.getOperand(0);
17191 if (!ISD::isNormalLoad(LdNode.getNode()))
17194 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17196 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17199 if (HasShuffleIntoBitcast) {
17200 // If there's a bitcast before the shuffle, check if the load type and
17201 // alignment is valid.
17202 unsigned Align = LN0->getAlignment();
17203 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17204 unsigned NewAlign = TLI.getDataLayout()->
17205 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17207 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17211 // All checks match so transform back to vector_shuffle so that DAG combiner
17212 // can finish the job
17215 // Create shuffle node taking into account the case that its a unary shuffle
17216 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17217 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17218 InVec.getOperand(0), Shuffle,
17220 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17221 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17225 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17226 /// generation and convert it from being a bunch of shuffles and extracts
17227 /// to a simple store and scalar loads to extract the elements.
17228 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17229 TargetLowering::DAGCombinerInfo &DCI) {
17230 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17231 if (NewOp.getNode())
17234 SDValue InputVector = N->getOperand(0);
17236 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17237 // from mmx to v2i32 has a single usage.
17238 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17239 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17240 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17241 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17242 N->getValueType(0),
17243 InputVector.getNode()->getOperand(0));
17245 // Only operate on vectors of 4 elements, where the alternative shuffling
17246 // gets to be more expensive.
17247 if (InputVector.getValueType() != MVT::v4i32)
17250 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17251 // single use which is a sign-extend or zero-extend, and all elements are
17253 SmallVector<SDNode *, 4> Uses;
17254 unsigned ExtractedElements = 0;
17255 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17256 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17257 if (UI.getUse().getResNo() != InputVector.getResNo())
17260 SDNode *Extract = *UI;
17261 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17264 if (Extract->getValueType(0) != MVT::i32)
17266 if (!Extract->hasOneUse())
17268 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17269 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17271 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17274 // Record which element was extracted.
17275 ExtractedElements |=
17276 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17278 Uses.push_back(Extract);
17281 // If not all the elements were used, this may not be worthwhile.
17282 if (ExtractedElements != 15)
17285 // Ok, we've now decided to do the transformation.
17286 SDLoc dl(InputVector);
17288 // Store the value to a temporary stack slot.
17289 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17290 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17291 MachinePointerInfo(), false, false, 0);
17293 // Replace each use (extract) with a load of the appropriate element.
17294 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17295 UE = Uses.end(); UI != UE; ++UI) {
17296 SDNode *Extract = *UI;
17298 // cOMpute the element's address.
17299 SDValue Idx = Extract->getOperand(1);
17301 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17302 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17304 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17306 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17307 StackPtr, OffsetVal);
17309 // Load the scalar.
17310 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17311 ScalarAddr, MachinePointerInfo(),
17312 false, false, false, 0);
17314 // Replace the exact with the load.
17315 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17318 // The replacement was made in place; don't return anything.
17322 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17323 static std::pair<unsigned, bool>
17324 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17325 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17326 if (!VT.isVector())
17327 return std::make_pair(0, false);
17329 bool NeedSplit = false;
17330 switch (VT.getSimpleVT().SimpleTy) {
17331 default: return std::make_pair(0, false);
17335 if (!Subtarget->hasAVX2())
17337 if (!Subtarget->hasAVX())
17338 return std::make_pair(0, false);
17343 if (!Subtarget->hasSSE2())
17344 return std::make_pair(0, false);
17347 // SSE2 has only a small subset of the operations.
17348 bool hasUnsigned = Subtarget->hasSSE41() ||
17349 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17350 bool hasSigned = Subtarget->hasSSE41() ||
17351 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17353 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17356 // Check for x CC y ? x : y.
17357 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17358 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17363 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17366 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17369 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17372 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17374 // Check for x CC y ? y : x -- a min/max with reversed arms.
17375 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17376 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17381 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17384 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17387 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17390 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17394 return std::make_pair(Opc, NeedSplit);
17397 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17399 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17400 TargetLowering::DAGCombinerInfo &DCI,
17401 const X86Subtarget *Subtarget) {
17403 SDValue Cond = N->getOperand(0);
17404 // Get the LHS/RHS of the select.
17405 SDValue LHS = N->getOperand(1);
17406 SDValue RHS = N->getOperand(2);
17407 EVT VT = LHS.getValueType();
17408 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17410 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17411 // instructions match the semantics of the common C idiom x<y?x:y but not
17412 // x<=y?x:y, because of how they handle negative zero (which can be
17413 // ignored in unsafe-math mode).
17414 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17415 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17416 (Subtarget->hasSSE2() ||
17417 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17418 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17420 unsigned Opcode = 0;
17421 // Check for x CC y ? x : y.
17422 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17423 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17427 // Converting this to a min would handle NaNs incorrectly, and swapping
17428 // the operands would cause it to handle comparisons between positive
17429 // and negative zero incorrectly.
17430 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17431 if (!DAG.getTarget().Options.UnsafeFPMath &&
17432 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17434 std::swap(LHS, RHS);
17436 Opcode = X86ISD::FMIN;
17439 // Converting this to a min would handle comparisons between positive
17440 // and negative zero incorrectly.
17441 if (!DAG.getTarget().Options.UnsafeFPMath &&
17442 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17444 Opcode = X86ISD::FMIN;
17447 // Converting this to a min would handle both negative zeros and NaNs
17448 // incorrectly, but we can swap the operands to fix both.
17449 std::swap(LHS, RHS);
17453 Opcode = X86ISD::FMIN;
17457 // Converting this to a max would handle comparisons between positive
17458 // and negative zero incorrectly.
17459 if (!DAG.getTarget().Options.UnsafeFPMath &&
17460 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17462 Opcode = X86ISD::FMAX;
17465 // Converting this to a max would handle NaNs incorrectly, and swapping
17466 // the operands would cause it to handle comparisons between positive
17467 // and negative zero incorrectly.
17468 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17469 if (!DAG.getTarget().Options.UnsafeFPMath &&
17470 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17472 std::swap(LHS, RHS);
17474 Opcode = X86ISD::FMAX;
17477 // Converting this to a max would handle both negative zeros and NaNs
17478 // incorrectly, but we can swap the operands to fix both.
17479 std::swap(LHS, RHS);
17483 Opcode = X86ISD::FMAX;
17486 // Check for x CC y ? y : x -- a min/max with reversed arms.
17487 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17488 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17492 // Converting this to a min would handle comparisons between positive
17493 // and negative zero incorrectly, and swapping the operands would
17494 // cause it to handle NaNs incorrectly.
17495 if (!DAG.getTarget().Options.UnsafeFPMath &&
17496 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17497 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17499 std::swap(LHS, RHS);
17501 Opcode = X86ISD::FMIN;
17504 // Converting this to a min would handle NaNs incorrectly.
17505 if (!DAG.getTarget().Options.UnsafeFPMath &&
17506 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17508 Opcode = X86ISD::FMIN;
17511 // Converting this to a min would handle both negative zeros and NaNs
17512 // incorrectly, but we can swap the operands to fix both.
17513 std::swap(LHS, RHS);
17517 Opcode = X86ISD::FMIN;
17521 // Converting this to a max would handle NaNs incorrectly.
17522 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17524 Opcode = X86ISD::FMAX;
17527 // Converting this to a max would handle comparisons between positive
17528 // and negative zero incorrectly, and swapping the operands would
17529 // cause it to handle NaNs incorrectly.
17530 if (!DAG.getTarget().Options.UnsafeFPMath &&
17531 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17532 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17534 std::swap(LHS, RHS);
17536 Opcode = X86ISD::FMAX;
17539 // Converting this to a max would handle both negative zeros and NaNs
17540 // incorrectly, but we can swap the operands to fix both.
17541 std::swap(LHS, RHS);
17545 Opcode = X86ISD::FMAX;
17551 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17554 EVT CondVT = Cond.getValueType();
17555 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17556 CondVT.getVectorElementType() == MVT::i1) {
17557 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17558 // lowering on AVX-512. In this case we convert it to
17559 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17560 // The same situation for all 128 and 256-bit vectors of i8 and i16
17561 EVT OpVT = LHS.getValueType();
17562 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17563 (OpVT.getVectorElementType() == MVT::i8 ||
17564 OpVT.getVectorElementType() == MVT::i16)) {
17565 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17566 DCI.AddToWorklist(Cond.getNode());
17567 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17570 // If this is a select between two integer constants, try to do some
17572 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17573 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17574 // Don't do this for crazy integer types.
17575 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17576 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17577 // so that TrueC (the true value) is larger than FalseC.
17578 bool NeedsCondInvert = false;
17580 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17581 // Efficiently invertible.
17582 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17583 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17584 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17585 NeedsCondInvert = true;
17586 std::swap(TrueC, FalseC);
17589 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17590 if (FalseC->getAPIntValue() == 0 &&
17591 TrueC->getAPIntValue().isPowerOf2()) {
17592 if (NeedsCondInvert) // Invert the condition if needed.
17593 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17594 DAG.getConstant(1, Cond.getValueType()));
17596 // Zero extend the condition if needed.
17597 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17599 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17600 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17601 DAG.getConstant(ShAmt, MVT::i8));
17604 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17605 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17606 if (NeedsCondInvert) // Invert the condition if needed.
17607 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17608 DAG.getConstant(1, Cond.getValueType()));
17610 // Zero extend the condition if needed.
17611 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17612 FalseC->getValueType(0), Cond);
17613 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17614 SDValue(FalseC, 0));
17617 // Optimize cases that will turn into an LEA instruction. This requires
17618 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17619 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17620 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17621 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17623 bool isFastMultiplier = false;
17625 switch ((unsigned char)Diff) {
17627 case 1: // result = add base, cond
17628 case 2: // result = lea base( , cond*2)
17629 case 3: // result = lea base(cond, cond*2)
17630 case 4: // result = lea base( , cond*4)
17631 case 5: // result = lea base(cond, cond*4)
17632 case 8: // result = lea base( , cond*8)
17633 case 9: // result = lea base(cond, cond*8)
17634 isFastMultiplier = true;
17639 if (isFastMultiplier) {
17640 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17641 if (NeedsCondInvert) // Invert the condition if needed.
17642 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17643 DAG.getConstant(1, Cond.getValueType()));
17645 // Zero extend the condition if needed.
17646 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17648 // Scale the condition by the difference.
17650 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17651 DAG.getConstant(Diff, Cond.getValueType()));
17653 // Add the base if non-zero.
17654 if (FalseC->getAPIntValue() != 0)
17655 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17656 SDValue(FalseC, 0));
17663 // Canonicalize max and min:
17664 // (x > y) ? x : y -> (x >= y) ? x : y
17665 // (x < y) ? x : y -> (x <= y) ? x : y
17666 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17667 // the need for an extra compare
17668 // against zero. e.g.
17669 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17671 // testl %edi, %edi
17673 // cmovgl %edi, %eax
17677 // cmovsl %eax, %edi
17678 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17679 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17680 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17681 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17686 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17687 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17688 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17689 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17694 // Early exit check
17695 if (!TLI.isTypeLegal(VT))
17698 // Match VSELECTs into subs with unsigned saturation.
17699 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17700 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17701 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17702 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17703 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17705 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17706 // left side invert the predicate to simplify logic below.
17708 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17710 CC = ISD::getSetCCInverse(CC, true);
17711 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17715 if (Other.getNode() && Other->getNumOperands() == 2 &&
17716 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17717 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17718 SDValue CondRHS = Cond->getOperand(1);
17720 // Look for a general sub with unsigned saturation first.
17721 // x >= y ? x-y : 0 --> subus x, y
17722 // x > y ? x-y : 0 --> subus x, y
17723 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17724 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17725 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17727 // If the RHS is a constant we have to reverse the const canonicalization.
17728 // x > C-1 ? x+-C : 0 --> subus x, C
17729 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17730 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17731 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17732 if (CondRHS.getConstantOperandVal(0) == -A-1)
17733 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17734 DAG.getConstant(-A, VT));
17737 // Another special case: If C was a sign bit, the sub has been
17738 // canonicalized into a xor.
17739 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17740 // it's safe to decanonicalize the xor?
17741 // x s< 0 ? x^C : 0 --> subus x, C
17742 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17743 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17744 isSplatVector(OpRHS.getNode())) {
17745 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17747 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17752 // Try to match a min/max vector operation.
17753 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17754 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17755 unsigned Opc = ret.first;
17756 bool NeedSplit = ret.second;
17758 if (Opc && NeedSplit) {
17759 unsigned NumElems = VT.getVectorNumElements();
17760 // Extract the LHS vectors
17761 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17762 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17764 // Extract the RHS vectors
17765 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17766 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17768 // Create min/max for each subvector
17769 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17770 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17772 // Merge the result
17773 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17775 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17778 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17779 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17780 // Check if SETCC has already been promoted
17781 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17782 // Check that condition value type matches vselect operand type
17785 assert(Cond.getValueType().isVector() &&
17786 "vector select expects a vector selector!");
17788 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17789 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17791 if (!TValIsAllOnes && !FValIsAllZeros) {
17792 // Try invert the condition if true value is not all 1s and false value
17794 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17795 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17797 if (TValIsAllZeros || FValIsAllOnes) {
17798 SDValue CC = Cond.getOperand(2);
17799 ISD::CondCode NewCC =
17800 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17801 Cond.getOperand(0).getValueType().isInteger());
17802 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17803 std::swap(LHS, RHS);
17804 TValIsAllOnes = FValIsAllOnes;
17805 FValIsAllZeros = TValIsAllZeros;
17809 if (TValIsAllOnes || FValIsAllZeros) {
17812 if (TValIsAllOnes && FValIsAllZeros)
17814 else if (TValIsAllOnes)
17815 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17816 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17817 else if (FValIsAllZeros)
17818 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17819 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17821 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17825 // Try to fold this VSELECT into a MOVSS/MOVSD
17826 if (N->getOpcode() == ISD::VSELECT &&
17827 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17828 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17829 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17830 bool CanFold = false;
17831 unsigned NumElems = Cond.getNumOperands();
17835 if (isZero(Cond.getOperand(0))) {
17838 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17839 // fold (vselect <0,-1> -> (movsd A, B)
17840 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17841 CanFold = isAllOnes(Cond.getOperand(i));
17842 } else if (isAllOnes(Cond.getOperand(0))) {
17846 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17847 // fold (vselect <-1,0> -> (movsd B, A)
17848 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17849 CanFold = isZero(Cond.getOperand(i));
17853 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17854 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17855 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17858 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17859 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17860 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17861 // (v2i64 (bitcast B)))))
17863 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17864 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17865 // (v2f64 (bitcast B)))))
17867 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17868 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17869 // (v2i64 (bitcast A)))))
17871 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17872 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17873 // (v2f64 (bitcast A)))))
17875 CanFold = (isZero(Cond.getOperand(0)) &&
17876 isZero(Cond.getOperand(1)) &&
17877 isAllOnes(Cond.getOperand(2)) &&
17878 isAllOnes(Cond.getOperand(3)));
17880 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17881 isAllOnes(Cond.getOperand(1)) &&
17882 isZero(Cond.getOperand(2)) &&
17883 isZero(Cond.getOperand(3))) {
17885 std::swap(LHS, RHS);
17889 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17890 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17891 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17892 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17894 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17900 // If we know that this node is legal then we know that it is going to be
17901 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17902 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17903 // to simplify previous instructions.
17904 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17905 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17906 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17908 // Don't optimize vector selects that map to mask-registers.
17912 // Check all uses of that condition operand to check whether it will be
17913 // consumed by non-BLEND instructions, which may depend on all bits are set
17915 for (SDNode::use_iterator I = Cond->use_begin(),
17916 E = Cond->use_end(); I != E; ++I)
17917 if (I->getOpcode() != ISD::VSELECT)
17918 // TODO: Add other opcodes eventually lowered into BLEND.
17921 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17922 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17924 APInt KnownZero, KnownOne;
17925 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17926 DCI.isBeforeLegalizeOps());
17927 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17928 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17929 DCI.CommitTargetLoweringOpt(TLO);
17935 // Check whether a boolean test is testing a boolean value generated by
17936 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17939 // Simplify the following patterns:
17940 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17941 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17942 // to (Op EFLAGS Cond)
17944 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17945 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17946 // to (Op EFLAGS !Cond)
17948 // where Op could be BRCOND or CMOV.
17950 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17951 // Quit if not CMP and SUB with its value result used.
17952 if (Cmp.getOpcode() != X86ISD::CMP &&
17953 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17956 // Quit if not used as a boolean value.
17957 if (CC != X86::COND_E && CC != X86::COND_NE)
17960 // Check CMP operands. One of them should be 0 or 1 and the other should be
17961 // an SetCC or extended from it.
17962 SDValue Op1 = Cmp.getOperand(0);
17963 SDValue Op2 = Cmp.getOperand(1);
17966 const ConstantSDNode* C = nullptr;
17967 bool needOppositeCond = (CC == X86::COND_E);
17968 bool checkAgainstTrue = false; // Is it a comparison against 1?
17970 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17972 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17974 else // Quit if all operands are not constants.
17977 if (C->getZExtValue() == 1) {
17978 needOppositeCond = !needOppositeCond;
17979 checkAgainstTrue = true;
17980 } else if (C->getZExtValue() != 0)
17981 // Quit if the constant is neither 0 or 1.
17984 bool truncatedToBoolWithAnd = false;
17985 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17986 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17987 SetCC.getOpcode() == ISD::TRUNCATE ||
17988 SetCC.getOpcode() == ISD::AND) {
17989 if (SetCC.getOpcode() == ISD::AND) {
17991 ConstantSDNode *CS;
17992 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17993 CS->getZExtValue() == 1)
17995 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17996 CS->getZExtValue() == 1)
18000 SetCC = SetCC.getOperand(OpIdx);
18001 truncatedToBoolWithAnd = true;
18003 SetCC = SetCC.getOperand(0);
18006 switch (SetCC.getOpcode()) {
18007 case X86ISD::SETCC_CARRY:
18008 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18009 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18010 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18011 // truncated to i1 using 'and'.
18012 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18014 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18015 "Invalid use of SETCC_CARRY!");
18017 case X86ISD::SETCC:
18018 // Set the condition code or opposite one if necessary.
18019 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18020 if (needOppositeCond)
18021 CC = X86::GetOppositeBranchCondition(CC);
18022 return SetCC.getOperand(1);
18023 case X86ISD::CMOV: {
18024 // Check whether false/true value has canonical one, i.e. 0 or 1.
18025 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18026 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18027 // Quit if true value is not a constant.
18030 // Quit if false value is not a constant.
18032 SDValue Op = SetCC.getOperand(0);
18033 // Skip 'zext' or 'trunc' node.
18034 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18035 Op.getOpcode() == ISD::TRUNCATE)
18036 Op = Op.getOperand(0);
18037 // A special case for rdrand/rdseed, where 0 is set if false cond is
18039 if ((Op.getOpcode() != X86ISD::RDRAND &&
18040 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18043 // Quit if false value is not the constant 0 or 1.
18044 bool FValIsFalse = true;
18045 if (FVal && FVal->getZExtValue() != 0) {
18046 if (FVal->getZExtValue() != 1)
18048 // If FVal is 1, opposite cond is needed.
18049 needOppositeCond = !needOppositeCond;
18050 FValIsFalse = false;
18052 // Quit if TVal is not the constant opposite of FVal.
18053 if (FValIsFalse && TVal->getZExtValue() != 1)
18055 if (!FValIsFalse && TVal->getZExtValue() != 0)
18057 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18058 if (needOppositeCond)
18059 CC = X86::GetOppositeBranchCondition(CC);
18060 return SetCC.getOperand(3);
18067 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18068 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18069 TargetLowering::DAGCombinerInfo &DCI,
18070 const X86Subtarget *Subtarget) {
18073 // If the flag operand isn't dead, don't touch this CMOV.
18074 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18077 SDValue FalseOp = N->getOperand(0);
18078 SDValue TrueOp = N->getOperand(1);
18079 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18080 SDValue Cond = N->getOperand(3);
18082 if (CC == X86::COND_E || CC == X86::COND_NE) {
18083 switch (Cond.getOpcode()) {
18087 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18088 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18089 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18095 Flags = checkBoolTestSetCCCombine(Cond, CC);
18096 if (Flags.getNode() &&
18097 // Extra check as FCMOV only supports a subset of X86 cond.
18098 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18099 SDValue Ops[] = { FalseOp, TrueOp,
18100 DAG.getConstant(CC, MVT::i8), Flags };
18101 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18104 // If this is a select between two integer constants, try to do some
18105 // optimizations. Note that the operands are ordered the opposite of SELECT
18107 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18108 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18109 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18110 // larger than FalseC (the false value).
18111 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18112 CC = X86::GetOppositeBranchCondition(CC);
18113 std::swap(TrueC, FalseC);
18114 std::swap(TrueOp, FalseOp);
18117 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18118 // This is efficient for any integer data type (including i8/i16) and
18120 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18121 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18122 DAG.getConstant(CC, MVT::i8), Cond);
18124 // Zero extend the condition if needed.
18125 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18127 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18128 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18129 DAG.getConstant(ShAmt, MVT::i8));
18130 if (N->getNumValues() == 2) // Dead flag value?
18131 return DCI.CombineTo(N, Cond, SDValue());
18135 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18136 // for any integer data type, including i8/i16.
18137 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18138 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18139 DAG.getConstant(CC, MVT::i8), Cond);
18141 // Zero extend the condition if needed.
18142 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18143 FalseC->getValueType(0), Cond);
18144 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18145 SDValue(FalseC, 0));
18147 if (N->getNumValues() == 2) // Dead flag value?
18148 return DCI.CombineTo(N, Cond, SDValue());
18152 // Optimize cases that will turn into an LEA instruction. This requires
18153 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18154 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18155 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18156 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18158 bool isFastMultiplier = false;
18160 switch ((unsigned char)Diff) {
18162 case 1: // result = add base, cond
18163 case 2: // result = lea base( , cond*2)
18164 case 3: // result = lea base(cond, cond*2)
18165 case 4: // result = lea base( , cond*4)
18166 case 5: // result = lea base(cond, cond*4)
18167 case 8: // result = lea base( , cond*8)
18168 case 9: // result = lea base(cond, cond*8)
18169 isFastMultiplier = true;
18174 if (isFastMultiplier) {
18175 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18176 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18177 DAG.getConstant(CC, MVT::i8), Cond);
18178 // Zero extend the condition if needed.
18179 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18181 // Scale the condition by the difference.
18183 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18184 DAG.getConstant(Diff, Cond.getValueType()));
18186 // Add the base if non-zero.
18187 if (FalseC->getAPIntValue() != 0)
18188 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18189 SDValue(FalseC, 0));
18190 if (N->getNumValues() == 2) // Dead flag value?
18191 return DCI.CombineTo(N, Cond, SDValue());
18198 // Handle these cases:
18199 // (select (x != c), e, c) -> select (x != c), e, x),
18200 // (select (x == c), c, e) -> select (x == c), x, e)
18201 // where the c is an integer constant, and the "select" is the combination
18202 // of CMOV and CMP.
18204 // The rationale for this change is that the conditional-move from a constant
18205 // needs two instructions, however, conditional-move from a register needs
18206 // only one instruction.
18208 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18209 // some instruction-combining opportunities. This opt needs to be
18210 // postponed as late as possible.
18212 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18213 // the DCI.xxxx conditions are provided to postpone the optimization as
18214 // late as possible.
18216 ConstantSDNode *CmpAgainst = nullptr;
18217 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18218 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18219 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18221 if (CC == X86::COND_NE &&
18222 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18223 CC = X86::GetOppositeBranchCondition(CC);
18224 std::swap(TrueOp, FalseOp);
18227 if (CC == X86::COND_E &&
18228 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18229 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18230 DAG.getConstant(CC, MVT::i8), Cond };
18231 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18239 /// PerformMulCombine - Optimize a single multiply with constant into two
18240 /// in order to implement it with two cheaper instructions, e.g.
18241 /// LEA + SHL, LEA + LEA.
18242 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18243 TargetLowering::DAGCombinerInfo &DCI) {
18244 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18247 EVT VT = N->getValueType(0);
18248 if (VT != MVT::i64)
18251 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18254 uint64_t MulAmt = C->getZExtValue();
18255 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18258 uint64_t MulAmt1 = 0;
18259 uint64_t MulAmt2 = 0;
18260 if ((MulAmt % 9) == 0) {
18262 MulAmt2 = MulAmt / 9;
18263 } else if ((MulAmt % 5) == 0) {
18265 MulAmt2 = MulAmt / 5;
18266 } else if ((MulAmt % 3) == 0) {
18268 MulAmt2 = MulAmt / 3;
18271 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18274 if (isPowerOf2_64(MulAmt2) &&
18275 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18276 // If second multiplifer is pow2, issue it first. We want the multiply by
18277 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18279 std::swap(MulAmt1, MulAmt2);
18282 if (isPowerOf2_64(MulAmt1))
18283 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18284 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18286 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18287 DAG.getConstant(MulAmt1, VT));
18289 if (isPowerOf2_64(MulAmt2))
18290 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18291 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18293 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18294 DAG.getConstant(MulAmt2, VT));
18296 // Do not add new nodes to DAG combiner worklist.
18297 DCI.CombineTo(N, NewMul, false);
18302 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18303 SDValue N0 = N->getOperand(0);
18304 SDValue N1 = N->getOperand(1);
18305 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18306 EVT VT = N0.getValueType();
18308 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18309 // since the result of setcc_c is all zero's or all ones.
18310 if (VT.isInteger() && !VT.isVector() &&
18311 N1C && N0.getOpcode() == ISD::AND &&
18312 N0.getOperand(1).getOpcode() == ISD::Constant) {
18313 SDValue N00 = N0.getOperand(0);
18314 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18315 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18316 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18317 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18318 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18319 APInt ShAmt = N1C->getAPIntValue();
18320 Mask = Mask.shl(ShAmt);
18322 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18323 N00, DAG.getConstant(Mask, VT));
18327 // Hardware support for vector shifts is sparse which makes us scalarize the
18328 // vector operations in many cases. Also, on sandybridge ADD is faster than
18330 // (shl V, 1) -> add V,V
18331 if (isSplatVector(N1.getNode())) {
18332 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18333 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18334 // We shift all of the values by one. In many cases we do not have
18335 // hardware support for this operation. This is better expressed as an ADD
18337 if (N1C && (1 == N1C->getZExtValue())) {
18338 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18345 /// \brief Returns a vector of 0s if the node in input is a vector logical
18346 /// shift by a constant amount which is known to be bigger than or equal
18347 /// to the vector element size in bits.
18348 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18349 const X86Subtarget *Subtarget) {
18350 EVT VT = N->getValueType(0);
18352 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18353 (!Subtarget->hasInt256() ||
18354 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18357 SDValue Amt = N->getOperand(1);
18359 if (isSplatVector(Amt.getNode())) {
18360 SDValue SclrAmt = Amt->getOperand(0);
18361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18362 APInt ShiftAmt = C->getAPIntValue();
18363 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18365 // SSE2/AVX2 logical shifts always return a vector of 0s
18366 // if the shift amount is bigger than or equal to
18367 // the element size. The constant shift amount will be
18368 // encoded as a 8-bit immediate.
18369 if (ShiftAmt.trunc(8).uge(MaxAmount))
18370 return getZeroVector(VT, Subtarget, DAG, DL);
18377 /// PerformShiftCombine - Combine shifts.
18378 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18379 TargetLowering::DAGCombinerInfo &DCI,
18380 const X86Subtarget *Subtarget) {
18381 if (N->getOpcode() == ISD::SHL) {
18382 SDValue V = PerformSHLCombine(N, DAG);
18383 if (V.getNode()) return V;
18386 if (N->getOpcode() != ISD::SRA) {
18387 // Try to fold this logical shift into a zero vector.
18388 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18389 if (V.getNode()) return V;
18395 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18396 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18397 // and friends. Likewise for OR -> CMPNEQSS.
18398 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18399 TargetLowering::DAGCombinerInfo &DCI,
18400 const X86Subtarget *Subtarget) {
18403 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18404 // we're requiring SSE2 for both.
18405 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18406 SDValue N0 = N->getOperand(0);
18407 SDValue N1 = N->getOperand(1);
18408 SDValue CMP0 = N0->getOperand(1);
18409 SDValue CMP1 = N1->getOperand(1);
18412 // The SETCCs should both refer to the same CMP.
18413 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18416 SDValue CMP00 = CMP0->getOperand(0);
18417 SDValue CMP01 = CMP0->getOperand(1);
18418 EVT VT = CMP00.getValueType();
18420 if (VT == MVT::f32 || VT == MVT::f64) {
18421 bool ExpectingFlags = false;
18422 // Check for any users that want flags:
18423 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18424 !ExpectingFlags && UI != UE; ++UI)
18425 switch (UI->getOpcode()) {
18430 ExpectingFlags = true;
18432 case ISD::CopyToReg:
18433 case ISD::SIGN_EXTEND:
18434 case ISD::ZERO_EXTEND:
18435 case ISD::ANY_EXTEND:
18439 if (!ExpectingFlags) {
18440 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18441 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18443 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18444 X86::CondCode tmp = cc0;
18449 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18450 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18451 // FIXME: need symbolic constants for these magic numbers.
18452 // See X86ATTInstPrinter.cpp:printSSECC().
18453 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18454 if (Subtarget->hasAVX512()) {
18455 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18456 CMP01, DAG.getConstant(x86cc, MVT::i8));
18457 if (N->getValueType(0) != MVT::i1)
18458 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18462 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18463 CMP00.getValueType(), CMP00, CMP01,
18464 DAG.getConstant(x86cc, MVT::i8));
18466 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18467 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18469 if (is64BitFP && !Subtarget->is64Bit()) {
18470 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18471 // 64-bit integer, since that's not a legal type. Since
18472 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18473 // bits, but can do this little dance to extract the lowest 32 bits
18474 // and work with those going forward.
18475 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18477 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18479 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18480 Vector32, DAG.getIntPtrConstant(0));
18484 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18485 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18486 DAG.getConstant(1, IntVT));
18487 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18488 return OneBitOfTruth;
18496 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18497 /// so it can be folded inside ANDNP.
18498 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18499 EVT VT = N->getValueType(0);
18501 // Match direct AllOnes for 128 and 256-bit vectors
18502 if (ISD::isBuildVectorAllOnes(N))
18505 // Look through a bit convert.
18506 if (N->getOpcode() == ISD::BITCAST)
18507 N = N->getOperand(0).getNode();
18509 // Sometimes the operand may come from a insert_subvector building a 256-bit
18511 if (VT.is256BitVector() &&
18512 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18513 SDValue V1 = N->getOperand(0);
18514 SDValue V2 = N->getOperand(1);
18516 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18517 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18518 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18519 ISD::isBuildVectorAllOnes(V2.getNode()))
18526 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18527 // register. In most cases we actually compare or select YMM-sized registers
18528 // and mixing the two types creates horrible code. This method optimizes
18529 // some of the transition sequences.
18530 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18531 TargetLowering::DAGCombinerInfo &DCI,
18532 const X86Subtarget *Subtarget) {
18533 EVT VT = N->getValueType(0);
18534 if (!VT.is256BitVector())
18537 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18538 N->getOpcode() == ISD::ZERO_EXTEND ||
18539 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18541 SDValue Narrow = N->getOperand(0);
18542 EVT NarrowVT = Narrow->getValueType(0);
18543 if (!NarrowVT.is128BitVector())
18546 if (Narrow->getOpcode() != ISD::XOR &&
18547 Narrow->getOpcode() != ISD::AND &&
18548 Narrow->getOpcode() != ISD::OR)
18551 SDValue N0 = Narrow->getOperand(0);
18552 SDValue N1 = Narrow->getOperand(1);
18555 // The Left side has to be a trunc.
18556 if (N0.getOpcode() != ISD::TRUNCATE)
18559 // The type of the truncated inputs.
18560 EVT WideVT = N0->getOperand(0)->getValueType(0);
18564 // The right side has to be a 'trunc' or a constant vector.
18565 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18566 bool RHSConst = (isSplatVector(N1.getNode()) &&
18567 isa<ConstantSDNode>(N1->getOperand(0)));
18568 if (!RHSTrunc && !RHSConst)
18571 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18573 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18576 // Set N0 and N1 to hold the inputs to the new wide operation.
18577 N0 = N0->getOperand(0);
18579 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18580 N1->getOperand(0));
18581 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18582 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18583 } else if (RHSTrunc) {
18584 N1 = N1->getOperand(0);
18587 // Generate the wide operation.
18588 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18589 unsigned Opcode = N->getOpcode();
18591 case ISD::ANY_EXTEND:
18593 case ISD::ZERO_EXTEND: {
18594 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18595 APInt Mask = APInt::getAllOnesValue(InBits);
18596 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18597 return DAG.getNode(ISD::AND, DL, VT,
18598 Op, DAG.getConstant(Mask, VT));
18600 case ISD::SIGN_EXTEND:
18601 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18602 Op, DAG.getValueType(NarrowVT));
18604 llvm_unreachable("Unexpected opcode");
18608 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18609 TargetLowering::DAGCombinerInfo &DCI,
18610 const X86Subtarget *Subtarget) {
18611 EVT VT = N->getValueType(0);
18612 if (DCI.isBeforeLegalizeOps())
18615 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18619 // Create BEXTR instructions
18620 // BEXTR is ((X >> imm) & (2**size-1))
18621 if (VT == MVT::i32 || VT == MVT::i64) {
18622 SDValue N0 = N->getOperand(0);
18623 SDValue N1 = N->getOperand(1);
18626 // Check for BEXTR.
18627 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18628 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18629 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18630 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18631 if (MaskNode && ShiftNode) {
18632 uint64_t Mask = MaskNode->getZExtValue();
18633 uint64_t Shift = ShiftNode->getZExtValue();
18634 if (isMask_64(Mask)) {
18635 uint64_t MaskSize = CountPopulation_64(Mask);
18636 if (Shift + MaskSize <= VT.getSizeInBits())
18637 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18638 DAG.getConstant(Shift | (MaskSize << 8), VT));
18646 // Want to form ANDNP nodes:
18647 // 1) In the hopes of then easily combining them with OR and AND nodes
18648 // to form PBLEND/PSIGN.
18649 // 2) To match ANDN packed intrinsics
18650 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18653 SDValue N0 = N->getOperand(0);
18654 SDValue N1 = N->getOperand(1);
18657 // Check LHS for vnot
18658 if (N0.getOpcode() == ISD::XOR &&
18659 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18660 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18661 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18663 // Check RHS for vnot
18664 if (N1.getOpcode() == ISD::XOR &&
18665 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18666 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18667 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18672 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18673 TargetLowering::DAGCombinerInfo &DCI,
18674 const X86Subtarget *Subtarget) {
18675 if (DCI.isBeforeLegalizeOps())
18678 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18682 SDValue N0 = N->getOperand(0);
18683 SDValue N1 = N->getOperand(1);
18684 EVT VT = N->getValueType(0);
18686 // look for psign/blend
18687 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18688 if (!Subtarget->hasSSSE3() ||
18689 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18692 // Canonicalize pandn to RHS
18693 if (N0.getOpcode() == X86ISD::ANDNP)
18695 // or (and (m, y), (pandn m, x))
18696 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18697 SDValue Mask = N1.getOperand(0);
18698 SDValue X = N1.getOperand(1);
18700 if (N0.getOperand(0) == Mask)
18701 Y = N0.getOperand(1);
18702 if (N0.getOperand(1) == Mask)
18703 Y = N0.getOperand(0);
18705 // Check to see if the mask appeared in both the AND and ANDNP and
18709 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18710 // Look through mask bitcast.
18711 if (Mask.getOpcode() == ISD::BITCAST)
18712 Mask = Mask.getOperand(0);
18713 if (X.getOpcode() == ISD::BITCAST)
18714 X = X.getOperand(0);
18715 if (Y.getOpcode() == ISD::BITCAST)
18716 Y = Y.getOperand(0);
18718 EVT MaskVT = Mask.getValueType();
18720 // Validate that the Mask operand is a vector sra node.
18721 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18722 // there is no psrai.b
18723 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18724 unsigned SraAmt = ~0;
18725 if (Mask.getOpcode() == ISD::SRA) {
18726 SDValue Amt = Mask.getOperand(1);
18727 if (isSplatVector(Amt.getNode())) {
18728 SDValue SclrAmt = Amt->getOperand(0);
18729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18730 SraAmt = C->getZExtValue();
18732 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18733 SDValue SraC = Mask.getOperand(1);
18734 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18736 if ((SraAmt + 1) != EltBits)
18741 // Now we know we at least have a plendvb with the mask val. See if
18742 // we can form a psignb/w/d.
18743 // psign = x.type == y.type == mask.type && y = sub(0, x);
18744 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18745 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18746 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18747 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18748 "Unsupported VT for PSIGN");
18749 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18750 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18752 // PBLENDVB only available on SSE 4.1
18753 if (!Subtarget->hasSSE41())
18756 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18758 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18759 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18760 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18761 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18762 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18766 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18769 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18770 MachineFunction &MF = DAG.getMachineFunction();
18771 bool OptForSize = MF.getFunction()->getAttributes().
18772 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18774 // SHLD/SHRD instructions have lower register pressure, but on some
18775 // platforms they have higher latency than the equivalent
18776 // series of shifts/or that would otherwise be generated.
18777 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18778 // have higher latencies and we are not optimizing for size.
18779 if (!OptForSize && Subtarget->isSHLDSlow())
18782 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18784 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18786 if (!N0.hasOneUse() || !N1.hasOneUse())
18789 SDValue ShAmt0 = N0.getOperand(1);
18790 if (ShAmt0.getValueType() != MVT::i8)
18792 SDValue ShAmt1 = N1.getOperand(1);
18793 if (ShAmt1.getValueType() != MVT::i8)
18795 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18796 ShAmt0 = ShAmt0.getOperand(0);
18797 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18798 ShAmt1 = ShAmt1.getOperand(0);
18801 unsigned Opc = X86ISD::SHLD;
18802 SDValue Op0 = N0.getOperand(0);
18803 SDValue Op1 = N1.getOperand(0);
18804 if (ShAmt0.getOpcode() == ISD::SUB) {
18805 Opc = X86ISD::SHRD;
18806 std::swap(Op0, Op1);
18807 std::swap(ShAmt0, ShAmt1);
18810 unsigned Bits = VT.getSizeInBits();
18811 if (ShAmt1.getOpcode() == ISD::SUB) {
18812 SDValue Sum = ShAmt1.getOperand(0);
18813 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18814 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18815 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18816 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18817 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18818 return DAG.getNode(Opc, DL, VT,
18820 DAG.getNode(ISD::TRUNCATE, DL,
18823 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18824 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18826 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18827 return DAG.getNode(Opc, DL, VT,
18828 N0.getOperand(0), N1.getOperand(0),
18829 DAG.getNode(ISD::TRUNCATE, DL,
18836 // Generate NEG and CMOV for integer abs.
18837 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18838 EVT VT = N->getValueType(0);
18840 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18841 // 8-bit integer abs to NEG and CMOV.
18842 if (VT.isInteger() && VT.getSizeInBits() == 8)
18845 SDValue N0 = N->getOperand(0);
18846 SDValue N1 = N->getOperand(1);
18849 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18850 // and change it to SUB and CMOV.
18851 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18852 N0.getOpcode() == ISD::ADD &&
18853 N0.getOperand(1) == N1 &&
18854 N1.getOpcode() == ISD::SRA &&
18855 N1.getOperand(0) == N0.getOperand(0))
18856 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18857 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18858 // Generate SUB & CMOV.
18859 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18860 DAG.getConstant(0, VT), N0.getOperand(0));
18862 SDValue Ops[] = { N0.getOperand(0), Neg,
18863 DAG.getConstant(X86::COND_GE, MVT::i8),
18864 SDValue(Neg.getNode(), 1) };
18865 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18870 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18871 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18872 TargetLowering::DAGCombinerInfo &DCI,
18873 const X86Subtarget *Subtarget) {
18874 if (DCI.isBeforeLegalizeOps())
18877 if (Subtarget->hasCMov()) {
18878 SDValue RV = performIntegerAbsCombine(N, DAG);
18886 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18887 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18888 TargetLowering::DAGCombinerInfo &DCI,
18889 const X86Subtarget *Subtarget) {
18890 LoadSDNode *Ld = cast<LoadSDNode>(N);
18891 EVT RegVT = Ld->getValueType(0);
18892 EVT MemVT = Ld->getMemoryVT();
18894 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18895 unsigned RegSz = RegVT.getSizeInBits();
18897 // On Sandybridge unaligned 256bit loads are inefficient.
18898 ISD::LoadExtType Ext = Ld->getExtensionType();
18899 unsigned Alignment = Ld->getAlignment();
18900 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18901 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18902 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18903 unsigned NumElems = RegVT.getVectorNumElements();
18907 SDValue Ptr = Ld->getBasePtr();
18908 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18910 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18912 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18913 Ld->getPointerInfo(), Ld->isVolatile(),
18914 Ld->isNonTemporal(), Ld->isInvariant(),
18916 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18917 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18918 Ld->getPointerInfo(), Ld->isVolatile(),
18919 Ld->isNonTemporal(), Ld->isInvariant(),
18920 std::min(16U, Alignment));
18921 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18923 Load2.getValue(1));
18925 SDValue NewVec = DAG.getUNDEF(RegVT);
18926 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18927 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18928 return DCI.CombineTo(N, NewVec, TF, true);
18931 // If this is a vector EXT Load then attempt to optimize it using a
18932 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18933 // expansion is still better than scalar code.
18934 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18935 // emit a shuffle and a arithmetic shift.
18936 // TODO: It is possible to support ZExt by zeroing the undef values
18937 // during the shuffle phase or after the shuffle.
18938 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18939 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18940 assert(MemVT != RegVT && "Cannot extend to the same type");
18941 assert(MemVT.isVector() && "Must load a vector from memory");
18943 unsigned NumElems = RegVT.getVectorNumElements();
18944 unsigned MemSz = MemVT.getSizeInBits();
18945 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18947 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18950 // All sizes must be a power of two.
18951 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18954 // Attempt to load the original value using scalar loads.
18955 // Find the largest scalar type that divides the total loaded size.
18956 MVT SclrLoadTy = MVT::i8;
18957 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18958 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18959 MVT Tp = (MVT::SimpleValueType)tp;
18960 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18965 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18966 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18968 SclrLoadTy = MVT::f64;
18970 // Calculate the number of scalar loads that we need to perform
18971 // in order to load our vector from memory.
18972 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18973 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18976 unsigned loadRegZize = RegSz;
18977 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18980 // Represent our vector as a sequence of elements which are the
18981 // largest scalar that we can load.
18982 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18983 loadRegZize/SclrLoadTy.getSizeInBits());
18985 // Represent the data using the same element type that is stored in
18986 // memory. In practice, we ''widen'' MemVT.
18988 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18989 loadRegZize/MemVT.getScalarType().getSizeInBits());
18991 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18992 "Invalid vector type");
18994 // We can't shuffle using an illegal type.
18995 if (!TLI.isTypeLegal(WideVecVT))
18998 SmallVector<SDValue, 8> Chains;
18999 SDValue Ptr = Ld->getBasePtr();
19000 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19001 TLI.getPointerTy());
19002 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19004 for (unsigned i = 0; i < NumLoads; ++i) {
19005 // Perform a single load.
19006 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19007 Ptr, Ld->getPointerInfo(),
19008 Ld->isVolatile(), Ld->isNonTemporal(),
19009 Ld->isInvariant(), Ld->getAlignment());
19010 Chains.push_back(ScalarLoad.getValue(1));
19011 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19012 // another round of DAGCombining.
19014 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19016 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19017 ScalarLoad, DAG.getIntPtrConstant(i));
19019 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19022 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19024 // Bitcast the loaded value to a vector of the original element type, in
19025 // the size of the target vector type.
19026 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19027 unsigned SizeRatio = RegSz/MemSz;
19029 if (Ext == ISD::SEXTLOAD) {
19030 // If we have SSE4.1 we can directly emit a VSEXT node.
19031 if (Subtarget->hasSSE41()) {
19032 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19033 return DCI.CombineTo(N, Sext, TF, true);
19036 // Otherwise we'll shuffle the small elements in the high bits of the
19037 // larger type and perform an arithmetic shift. If the shift is not legal
19038 // it's better to scalarize.
19039 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19042 // Redistribute the loaded elements into the different locations.
19043 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19044 for (unsigned i = 0; i != NumElems; ++i)
19045 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19047 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19048 DAG.getUNDEF(WideVecVT),
19051 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19053 // Build the arithmetic shift.
19054 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19055 MemVT.getVectorElementType().getSizeInBits();
19056 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19057 DAG.getConstant(Amt, RegVT));
19059 return DCI.CombineTo(N, Shuff, TF, true);
19062 // Redistribute the loaded elements into the different locations.
19063 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19064 for (unsigned i = 0; i != NumElems; ++i)
19065 ShuffleVec[i*SizeRatio] = i;
19067 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19068 DAG.getUNDEF(WideVecVT),
19071 // Bitcast to the requested type.
19072 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19073 // Replace the original load with the new sequence
19074 // and return the new chain.
19075 return DCI.CombineTo(N, Shuff, TF, true);
19081 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19082 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19083 const X86Subtarget *Subtarget) {
19084 StoreSDNode *St = cast<StoreSDNode>(N);
19085 EVT VT = St->getValue().getValueType();
19086 EVT StVT = St->getMemoryVT();
19088 SDValue StoredVal = St->getOperand(1);
19089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19091 // If we are saving a concatenation of two XMM registers, perform two stores.
19092 // On Sandy Bridge, 256-bit memory operations are executed by two
19093 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19094 // memory operation.
19095 unsigned Alignment = St->getAlignment();
19096 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19097 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19098 StVT == VT && !IsAligned) {
19099 unsigned NumElems = VT.getVectorNumElements();
19103 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19104 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19106 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19107 SDValue Ptr0 = St->getBasePtr();
19108 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19110 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19111 St->getPointerInfo(), St->isVolatile(),
19112 St->isNonTemporal(), Alignment);
19113 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19114 St->getPointerInfo(), St->isVolatile(),
19115 St->isNonTemporal(),
19116 std::min(16U, Alignment));
19117 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19120 // Optimize trunc store (of multiple scalars) to shuffle and store.
19121 // First, pack all of the elements in one place. Next, store to memory
19122 // in fewer chunks.
19123 if (St->isTruncatingStore() && VT.isVector()) {
19124 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19125 unsigned NumElems = VT.getVectorNumElements();
19126 assert(StVT != VT && "Cannot truncate to the same type");
19127 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19128 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19130 // From, To sizes and ElemCount must be pow of two
19131 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19132 // We are going to use the original vector elt for storing.
19133 // Accumulated smaller vector elements must be a multiple of the store size.
19134 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19136 unsigned SizeRatio = FromSz / ToSz;
19138 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19140 // Create a type on which we perform the shuffle
19141 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19142 StVT.getScalarType(), NumElems*SizeRatio);
19144 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19146 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19147 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19148 for (unsigned i = 0; i != NumElems; ++i)
19149 ShuffleVec[i] = i * SizeRatio;
19151 // Can't shuffle using an illegal type.
19152 if (!TLI.isTypeLegal(WideVecVT))
19155 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19156 DAG.getUNDEF(WideVecVT),
19158 // At this point all of the data is stored at the bottom of the
19159 // register. We now need to save it to mem.
19161 // Find the largest store unit
19162 MVT StoreType = MVT::i8;
19163 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19164 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19165 MVT Tp = (MVT::SimpleValueType)tp;
19166 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19170 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19171 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19172 (64 <= NumElems * ToSz))
19173 StoreType = MVT::f64;
19175 // Bitcast the original vector into a vector of store-size units
19176 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19177 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19178 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19179 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19180 SmallVector<SDValue, 8> Chains;
19181 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19182 TLI.getPointerTy());
19183 SDValue Ptr = St->getBasePtr();
19185 // Perform one or more big stores into memory.
19186 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19187 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19188 StoreType, ShuffWide,
19189 DAG.getIntPtrConstant(i));
19190 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19191 St->getPointerInfo(), St->isVolatile(),
19192 St->isNonTemporal(), St->getAlignment());
19193 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19194 Chains.push_back(Ch);
19197 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19200 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19201 // the FP state in cases where an emms may be missing.
19202 // A preferable solution to the general problem is to figure out the right
19203 // places to insert EMMS. This qualifies as a quick hack.
19205 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19206 if (VT.getSizeInBits() != 64)
19209 const Function *F = DAG.getMachineFunction().getFunction();
19210 bool NoImplicitFloatOps = F->getAttributes().
19211 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19212 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19213 && Subtarget->hasSSE2();
19214 if ((VT.isVector() ||
19215 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19216 isa<LoadSDNode>(St->getValue()) &&
19217 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19218 St->getChain().hasOneUse() && !St->isVolatile()) {
19219 SDNode* LdVal = St->getValue().getNode();
19220 LoadSDNode *Ld = nullptr;
19221 int TokenFactorIndex = -1;
19222 SmallVector<SDValue, 8> Ops;
19223 SDNode* ChainVal = St->getChain().getNode();
19224 // Must be a store of a load. We currently handle two cases: the load
19225 // is a direct child, and it's under an intervening TokenFactor. It is
19226 // possible to dig deeper under nested TokenFactors.
19227 if (ChainVal == LdVal)
19228 Ld = cast<LoadSDNode>(St->getChain());
19229 else if (St->getValue().hasOneUse() &&
19230 ChainVal->getOpcode() == ISD::TokenFactor) {
19231 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19232 if (ChainVal->getOperand(i).getNode() == LdVal) {
19233 TokenFactorIndex = i;
19234 Ld = cast<LoadSDNode>(St->getValue());
19236 Ops.push_back(ChainVal->getOperand(i));
19240 if (!Ld || !ISD::isNormalLoad(Ld))
19243 // If this is not the MMX case, i.e. we are just turning i64 load/store
19244 // into f64 load/store, avoid the transformation if there are multiple
19245 // uses of the loaded value.
19246 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19251 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19252 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19254 if (Subtarget->is64Bit() || F64IsLegal) {
19255 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19256 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19257 Ld->getPointerInfo(), Ld->isVolatile(),
19258 Ld->isNonTemporal(), Ld->isInvariant(),
19259 Ld->getAlignment());
19260 SDValue NewChain = NewLd.getValue(1);
19261 if (TokenFactorIndex != -1) {
19262 Ops.push_back(NewChain);
19263 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19265 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19266 St->getPointerInfo(),
19267 St->isVolatile(), St->isNonTemporal(),
19268 St->getAlignment());
19271 // Otherwise, lower to two pairs of 32-bit loads / stores.
19272 SDValue LoAddr = Ld->getBasePtr();
19273 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19274 DAG.getConstant(4, MVT::i32));
19276 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19277 Ld->getPointerInfo(),
19278 Ld->isVolatile(), Ld->isNonTemporal(),
19279 Ld->isInvariant(), Ld->getAlignment());
19280 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19281 Ld->getPointerInfo().getWithOffset(4),
19282 Ld->isVolatile(), Ld->isNonTemporal(),
19284 MinAlign(Ld->getAlignment(), 4));
19286 SDValue NewChain = LoLd.getValue(1);
19287 if (TokenFactorIndex != -1) {
19288 Ops.push_back(LoLd);
19289 Ops.push_back(HiLd);
19290 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19293 LoAddr = St->getBasePtr();
19294 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19295 DAG.getConstant(4, MVT::i32));
19297 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19298 St->getPointerInfo(),
19299 St->isVolatile(), St->isNonTemporal(),
19300 St->getAlignment());
19301 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19302 St->getPointerInfo().getWithOffset(4),
19304 St->isNonTemporal(),
19305 MinAlign(St->getAlignment(), 4));
19306 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19311 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19312 /// and return the operands for the horizontal operation in LHS and RHS. A
19313 /// horizontal operation performs the binary operation on successive elements
19314 /// of its first operand, then on successive elements of its second operand,
19315 /// returning the resulting values in a vector. For example, if
19316 /// A = < float a0, float a1, float a2, float a3 >
19318 /// B = < float b0, float b1, float b2, float b3 >
19319 /// then the result of doing a horizontal operation on A and B is
19320 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19321 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19322 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19323 /// set to A, RHS to B, and the routine returns 'true'.
19324 /// Note that the binary operation should have the property that if one of the
19325 /// operands is UNDEF then the result is UNDEF.
19326 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19327 // Look for the following pattern: if
19328 // A = < float a0, float a1, float a2, float a3 >
19329 // B = < float b0, float b1, float b2, float b3 >
19331 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19332 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19333 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19334 // which is A horizontal-op B.
19336 // At least one of the operands should be a vector shuffle.
19337 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19338 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19341 MVT VT = LHS.getSimpleValueType();
19343 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19344 "Unsupported vector type for horizontal add/sub");
19346 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19347 // operate independently on 128-bit lanes.
19348 unsigned NumElts = VT.getVectorNumElements();
19349 unsigned NumLanes = VT.getSizeInBits()/128;
19350 unsigned NumLaneElts = NumElts / NumLanes;
19351 assert((NumLaneElts % 2 == 0) &&
19352 "Vector type should have an even number of elements in each lane");
19353 unsigned HalfLaneElts = NumLaneElts/2;
19355 // View LHS in the form
19356 // LHS = VECTOR_SHUFFLE A, B, LMask
19357 // If LHS is not a shuffle then pretend it is the shuffle
19358 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19359 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19362 SmallVector<int, 16> LMask(NumElts);
19363 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19364 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19365 A = LHS.getOperand(0);
19366 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19367 B = LHS.getOperand(1);
19368 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19369 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19371 if (LHS.getOpcode() != ISD::UNDEF)
19373 for (unsigned i = 0; i != NumElts; ++i)
19377 // Likewise, view RHS in the form
19378 // RHS = VECTOR_SHUFFLE C, D, RMask
19380 SmallVector<int, 16> RMask(NumElts);
19381 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19382 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19383 C = RHS.getOperand(0);
19384 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19385 D = RHS.getOperand(1);
19386 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19387 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19389 if (RHS.getOpcode() != ISD::UNDEF)
19391 for (unsigned i = 0; i != NumElts; ++i)
19395 // Check that the shuffles are both shuffling the same vectors.
19396 if (!(A == C && B == D) && !(A == D && B == C))
19399 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19400 if (!A.getNode() && !B.getNode())
19403 // If A and B occur in reverse order in RHS, then "swap" them (which means
19404 // rewriting the mask).
19406 CommuteVectorShuffleMask(RMask, NumElts);
19408 // At this point LHS and RHS are equivalent to
19409 // LHS = VECTOR_SHUFFLE A, B, LMask
19410 // RHS = VECTOR_SHUFFLE A, B, RMask
19411 // Check that the masks correspond to performing a horizontal operation.
19412 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19413 for (unsigned i = 0; i != NumLaneElts; ++i) {
19414 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19416 // Ignore any UNDEF components.
19417 if (LIdx < 0 || RIdx < 0 ||
19418 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19419 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19422 // Check that successive elements are being operated on. If not, this is
19423 // not a horizontal operation.
19424 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19425 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19426 if (!(LIdx == Index && RIdx == Index + 1) &&
19427 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19432 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19433 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19437 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19438 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19439 const X86Subtarget *Subtarget) {
19440 EVT VT = N->getValueType(0);
19441 SDValue LHS = N->getOperand(0);
19442 SDValue RHS = N->getOperand(1);
19444 // Try to synthesize horizontal adds from adds of shuffles.
19445 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19446 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19447 isHorizontalBinOp(LHS, RHS, true))
19448 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19452 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19453 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19454 const X86Subtarget *Subtarget) {
19455 EVT VT = N->getValueType(0);
19456 SDValue LHS = N->getOperand(0);
19457 SDValue RHS = N->getOperand(1);
19459 // Try to synthesize horizontal subs from subs of shuffles.
19460 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19461 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19462 isHorizontalBinOp(LHS, RHS, false))
19463 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19467 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19468 /// X86ISD::FXOR nodes.
19469 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19470 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19471 // F[X]OR(0.0, x) -> x
19472 // F[X]OR(x, 0.0) -> x
19473 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19474 if (C->getValueAPF().isPosZero())
19475 return N->getOperand(1);
19476 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19477 if (C->getValueAPF().isPosZero())
19478 return N->getOperand(0);
19482 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19483 /// X86ISD::FMAX nodes.
19484 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19485 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19487 // Only perform optimizations if UnsafeMath is used.
19488 if (!DAG.getTarget().Options.UnsafeFPMath)
19491 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19492 // into FMINC and FMAXC, which are Commutative operations.
19493 unsigned NewOp = 0;
19494 switch (N->getOpcode()) {
19495 default: llvm_unreachable("unknown opcode");
19496 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19497 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19500 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19501 N->getOperand(0), N->getOperand(1));
19504 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19505 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19506 // FAND(0.0, x) -> 0.0
19507 // FAND(x, 0.0) -> 0.0
19508 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19509 if (C->getValueAPF().isPosZero())
19510 return N->getOperand(0);
19511 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19512 if (C->getValueAPF().isPosZero())
19513 return N->getOperand(1);
19517 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19518 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19519 // FANDN(x, 0.0) -> 0.0
19520 // FANDN(0.0, x) -> x
19521 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19522 if (C->getValueAPF().isPosZero())
19523 return N->getOperand(1);
19524 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19525 if (C->getValueAPF().isPosZero())
19526 return N->getOperand(1);
19530 static SDValue PerformBTCombine(SDNode *N,
19532 TargetLowering::DAGCombinerInfo &DCI) {
19533 // BT ignores high bits in the bit index operand.
19534 SDValue Op1 = N->getOperand(1);
19535 if (Op1.hasOneUse()) {
19536 unsigned BitWidth = Op1.getValueSizeInBits();
19537 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19538 APInt KnownZero, KnownOne;
19539 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19540 !DCI.isBeforeLegalizeOps());
19541 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19542 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19543 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19544 DCI.CommitTargetLoweringOpt(TLO);
19549 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19550 SDValue Op = N->getOperand(0);
19551 if (Op.getOpcode() == ISD::BITCAST)
19552 Op = Op.getOperand(0);
19553 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19554 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19555 VT.getVectorElementType().getSizeInBits() ==
19556 OpVT.getVectorElementType().getSizeInBits()) {
19557 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19562 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19563 const X86Subtarget *Subtarget) {
19564 EVT VT = N->getValueType(0);
19565 if (!VT.isVector())
19568 SDValue N0 = N->getOperand(0);
19569 SDValue N1 = N->getOperand(1);
19570 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19573 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19574 // both SSE and AVX2 since there is no sign-extended shift right
19575 // operation on a vector with 64-bit elements.
19576 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19577 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19578 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19579 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19580 SDValue N00 = N0.getOperand(0);
19582 // EXTLOAD has a better solution on AVX2,
19583 // it may be replaced with X86ISD::VSEXT node.
19584 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19585 if (!ISD::isNormalLoad(N00.getNode()))
19588 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19589 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19591 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19597 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19598 TargetLowering::DAGCombinerInfo &DCI,
19599 const X86Subtarget *Subtarget) {
19600 if (!DCI.isBeforeLegalizeOps())
19603 if (!Subtarget->hasFp256())
19606 EVT VT = N->getValueType(0);
19607 if (VT.isVector() && VT.getSizeInBits() == 256) {
19608 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19616 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19617 const X86Subtarget* Subtarget) {
19619 EVT VT = N->getValueType(0);
19621 // Let legalize expand this if it isn't a legal type yet.
19622 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19625 EVT ScalarVT = VT.getScalarType();
19626 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19627 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19630 SDValue A = N->getOperand(0);
19631 SDValue B = N->getOperand(1);
19632 SDValue C = N->getOperand(2);
19634 bool NegA = (A.getOpcode() == ISD::FNEG);
19635 bool NegB = (B.getOpcode() == ISD::FNEG);
19636 bool NegC = (C.getOpcode() == ISD::FNEG);
19638 // Negative multiplication when NegA xor NegB
19639 bool NegMul = (NegA != NegB);
19641 A = A.getOperand(0);
19643 B = B.getOperand(0);
19645 C = C.getOperand(0);
19649 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19651 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19653 return DAG.getNode(Opcode, dl, VT, A, B, C);
19656 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19657 TargetLowering::DAGCombinerInfo &DCI,
19658 const X86Subtarget *Subtarget) {
19659 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19660 // (and (i32 x86isd::setcc_carry), 1)
19661 // This eliminates the zext. This transformation is necessary because
19662 // ISD::SETCC is always legalized to i8.
19664 SDValue N0 = N->getOperand(0);
19665 EVT VT = N->getValueType(0);
19667 if (N0.getOpcode() == ISD::AND &&
19669 N0.getOperand(0).hasOneUse()) {
19670 SDValue N00 = N0.getOperand(0);
19671 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19672 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19673 if (!C || C->getZExtValue() != 1)
19675 return DAG.getNode(ISD::AND, dl, VT,
19676 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19677 N00.getOperand(0), N00.getOperand(1)),
19678 DAG.getConstant(1, VT));
19682 if (N0.getOpcode() == ISD::TRUNCATE &&
19684 N0.getOperand(0).hasOneUse()) {
19685 SDValue N00 = N0.getOperand(0);
19686 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19687 return DAG.getNode(ISD::AND, dl, VT,
19688 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19689 N00.getOperand(0), N00.getOperand(1)),
19690 DAG.getConstant(1, VT));
19693 if (VT.is256BitVector()) {
19694 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19702 // Optimize x == -y --> x+y == 0
19703 // x != -y --> x+y != 0
19704 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19705 const X86Subtarget* Subtarget) {
19706 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19707 SDValue LHS = N->getOperand(0);
19708 SDValue RHS = N->getOperand(1);
19709 EVT VT = N->getValueType(0);
19712 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19714 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19715 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19716 LHS.getValueType(), RHS, LHS.getOperand(1));
19717 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19718 addV, DAG.getConstant(0, addV.getValueType()), CC);
19720 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19722 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19723 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19724 RHS.getValueType(), LHS, RHS.getOperand(1));
19725 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19726 addV, DAG.getConstant(0, addV.getValueType()), CC);
19729 if (VT.getScalarType() == MVT::i1) {
19730 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19731 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19732 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19733 if (!IsSEXT0 && !IsVZero0)
19735 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19736 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19737 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19739 if (!IsSEXT1 && !IsVZero1)
19742 if (IsSEXT0 && IsVZero1) {
19743 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19744 if (CC == ISD::SETEQ)
19745 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19746 return LHS.getOperand(0);
19748 if (IsSEXT1 && IsVZero0) {
19749 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19750 if (CC == ISD::SETEQ)
19751 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19752 return RHS.getOperand(0);
19759 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19760 // as "sbb reg,reg", since it can be extended without zext and produces
19761 // an all-ones bit which is more useful than 0/1 in some cases.
19762 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19765 return DAG.getNode(ISD::AND, DL, VT,
19766 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19767 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19768 DAG.getConstant(1, VT));
19769 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19770 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19771 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19772 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19775 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19776 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19777 TargetLowering::DAGCombinerInfo &DCI,
19778 const X86Subtarget *Subtarget) {
19780 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19781 SDValue EFLAGS = N->getOperand(1);
19783 if (CC == X86::COND_A) {
19784 // Try to convert COND_A into COND_B in an attempt to facilitate
19785 // materializing "setb reg".
19787 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19788 // cannot take an immediate as its first operand.
19790 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19791 EFLAGS.getValueType().isInteger() &&
19792 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19793 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19794 EFLAGS.getNode()->getVTList(),
19795 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19796 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19797 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19801 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19802 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19804 if (CC == X86::COND_B)
19805 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19809 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19810 if (Flags.getNode()) {
19811 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19812 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19818 // Optimize branch condition evaluation.
19820 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19821 TargetLowering::DAGCombinerInfo &DCI,
19822 const X86Subtarget *Subtarget) {
19824 SDValue Chain = N->getOperand(0);
19825 SDValue Dest = N->getOperand(1);
19826 SDValue EFLAGS = N->getOperand(3);
19827 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19831 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19832 if (Flags.getNode()) {
19833 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19834 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19841 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19842 const X86TargetLowering *XTLI) {
19843 SDValue Op0 = N->getOperand(0);
19844 EVT InVT = Op0->getValueType(0);
19846 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19847 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19849 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19850 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19851 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19854 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19855 // a 32-bit target where SSE doesn't support i64->FP operations.
19856 if (Op0.getOpcode() == ISD::LOAD) {
19857 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19858 EVT VT = Ld->getValueType(0);
19859 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19860 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19861 !XTLI->getSubtarget()->is64Bit() &&
19863 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19864 Ld->getChain(), Op0, DAG);
19865 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19872 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19873 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19874 X86TargetLowering::DAGCombinerInfo &DCI) {
19875 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19876 // the result is either zero or one (depending on the input carry bit).
19877 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19878 if (X86::isZeroNode(N->getOperand(0)) &&
19879 X86::isZeroNode(N->getOperand(1)) &&
19880 // We don't have a good way to replace an EFLAGS use, so only do this when
19882 SDValue(N, 1).use_empty()) {
19884 EVT VT = N->getValueType(0);
19885 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19886 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19887 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19888 DAG.getConstant(X86::COND_B,MVT::i8),
19890 DAG.getConstant(1, VT));
19891 return DCI.CombineTo(N, Res1, CarryOut);
19897 // fold (add Y, (sete X, 0)) -> adc 0, Y
19898 // (add Y, (setne X, 0)) -> sbb -1, Y
19899 // (sub (sete X, 0), Y) -> sbb 0, Y
19900 // (sub (setne X, 0), Y) -> adc -1, Y
19901 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19904 // Look through ZExts.
19905 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19906 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19909 SDValue SetCC = Ext.getOperand(0);
19910 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19913 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19914 if (CC != X86::COND_E && CC != X86::COND_NE)
19917 SDValue Cmp = SetCC.getOperand(1);
19918 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19919 !X86::isZeroNode(Cmp.getOperand(1)) ||
19920 !Cmp.getOperand(0).getValueType().isInteger())
19923 SDValue CmpOp0 = Cmp.getOperand(0);
19924 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19925 DAG.getConstant(1, CmpOp0.getValueType()));
19927 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19928 if (CC == X86::COND_NE)
19929 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19930 DL, OtherVal.getValueType(), OtherVal,
19931 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19932 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19933 DL, OtherVal.getValueType(), OtherVal,
19934 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19937 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19938 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19939 const X86Subtarget *Subtarget) {
19940 EVT VT = N->getValueType(0);
19941 SDValue Op0 = N->getOperand(0);
19942 SDValue Op1 = N->getOperand(1);
19944 // Try to synthesize horizontal adds from adds of shuffles.
19945 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19946 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19947 isHorizontalBinOp(Op0, Op1, true))
19948 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19950 return OptimizeConditionalInDecrement(N, DAG);
19953 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19954 const X86Subtarget *Subtarget) {
19955 SDValue Op0 = N->getOperand(0);
19956 SDValue Op1 = N->getOperand(1);
19958 // X86 can't encode an immediate LHS of a sub. See if we can push the
19959 // negation into a preceding instruction.
19960 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19961 // If the RHS of the sub is a XOR with one use and a constant, invert the
19962 // immediate. Then add one to the LHS of the sub so we can turn
19963 // X-Y -> X+~Y+1, saving one register.
19964 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19965 isa<ConstantSDNode>(Op1.getOperand(1))) {
19966 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19967 EVT VT = Op0.getValueType();
19968 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19970 DAG.getConstant(~XorC, VT));
19971 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19972 DAG.getConstant(C->getAPIntValue()+1, VT));
19976 // Try to synthesize horizontal adds from adds of shuffles.
19977 EVT VT = N->getValueType(0);
19978 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19979 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19980 isHorizontalBinOp(Op0, Op1, true))
19981 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19983 return OptimizeConditionalInDecrement(N, DAG);
19986 /// performVZEXTCombine - Performs build vector combines
19987 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19988 TargetLowering::DAGCombinerInfo &DCI,
19989 const X86Subtarget *Subtarget) {
19990 // (vzext (bitcast (vzext (x)) -> (vzext x)
19991 SDValue In = N->getOperand(0);
19992 while (In.getOpcode() == ISD::BITCAST)
19993 In = In.getOperand(0);
19995 if (In.getOpcode() != X86ISD::VZEXT)
19998 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20002 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20003 DAGCombinerInfo &DCI) const {
20004 SelectionDAG &DAG = DCI.DAG;
20005 switch (N->getOpcode()) {
20007 case ISD::EXTRACT_VECTOR_ELT:
20008 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20010 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20011 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20012 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20013 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20014 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20015 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20018 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20019 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20020 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20021 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20022 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20023 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20024 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20025 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20026 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20028 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20030 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20031 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20032 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20033 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20034 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20035 case ISD::ANY_EXTEND:
20036 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20037 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20038 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20039 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20040 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20041 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20042 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20043 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20044 case X86ISD::SHUFP: // Handle all target specific shuffles
20045 case X86ISD::PALIGNR:
20046 case X86ISD::UNPCKH:
20047 case X86ISD::UNPCKL:
20048 case X86ISD::MOVHLPS:
20049 case X86ISD::MOVLHPS:
20050 case X86ISD::PSHUFD:
20051 case X86ISD::PSHUFHW:
20052 case X86ISD::PSHUFLW:
20053 case X86ISD::MOVSS:
20054 case X86ISD::MOVSD:
20055 case X86ISD::VPERMILP:
20056 case X86ISD::VPERM2X128:
20057 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20058 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20064 /// isTypeDesirableForOp - Return true if the target has native support for
20065 /// the specified value type and it is 'desirable' to use the type for the
20066 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20067 /// instruction encodings are longer and some i16 instructions are slow.
20068 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20069 if (!isTypeLegal(VT))
20071 if (VT != MVT::i16)
20078 case ISD::SIGN_EXTEND:
20079 case ISD::ZERO_EXTEND:
20080 case ISD::ANY_EXTEND:
20093 /// IsDesirableToPromoteOp - This method query the target whether it is
20094 /// beneficial for dag combiner to promote the specified node. If true, it
20095 /// should return the desired promotion type by reference.
20096 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20097 EVT VT = Op.getValueType();
20098 if (VT != MVT::i16)
20101 bool Promote = false;
20102 bool Commute = false;
20103 switch (Op.getOpcode()) {
20106 LoadSDNode *LD = cast<LoadSDNode>(Op);
20107 // If the non-extending load has a single use and it's not live out, then it
20108 // might be folded.
20109 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20110 Op.hasOneUse()*/) {
20111 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20112 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20113 // The only case where we'd want to promote LOAD (rather then it being
20114 // promoted as an operand is when it's only use is liveout.
20115 if (UI->getOpcode() != ISD::CopyToReg)
20122 case ISD::SIGN_EXTEND:
20123 case ISD::ZERO_EXTEND:
20124 case ISD::ANY_EXTEND:
20129 SDValue N0 = Op.getOperand(0);
20130 // Look out for (store (shl (load), x)).
20131 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20144 SDValue N0 = Op.getOperand(0);
20145 SDValue N1 = Op.getOperand(1);
20146 if (!Commute && MayFoldLoad(N1))
20148 // Avoid disabling potential load folding opportunities.
20149 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20151 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20161 //===----------------------------------------------------------------------===//
20162 // X86 Inline Assembly Support
20163 //===----------------------------------------------------------------------===//
20166 // Helper to match a string separated by whitespace.
20167 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20168 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20170 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20171 StringRef piece(*args[i]);
20172 if (!s.startswith(piece)) // Check if the piece matches.
20175 s = s.substr(piece.size());
20176 StringRef::size_type pos = s.find_first_not_of(" \t");
20177 if (pos == 0) // We matched a prefix.
20185 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20188 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20190 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20191 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20192 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20193 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20195 if (AsmPieces.size() == 3)
20197 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20204 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20205 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20207 std::string AsmStr = IA->getAsmString();
20209 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20210 if (!Ty || Ty->getBitWidth() % 16 != 0)
20213 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20214 SmallVector<StringRef, 4> AsmPieces;
20215 SplitString(AsmStr, AsmPieces, ";\n");
20217 switch (AsmPieces.size()) {
20218 default: return false;
20220 // FIXME: this should verify that we are targeting a 486 or better. If not,
20221 // we will turn this bswap into something that will be lowered to logical
20222 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20223 // lower so don't worry about this.
20225 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20226 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20227 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20228 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20229 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20230 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20231 // No need to check constraints, nothing other than the equivalent of
20232 // "=r,0" would be valid here.
20233 return IntrinsicLowering::LowerToByteSwap(CI);
20236 // rorw $$8, ${0:w} --> llvm.bswap.i16
20237 if (CI->getType()->isIntegerTy(16) &&
20238 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20239 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20240 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20242 const std::string &ConstraintsStr = IA->getConstraintString();
20243 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20244 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20245 if (clobbersFlagRegisters(AsmPieces))
20246 return IntrinsicLowering::LowerToByteSwap(CI);
20250 if (CI->getType()->isIntegerTy(32) &&
20251 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20252 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20253 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20254 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20256 const std::string &ConstraintsStr = IA->getConstraintString();
20257 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20258 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20259 if (clobbersFlagRegisters(AsmPieces))
20260 return IntrinsicLowering::LowerToByteSwap(CI);
20263 if (CI->getType()->isIntegerTy(64)) {
20264 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20265 if (Constraints.size() >= 2 &&
20266 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20267 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20268 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20269 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20270 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20271 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20272 return IntrinsicLowering::LowerToByteSwap(CI);
20280 /// getConstraintType - Given a constraint letter, return the type of
20281 /// constraint it is for this target.
20282 X86TargetLowering::ConstraintType
20283 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20284 if (Constraint.size() == 1) {
20285 switch (Constraint[0]) {
20296 return C_RegisterClass;
20320 return TargetLowering::getConstraintType(Constraint);
20323 /// Examine constraint type and operand type and determine a weight value.
20324 /// This object must already have been set up with the operand type
20325 /// and the current alternative constraint selected.
20326 TargetLowering::ConstraintWeight
20327 X86TargetLowering::getSingleConstraintMatchWeight(
20328 AsmOperandInfo &info, const char *constraint) const {
20329 ConstraintWeight weight = CW_Invalid;
20330 Value *CallOperandVal = info.CallOperandVal;
20331 // If we don't have a value, we can't do a match,
20332 // but allow it at the lowest weight.
20333 if (!CallOperandVal)
20335 Type *type = CallOperandVal->getType();
20336 // Look at the constraint type.
20337 switch (*constraint) {
20339 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20350 if (CallOperandVal->getType()->isIntegerTy())
20351 weight = CW_SpecificReg;
20356 if (type->isFloatingPointTy())
20357 weight = CW_SpecificReg;
20360 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20361 weight = CW_SpecificReg;
20365 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20366 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20367 weight = CW_Register;
20370 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20371 if (C->getZExtValue() <= 31)
20372 weight = CW_Constant;
20376 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20377 if (C->getZExtValue() <= 63)
20378 weight = CW_Constant;
20382 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20383 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20384 weight = CW_Constant;
20388 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20389 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20390 weight = CW_Constant;
20394 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20395 if (C->getZExtValue() <= 3)
20396 weight = CW_Constant;
20400 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20401 if (C->getZExtValue() <= 0xff)
20402 weight = CW_Constant;
20407 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20408 weight = CW_Constant;
20412 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20413 if ((C->getSExtValue() >= -0x80000000LL) &&
20414 (C->getSExtValue() <= 0x7fffffffLL))
20415 weight = CW_Constant;
20419 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20420 if (C->getZExtValue() <= 0xffffffff)
20421 weight = CW_Constant;
20428 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20429 /// with another that has more specific requirements based on the type of the
20430 /// corresponding operand.
20431 const char *X86TargetLowering::
20432 LowerXConstraint(EVT ConstraintVT) const {
20433 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20434 // 'f' like normal targets.
20435 if (ConstraintVT.isFloatingPoint()) {
20436 if (Subtarget->hasSSE2())
20438 if (Subtarget->hasSSE1())
20442 return TargetLowering::LowerXConstraint(ConstraintVT);
20445 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20446 /// vector. If it is invalid, don't add anything to Ops.
20447 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20448 std::string &Constraint,
20449 std::vector<SDValue>&Ops,
20450 SelectionDAG &DAG) const {
20453 // Only support length 1 constraints for now.
20454 if (Constraint.length() > 1) return;
20456 char ConstraintLetter = Constraint[0];
20457 switch (ConstraintLetter) {
20460 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20461 if (C->getZExtValue() <= 31) {
20462 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20468 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20469 if (C->getZExtValue() <= 63) {
20470 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20476 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20477 if (isInt<8>(C->getSExtValue())) {
20478 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20485 if (C->getZExtValue() <= 255) {
20486 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20492 // 32-bit signed value
20493 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20494 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20495 C->getSExtValue())) {
20496 // Widen to 64 bits here to get it sign extended.
20497 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20500 // FIXME gcc accepts some relocatable values here too, but only in certain
20501 // memory models; it's complicated.
20506 // 32-bit unsigned value
20507 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20508 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20509 C->getZExtValue())) {
20510 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20514 // FIXME gcc accepts some relocatable values here too, but only in certain
20515 // memory models; it's complicated.
20519 // Literal immediates are always ok.
20520 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20521 // Widen to 64 bits here to get it sign extended.
20522 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20526 // In any sort of PIC mode addresses need to be computed at runtime by
20527 // adding in a register or some sort of table lookup. These can't
20528 // be used as immediates.
20529 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20532 // If we are in non-pic codegen mode, we allow the address of a global (with
20533 // an optional displacement) to be used with 'i'.
20534 GlobalAddressSDNode *GA = nullptr;
20535 int64_t Offset = 0;
20537 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20539 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20540 Offset += GA->getOffset();
20542 } else if (Op.getOpcode() == ISD::ADD) {
20543 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20544 Offset += C->getZExtValue();
20545 Op = Op.getOperand(0);
20548 } else if (Op.getOpcode() == ISD::SUB) {
20549 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20550 Offset += -C->getZExtValue();
20551 Op = Op.getOperand(0);
20556 // Otherwise, this isn't something we can handle, reject it.
20560 const GlobalValue *GV = GA->getGlobal();
20561 // If we require an extra load to get this address, as in PIC mode, we
20562 // can't accept it.
20563 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20564 getTargetMachine())))
20567 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20568 GA->getValueType(0), Offset);
20573 if (Result.getNode()) {
20574 Ops.push_back(Result);
20577 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20580 std::pair<unsigned, const TargetRegisterClass*>
20581 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20583 // First, see if this is a constraint that directly corresponds to an LLVM
20585 if (Constraint.size() == 1) {
20586 // GCC Constraint Letters
20587 switch (Constraint[0]) {
20589 // TODO: Slight differences here in allocation order and leaving
20590 // RIP in the class. Do they matter any more here than they do
20591 // in the normal allocation?
20592 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20593 if (Subtarget->is64Bit()) {
20594 if (VT == MVT::i32 || VT == MVT::f32)
20595 return std::make_pair(0U, &X86::GR32RegClass);
20596 if (VT == MVT::i16)
20597 return std::make_pair(0U, &X86::GR16RegClass);
20598 if (VT == MVT::i8 || VT == MVT::i1)
20599 return std::make_pair(0U, &X86::GR8RegClass);
20600 if (VT == MVT::i64 || VT == MVT::f64)
20601 return std::make_pair(0U, &X86::GR64RegClass);
20604 // 32-bit fallthrough
20605 case 'Q': // Q_REGS
20606 if (VT == MVT::i32 || VT == MVT::f32)
20607 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20608 if (VT == MVT::i16)
20609 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20610 if (VT == MVT::i8 || VT == MVT::i1)
20611 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20612 if (VT == MVT::i64)
20613 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20615 case 'r': // GENERAL_REGS
20616 case 'l': // INDEX_REGS
20617 if (VT == MVT::i8 || VT == MVT::i1)
20618 return std::make_pair(0U, &X86::GR8RegClass);
20619 if (VT == MVT::i16)
20620 return std::make_pair(0U, &X86::GR16RegClass);
20621 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20622 return std::make_pair(0U, &X86::GR32RegClass);
20623 return std::make_pair(0U, &X86::GR64RegClass);
20624 case 'R': // LEGACY_REGS
20625 if (VT == MVT::i8 || VT == MVT::i1)
20626 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20627 if (VT == MVT::i16)
20628 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20629 if (VT == MVT::i32 || !Subtarget->is64Bit())
20630 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20631 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20632 case 'f': // FP Stack registers.
20633 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20634 // value to the correct fpstack register class.
20635 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20636 return std::make_pair(0U, &X86::RFP32RegClass);
20637 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20638 return std::make_pair(0U, &X86::RFP64RegClass);
20639 return std::make_pair(0U, &X86::RFP80RegClass);
20640 case 'y': // MMX_REGS if MMX allowed.
20641 if (!Subtarget->hasMMX()) break;
20642 return std::make_pair(0U, &X86::VR64RegClass);
20643 case 'Y': // SSE_REGS if SSE2 allowed
20644 if (!Subtarget->hasSSE2()) break;
20646 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20647 if (!Subtarget->hasSSE1()) break;
20649 switch (VT.SimpleTy) {
20651 // Scalar SSE types.
20654 return std::make_pair(0U, &X86::FR32RegClass);
20657 return std::make_pair(0U, &X86::FR64RegClass);
20665 return std::make_pair(0U, &X86::VR128RegClass);
20673 return std::make_pair(0U, &X86::VR256RegClass);
20678 return std::make_pair(0U, &X86::VR512RegClass);
20684 // Use the default implementation in TargetLowering to convert the register
20685 // constraint into a member of a register class.
20686 std::pair<unsigned, const TargetRegisterClass*> Res;
20687 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20689 // Not found as a standard register?
20691 // Map st(0) -> st(7) -> ST0
20692 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20693 tolower(Constraint[1]) == 's' &&
20694 tolower(Constraint[2]) == 't' &&
20695 Constraint[3] == '(' &&
20696 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20697 Constraint[5] == ')' &&
20698 Constraint[6] == '}') {
20700 Res.first = X86::ST0+Constraint[4]-'0';
20701 Res.second = &X86::RFP80RegClass;
20705 // GCC allows "st(0)" to be called just plain "st".
20706 if (StringRef("{st}").equals_lower(Constraint)) {
20707 Res.first = X86::ST0;
20708 Res.second = &X86::RFP80RegClass;
20713 if (StringRef("{flags}").equals_lower(Constraint)) {
20714 Res.first = X86::EFLAGS;
20715 Res.second = &X86::CCRRegClass;
20719 // 'A' means EAX + EDX.
20720 if (Constraint == "A") {
20721 Res.first = X86::EAX;
20722 Res.second = &X86::GR32_ADRegClass;
20728 // Otherwise, check to see if this is a register class of the wrong value
20729 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20730 // turn into {ax},{dx}.
20731 if (Res.second->hasType(VT))
20732 return Res; // Correct type already, nothing to do.
20734 // All of the single-register GCC register classes map their values onto
20735 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20736 // really want an 8-bit or 32-bit register, map to the appropriate register
20737 // class and return the appropriate register.
20738 if (Res.second == &X86::GR16RegClass) {
20739 if (VT == MVT::i8 || VT == MVT::i1) {
20740 unsigned DestReg = 0;
20741 switch (Res.first) {
20743 case X86::AX: DestReg = X86::AL; break;
20744 case X86::DX: DestReg = X86::DL; break;
20745 case X86::CX: DestReg = X86::CL; break;
20746 case X86::BX: DestReg = X86::BL; break;
20749 Res.first = DestReg;
20750 Res.second = &X86::GR8RegClass;
20752 } else if (VT == MVT::i32 || VT == MVT::f32) {
20753 unsigned DestReg = 0;
20754 switch (Res.first) {
20756 case X86::AX: DestReg = X86::EAX; break;
20757 case X86::DX: DestReg = X86::EDX; break;
20758 case X86::CX: DestReg = X86::ECX; break;
20759 case X86::BX: DestReg = X86::EBX; break;
20760 case X86::SI: DestReg = X86::ESI; break;
20761 case X86::DI: DestReg = X86::EDI; break;
20762 case X86::BP: DestReg = X86::EBP; break;
20763 case X86::SP: DestReg = X86::ESP; break;
20766 Res.first = DestReg;
20767 Res.second = &X86::GR32RegClass;
20769 } else if (VT == MVT::i64 || VT == MVT::f64) {
20770 unsigned DestReg = 0;
20771 switch (Res.first) {
20773 case X86::AX: DestReg = X86::RAX; break;
20774 case X86::DX: DestReg = X86::RDX; break;
20775 case X86::CX: DestReg = X86::RCX; break;
20776 case X86::BX: DestReg = X86::RBX; break;
20777 case X86::SI: DestReg = X86::RSI; break;
20778 case X86::DI: DestReg = X86::RDI; break;
20779 case X86::BP: DestReg = X86::RBP; break;
20780 case X86::SP: DestReg = X86::RSP; break;
20783 Res.first = DestReg;
20784 Res.second = &X86::GR64RegClass;
20787 } else if (Res.second == &X86::FR32RegClass ||
20788 Res.second == &X86::FR64RegClass ||
20789 Res.second == &X86::VR128RegClass ||
20790 Res.second == &X86::VR256RegClass ||
20791 Res.second == &X86::FR32XRegClass ||
20792 Res.second == &X86::FR64XRegClass ||
20793 Res.second == &X86::VR128XRegClass ||
20794 Res.second == &X86::VR256XRegClass ||
20795 Res.second == &X86::VR512RegClass) {
20796 // Handle references to XMM physical registers that got mapped into the
20797 // wrong class. This can happen with constraints like {xmm0} where the
20798 // target independent register mapper will just pick the first match it can
20799 // find, ignoring the required type.
20801 if (VT == MVT::f32 || VT == MVT::i32)
20802 Res.second = &X86::FR32RegClass;
20803 else if (VT == MVT::f64 || VT == MVT::i64)
20804 Res.second = &X86::FR64RegClass;
20805 else if (X86::VR128RegClass.hasType(VT))
20806 Res.second = &X86::VR128RegClass;
20807 else if (X86::VR256RegClass.hasType(VT))
20808 Res.second = &X86::VR256RegClass;
20809 else if (X86::VR512RegClass.hasType(VT))
20810 Res.second = &X86::VR512RegClass;
20816 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20818 // Scaling factors are not free at all.
20819 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20820 // will take 2 allocations instead of 1 for plain addressing mode,
20821 // i.e. inst (reg1).
20822 if (isLegalAddressingMode(AM, Ty))
20823 // Scale represents reg2 * scale, thus account for 1
20824 // as soon as we use a second register.
20825 return AM.Scale != 0;