1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "x86-isel"
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63 SelectionDAG &DAG, SDLoc dl,
64 unsigned vectorWidth) {
65 assert((vectorWidth == 128 || vectorWidth == 256) &&
66 "Unsupported vector width");
67 EVT VT = Vec.getValueType();
68 EVT ElVT = VT.getVectorElementType();
69 unsigned Factor = VT.getSizeInBits()/vectorWidth;
70 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71 VT.getVectorNumElements()/Factor);
73 // Extract from UNDEF is UNDEF.
74 if (Vec.getOpcode() == ISD::UNDEF)
75 return DAG.getUNDEF(ResultVT);
77 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
78 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80 // This is the index of the first element of the vectorWidth-bit chunk
82 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
85 // If the input is a buildvector just emit a smaller one.
86 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
90 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104 SelectionDAG &DAG, SDLoc dl) {
105 assert((Vec.getValueType().is256BitVector() ||
106 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112 SelectionDAG &DAG, SDLoc dl) {
113 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118 unsigned IdxVal, SelectionDAG &DAG,
119 SDLoc dl, unsigned vectorWidth) {
120 assert((vectorWidth == 128 || vectorWidth == 256) &&
121 "Unsupported vector width");
122 // Inserting UNDEF is Result
123 if (Vec.getOpcode() == ISD::UNDEF)
125 EVT VT = Vec.getValueType();
126 EVT ElVT = VT.getVectorElementType();
127 EVT ResultVT = Result.getValueType();
129 // Insert the relevant vectorWidth bits.
130 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
132 // This is the index of the first element of the vectorWidth-bit chunk
134 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference. Idx is an index in the 128 bits
145 /// we want. It need not be aligned to a 128-bit bounday. That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148 unsigned IdxVal, SelectionDAG &DAG,
150 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155 unsigned IdxVal, SelectionDAG &DAG,
157 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166 unsigned NumElems, SelectionDAG &DAG,
168 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173 unsigned NumElems, SelectionDAG &DAG,
175 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181 bool is64Bit = Subtarget->is64Bit();
183 if (Subtarget->isTargetMacho()) {
185 return new X86_64MachoTargetObjectFile();
186 return new TargetLoweringObjectFileMachO();
189 if (Subtarget->isTargetLinux())
190 return new X86LinuxTargetObjectFile();
191 if (Subtarget->isTargetELF())
192 return new TargetLoweringObjectFileELF();
193 if (Subtarget->isTargetKnownWindowsMSVC())
194 return new X86WindowsTargetObjectFile();
195 if (Subtarget->isTargetCOFF())
196 return new TargetLoweringObjectFileCOFF();
197 llvm_unreachable("unknown subtarget type");
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201 : TargetLowering(TM, createTLOF(TM)) {
202 Subtarget = &TM.getSubtarget<X86Subtarget>();
203 X86ScalarSSEf64 = Subtarget->hasSSE2();
204 X86ScalarSSEf32 = Subtarget->hasSSE1();
205 TD = getDataLayout();
207 resetOperationActions();
210 void X86TargetLowering::resetOperationActions() {
211 const TargetMachine &TM = getTargetMachine();
212 static bool FirstTimeThrough = true;
214 // If none of the target options have changed, then we don't need to reset the
215 // operation actions.
216 if (!FirstTimeThrough && TO == TM.Options) return;
218 if (!FirstTimeThrough) {
219 // Reinitialize the actions.
221 FirstTimeThrough = false;
226 // Set up the TargetLowering object.
227 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
229 // X86 is weird, it always uses i8 for shift amounts and setcc results.
230 setBooleanContents(ZeroOrOneBooleanContent);
231 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
234 // For 64-bit since we have so many registers use the ILP scheduler, for
235 // 32-bit code use the register pressure specific scheduling.
236 // For Atom, always use ILP scheduling.
237 if (Subtarget->isAtom())
238 setSchedulingPreference(Sched::ILP);
239 else if (Subtarget->is64Bit())
240 setSchedulingPreference(Sched::ILP);
242 setSchedulingPreference(Sched::RegPressure);
243 const X86RegisterInfo *RegInfo =
244 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
247 // Bypass expensive divides on Atom when compiling with O2
248 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249 addBypassSlowDiv(32, 8);
250 if (Subtarget->is64Bit())
251 addBypassSlowDiv(64, 16);
254 if (Subtarget->isTargetKnownWindowsMSVC()) {
255 // Setup Windows compiler runtime calls.
256 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258 setLibcallName(RTLIB::SREM_I64, "_allrem");
259 setLibcallName(RTLIB::UREM_I64, "_aullrem");
260 setLibcallName(RTLIB::MUL_I64, "_allmul");
261 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
267 // The _ftol2 runtime function has an unusual calling conv, which
268 // is modeled by a special pseudo-instruction.
269 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
270 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
271 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
272 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
275 if (Subtarget->isTargetDarwin()) {
276 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277 setUseUnderscoreSetJmp(false);
278 setUseUnderscoreLongJmp(false);
279 } else if (Subtarget->isTargetWindowsGNU()) {
280 // MS runtime is weird: it exports _setjmp, but longjmp!
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(false);
284 setUseUnderscoreSetJmp(true);
285 setUseUnderscoreLongJmp(true);
288 // Set up the register classes.
289 addRegisterClass(MVT::i8, &X86::GR8RegClass);
290 addRegisterClass(MVT::i16, &X86::GR16RegClass);
291 addRegisterClass(MVT::i32, &X86::GR32RegClass);
292 if (Subtarget->is64Bit())
293 addRegisterClass(MVT::i64, &X86::GR64RegClass);
295 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297 // We don't accept any truncstore of integer registers.
298 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
305 // SETOEQ and SETUNE require checking two conditions.
306 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
313 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
315 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
319 if (Subtarget->is64Bit()) {
320 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
321 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
322 } else if (!TM.Options.UseSoftFloat) {
323 // We have an algorithm for SSE2->double, and we turn this into a
324 // 64-bit FILD followed by conditional FADD for other targets.
325 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
326 // We have an algorithm for SSE2, and we turn this into a 64-bit
327 // FILD for other targets.
328 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
331 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
333 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
334 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
336 if (!TM.Options.UseSoftFloat) {
337 // SSE has no i16 to fp conversion, only i32
338 if (X86ScalarSSEf32) {
339 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
340 // f32 and f64 cases are Legal, f80 case is not
341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
351 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
352 // are Legal, f80 is custom lowered.
353 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
354 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
356 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
358 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
359 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
361 if (X86ScalarSSEf32) {
362 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
363 // f32 and f64 cases are Legal, f80 case is not
364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
370 // Handle FP_TO_UINT by promoting the destination to a larger signed
372 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
376 if (Subtarget->is64Bit()) {
377 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
378 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
379 } else if (!TM.Options.UseSoftFloat) {
380 // Since AVX is a superset of SSE3, only check for SSE here.
381 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382 // Expand FP_TO_UINT into a select.
383 // FIXME: We would like to use a Custom expander here eventually to do
384 // the optimal thing for SSE vs. the default expansion in the legalizer.
385 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
387 // With SSE3 we can use fisttpll to convert to a signed i64; without
388 // SSE, we're stuck with a fistpll.
389 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
392 if (isTargetFTOL()) {
393 // Use the _ftol2 runtime function, which has a pseudo-instruction
394 // to handle its weird calling convention.
395 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
398 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399 if (!X86ScalarSSEf64) {
400 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
401 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
402 if (Subtarget->is64Bit()) {
403 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
404 // Without SSE, i64->f64 goes through memory.
405 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
409 // Scalar integer divide and remainder are lowered to use operations that
410 // produce two results, to match the available instructions. This exposes
411 // the two-result form to trivial CSE, which is able to combine x/y and x%y
412 // into a single instruction.
414 // Scalar integer multiply-high is also lowered to use two-result
415 // operations, to match the available instructions. However, plain multiply
416 // (low) operations are left as Legal, as there are single-result
417 // instructions for this in x86. Using the two-result multiply instructions
418 // when both high and low results are needed must be arranged by dagcombine.
419 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
421 setOperationAction(ISD::MULHS, VT, Expand);
422 setOperationAction(ISD::MULHU, VT, Expand);
423 setOperationAction(ISD::SDIV, VT, Expand);
424 setOperationAction(ISD::UDIV, VT, Expand);
425 setOperationAction(ISD::SREM, VT, Expand);
426 setOperationAction(ISD::UREM, VT, Expand);
428 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429 setOperationAction(ISD::ADDC, VT, Custom);
430 setOperationAction(ISD::ADDE, VT, Custom);
431 setOperationAction(ISD::SUBC, VT, Custom);
432 setOperationAction(ISD::SUBE, VT, Custom);
435 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
436 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
437 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
444 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
445 if (Subtarget->is64Bit())
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
450 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f32 , Expand);
452 setOperationAction(ISD::FREM , MVT::f64 , Expand);
453 setOperationAction(ISD::FREM , MVT::f80 , Expand);
454 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
456 // Promote the i8 variants and force them on up to i32 which has a shorter
458 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
459 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
460 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
462 if (Subtarget->hasBMI()) {
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
469 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
474 if (Subtarget->hasLZCNT()) {
475 // When promoting the i8 variants, force them to i32 for a shorter
477 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
478 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
482 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
483 if (Subtarget->is64Bit())
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
486 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
488 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
492 if (Subtarget->is64Bit()) {
493 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
494 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
498 if (Subtarget->hasPOPCNT()) {
499 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
501 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
503 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
504 if (Subtarget->is64Bit())
505 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
508 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
510 if (!Subtarget->hasMOVBE())
511 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
513 // These should be promoted to a larger select which is supported.
514 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
515 // X86 wants to expand cmov itself.
516 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
518 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
528 if (Subtarget->is64Bit()) {
529 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
530 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
532 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
533 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535 // support continuation, user-level threading, and etc.. As a result, no
536 // other SjLj exception interfaces are implemented and please don't build
537 // your own exception handling based on them.
538 // LLVM/Clang supports zero-cost DWARF exception handling.
539 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
544 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
546 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
547 if (Subtarget->is64Bit())
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
550 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
551 if (Subtarget->is64Bit()) {
552 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
553 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
554 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
555 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
556 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
558 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
561 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
562 if (Subtarget->is64Bit()) {
563 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
565 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
568 if (Subtarget->hasSSE1())
569 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
571 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
573 // Expand certain atomics
574 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
576 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581 if (!Subtarget->is64Bit()) {
582 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596 if (Subtarget->hasCmpxchg16b()) {
597 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600 // FIXME - use subtarget debug flags
601 if (!Subtarget->isTargetDarwin() &&
602 !Subtarget->isTargetELF() &&
603 !Subtarget->isTargetCygMing()) {
604 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607 if (Subtarget->is64Bit()) {
608 setExceptionPointerRegister(X86::RAX);
609 setExceptionSelectorRegister(X86::RDX);
611 setExceptionPointerRegister(X86::EAX);
612 setExceptionSelectorRegister(X86::EDX);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
617 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::TRAP, MVT::Other, Legal);
621 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
623 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624 setOperationAction(ISD::VASTART , MVT::Other, Custom);
625 setOperationAction(ISD::VAEND , MVT::Other, Expand);
626 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627 // TargetInfo::X86_64ABIBuiltinVaList
628 setOperationAction(ISD::VAARG , MVT::Other, Custom);
629 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
631 // TargetInfo::CharPtrBuiltinVaList
632 setOperationAction(ISD::VAARG , MVT::Other, Expand);
633 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
636 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
637 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
642 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643 // f32 and f64 use SSE.
644 // Set up the FP register classes.
645 addRegisterClass(MVT::f32, &X86::FR32RegClass);
646 addRegisterClass(MVT::f64, &X86::FR64RegClass);
648 // Use ANDPD to simulate FABS.
649 setOperationAction(ISD::FABS , MVT::f64, Custom);
650 setOperationAction(ISD::FABS , MVT::f32, Custom);
652 // Use XORP to simulate FNEG.
653 setOperationAction(ISD::FNEG , MVT::f64, Custom);
654 setOperationAction(ISD::FNEG , MVT::f32, Custom);
656 // Use ANDPD and ORPD to simulate FCOPYSIGN.
657 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660 // Lower this to FGETSIGNx86 plus an AND.
661 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
664 // We don't support sin/cos/fmod
665 setOperationAction(ISD::FSIN , MVT::f64, Expand);
666 setOperationAction(ISD::FCOS , MVT::f64, Expand);
667 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668 setOperationAction(ISD::FSIN , MVT::f32, Expand);
669 setOperationAction(ISD::FCOS , MVT::f32, Expand);
670 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672 // Expand FP immediates into loads from the stack, except for the special
674 addLegalFPImmediate(APFloat(+0.0)); // xorpd
675 addLegalFPImmediate(APFloat(+0.0f)); // xorps
676 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677 // Use SSE for f32, x87 for f64.
678 // Set up the FP register classes.
679 addRegisterClass(MVT::f32, &X86::FR32RegClass);
680 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682 // Use ANDPS to simulate FABS.
683 setOperationAction(ISD::FABS , MVT::f32, Custom);
685 // Use XORP to simulate FNEG.
686 setOperationAction(ISD::FNEG , MVT::f32, Custom);
688 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
690 // Use ANDPS and ORPS to simulate FCOPYSIGN.
691 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
694 // We don't support sin/cos/fmod
695 setOperationAction(ISD::FSIN , MVT::f32, Expand);
696 setOperationAction(ISD::FCOS , MVT::f32, Expand);
697 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
699 // Special cases we handle for FP constants.
700 addLegalFPImmediate(APFloat(+0.0f)); // xorps
701 addLegalFPImmediate(APFloat(+0.0)); // FLD0
702 addLegalFPImmediate(APFloat(+1.0)); // FLD1
703 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
706 if (!TM.Options.UnsafeFPMath) {
707 setOperationAction(ISD::FSIN , MVT::f64, Expand);
708 setOperationAction(ISD::FCOS , MVT::f64, Expand);
709 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
711 } else if (!TM.Options.UseSoftFloat) {
712 // f32 and f64 in x87.
713 // Set up the FP register classes.
714 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
717 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
718 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
719 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
722 if (!TM.Options.UnsafeFPMath) {
723 setOperationAction(ISD::FSIN , MVT::f64, Expand);
724 setOperationAction(ISD::FSIN , MVT::f32, Expand);
725 setOperationAction(ISD::FCOS , MVT::f64, Expand);
726 setOperationAction(ISD::FCOS , MVT::f32, Expand);
727 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
730 addLegalFPImmediate(APFloat(+0.0)); // FLD0
731 addLegalFPImmediate(APFloat(+1.0)); // FLD1
732 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740 // We don't support FMA.
741 setOperationAction(ISD::FMA, MVT::f64, Expand);
742 setOperationAction(ISD::FMA, MVT::f32, Expand);
744 // Long double always uses X87.
745 if (!TM.Options.UseSoftFloat) {
746 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
748 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
750 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751 addLegalFPImmediate(TmpFlt); // FLD0
753 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
756 APFloat TmpFlt2(+1.0);
757 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
759 addLegalFPImmediate(TmpFlt2); // FLD1
760 TmpFlt2.changeSign();
761 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
764 if (!TM.Options.UnsafeFPMath) {
765 setOperationAction(ISD::FSIN , MVT::f80, Expand);
766 setOperationAction(ISD::FCOS , MVT::f80, Expand);
767 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
772 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773 setOperationAction(ISD::FRINT, MVT::f80, Expand);
774 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775 setOperationAction(ISD::FMA, MVT::f80, Expand);
778 // Always use a library call for pow.
779 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
780 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
781 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
783 setOperationAction(ISD::FLOG, MVT::f80, Expand);
784 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786 setOperationAction(ISD::FEXP, MVT::f80, Expand);
787 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
789 // First set operation action for all vector types to either promote
790 // (for widening) or expand (for scalarization). Then we will selectively
791 // turn on ones that can be effectively codegen'd.
792 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794 MVT VT = (MVT::SimpleValueType)i;
795 setOperationAction(ISD::ADD , VT, Expand);
796 setOperationAction(ISD::SUB , VT, Expand);
797 setOperationAction(ISD::FADD, VT, Expand);
798 setOperationAction(ISD::FNEG, VT, Expand);
799 setOperationAction(ISD::FSUB, VT, Expand);
800 setOperationAction(ISD::MUL , VT, Expand);
801 setOperationAction(ISD::FMUL, VT, Expand);
802 setOperationAction(ISD::SDIV, VT, Expand);
803 setOperationAction(ISD::UDIV, VT, Expand);
804 setOperationAction(ISD::FDIV, VT, Expand);
805 setOperationAction(ISD::SREM, VT, Expand);
806 setOperationAction(ISD::UREM, VT, Expand);
807 setOperationAction(ISD::LOAD, VT, Expand);
808 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813 setOperationAction(ISD::FABS, VT, Expand);
814 setOperationAction(ISD::FSIN, VT, Expand);
815 setOperationAction(ISD::FSINCOS, VT, Expand);
816 setOperationAction(ISD::FCOS, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FREM, VT, Expand);
819 setOperationAction(ISD::FMA, VT, Expand);
820 setOperationAction(ISD::FPOWI, VT, Expand);
821 setOperationAction(ISD::FSQRT, VT, Expand);
822 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823 setOperationAction(ISD::FFLOOR, VT, Expand);
824 setOperationAction(ISD::FCEIL, VT, Expand);
825 setOperationAction(ISD::FTRUNC, VT, Expand);
826 setOperationAction(ISD::FRINT, VT, Expand);
827 setOperationAction(ISD::FNEARBYINT, VT, Expand);
828 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830 setOperationAction(ISD::SDIVREM, VT, Expand);
831 setOperationAction(ISD::UDIVREM, VT, Expand);
832 setOperationAction(ISD::FPOW, VT, Expand);
833 setOperationAction(ISD::CTPOP, VT, Expand);
834 setOperationAction(ISD::CTTZ, VT, Expand);
835 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836 setOperationAction(ISD::CTLZ, VT, Expand);
837 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::SHL, VT, Expand);
839 setOperationAction(ISD::SRA, VT, Expand);
840 setOperationAction(ISD::SRL, VT, Expand);
841 setOperationAction(ISD::ROTL, VT, Expand);
842 setOperationAction(ISD::ROTR, VT, Expand);
843 setOperationAction(ISD::BSWAP, VT, Expand);
844 setOperationAction(ISD::SETCC, VT, Expand);
845 setOperationAction(ISD::FLOG, VT, Expand);
846 setOperationAction(ISD::FLOG2, VT, Expand);
847 setOperationAction(ISD::FLOG10, VT, Expand);
848 setOperationAction(ISD::FEXP, VT, Expand);
849 setOperationAction(ISD::FEXP2, VT, Expand);
850 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855 setOperationAction(ISD::TRUNCATE, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859 setOperationAction(ISD::VSELECT, VT, Expand);
860 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
861 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
862 setTruncStoreAction(VT,
863 (MVT::SimpleValueType)InnerVT, Expand);
864 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
865 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
866 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
870 // with -msoft-float, disable use of MMX as well.
871 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
872 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
873 // No operations on x86mmx supported, everything uses intrinsics.
876 // MMX-sized vectors (other than x86mmx) are expected to be expanded
877 // into smaller operations.
878 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
879 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
880 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
881 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
882 setOperationAction(ISD::AND, MVT::v8i8, Expand);
883 setOperationAction(ISD::AND, MVT::v4i16, Expand);
884 setOperationAction(ISD::AND, MVT::v2i32, Expand);
885 setOperationAction(ISD::AND, MVT::v1i64, Expand);
886 setOperationAction(ISD::OR, MVT::v8i8, Expand);
887 setOperationAction(ISD::OR, MVT::v4i16, Expand);
888 setOperationAction(ISD::OR, MVT::v2i32, Expand);
889 setOperationAction(ISD::OR, MVT::v1i64, Expand);
890 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
891 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
892 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
893 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
895 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
898 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
899 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
900 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
901 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
902 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
903 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
904 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
908 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
909 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
911 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
912 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
913 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
914 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
915 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
916 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
917 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
918 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
919 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
920 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
922 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
925 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
926 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
928 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
929 // registers cannot be used even for integer operations.
930 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
931 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
932 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
933 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
935 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
936 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
937 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
938 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
939 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
940 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
941 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
942 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
943 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
944 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
945 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
946 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
947 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
948 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
949 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
950 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
951 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
952 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
954 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
955 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
956 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
957 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
959 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
960 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
961 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
965 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
966 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
967 MVT VT = (MVT::SimpleValueType)i;
968 // Do not attempt to custom lower non-power-of-2 vectors
969 if (!isPowerOf2_32(VT.getVectorNumElements()))
971 // Do not attempt to custom lower non-128-bit vectors
972 if (!VT.is128BitVector())
974 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
975 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
976 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
980 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
981 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
982 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
984 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
986 if (Subtarget->is64Bit()) {
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
992 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
993 MVT VT = (MVT::SimpleValueType)i;
995 // Do not attempt to promote non-128-bit vectors
996 if (!VT.is128BitVector())
999 setOperationAction(ISD::AND, VT, Promote);
1000 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1001 setOperationAction(ISD::OR, VT, Promote);
1002 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1003 setOperationAction(ISD::XOR, VT, Promote);
1004 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1005 setOperationAction(ISD::LOAD, VT, Promote);
1006 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1007 setOperationAction(ISD::SELECT, VT, Promote);
1008 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1013 // Custom lower v2i64 and v2f64 selects.
1014 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1015 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1016 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1017 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1020 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1022 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1023 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1024 // As there is no 64-bit GPR available, we need build a special custom
1025 // sequence to convert from v2i32 to v2f32.
1026 if (!Subtarget->is64Bit())
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1029 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1030 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1032 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1035 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1036 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1037 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1038 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1039 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1040 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1041 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1042 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1043 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1044 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1045 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1050 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1058 // FIXME: Do we need to handle scalar-to-vector here?
1059 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1061 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1062 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1063 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1067 // i8 and i16 vectors are custom , because the source register and source
1068 // source memory operand types are not the same width. f32 vectors are
1069 // custom since the immediate controlling the insert encodes additional
1071 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1072 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1076 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1077 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1078 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1081 // FIXME: these should be Legal but thats only for the case where
1082 // the index is constant. For now custom expand to deal with that.
1083 if (Subtarget->is64Bit()) {
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1089 if (Subtarget->hasSSE2()) {
1090 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1091 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1093 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1094 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1096 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1099 // In the customized shift lowering, the legal cases in AVX2 will be
1101 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1102 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1104 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1105 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1107 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1109 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1113 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1114 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1115 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1116 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1117 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1121 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1122 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1123 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1125 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1126 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1127 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1136 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1138 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1139 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1140 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1141 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1149 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1151 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1152 // even though v8i16 is a legal type.
1153 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1154 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1155 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1157 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1158 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1159 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1161 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1162 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1164 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1166 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1167 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1169 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1182 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1183 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1186 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1187 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1188 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1194 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1201 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1204 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1206 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1208 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1209 setOperationAction(ISD::FMA, MVT::f32, Legal);
1210 setOperationAction(ISD::FMA, MVT::f64, Legal);
1213 if (Subtarget->hasInt256()) {
1214 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1215 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1216 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1217 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1219 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1220 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1221 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1222 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1224 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1226 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1227 // Don't lower v32i8 because there is no 128-bit byte mul
1229 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1231 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1233 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1234 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1235 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1236 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1238 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1239 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1240 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1241 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1243 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1244 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1245 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1246 // Don't lower v32i8 because there is no 128-bit byte mul
1249 // In the customized shift lowering, the legal cases in AVX2 will be
1251 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1257 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1259 // Custom lower several nodes for 256-bit types.
1260 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262 MVT VT = (MVT::SimpleValueType)i;
1264 // Extract subvector is special because the value type
1265 // (result) is 128-bit but the source is 256-bit wide.
1266 if (VT.is128BitVector())
1267 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1269 // Do not attempt to custom lower other non-256-bit vectors
1270 if (!VT.is256BitVector())
1273 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1274 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1275 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1276 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1278 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1279 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1282 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284 MVT VT = (MVT::SimpleValueType)i;
1286 // Do not attempt to promote non-256-bit vectors
1287 if (!VT.is256BitVector())
1290 setOperationAction(ISD::AND, VT, Promote);
1291 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1292 setOperationAction(ISD::OR, VT, Promote);
1293 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1294 setOperationAction(ISD::XOR, VT, Promote);
1295 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1296 setOperationAction(ISD::LOAD, VT, Promote);
1297 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1298 setOperationAction(ISD::SELECT, VT, Promote);
1299 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1303 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1309 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1310 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1311 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1313 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1314 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1315 setOperationAction(ISD::XOR, MVT::i1, Legal);
1316 setOperationAction(ISD::OR, MVT::i1, Legal);
1317 setOperationAction(ISD::AND, MVT::i1, Legal);
1318 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1319 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1320 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1321 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1322 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1323 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1325 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1326 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1327 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1328 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1329 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1330 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1332 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1333 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1335 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1338 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1340 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1342 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1343 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1344 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1346 if (Subtarget->is64Bit()) {
1347 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1348 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1349 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1350 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1353 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1354 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1355 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1356 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1357 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1358 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1359 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1360 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1361 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1363 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1364 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1365 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1369 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1370 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1372 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1373 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1374 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1377 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1378 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1379 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1380 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1384 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1385 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1387 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1393 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1394 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1395 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1396 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1397 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1399 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1400 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1402 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1403 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1405 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1407 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1408 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1410 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1411 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1413 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1416 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1417 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1418 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1419 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1420 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1421 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1423 // Custom lower several nodes.
1424 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1425 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1426 MVT VT = (MVT::SimpleValueType)i;
1428 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1429 // Extract subvector is special because the value type
1430 // (result) is 256/128-bit but the source is 512-bit wide.
1431 if (VT.is128BitVector() || VT.is256BitVector())
1432 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1434 if (VT.getVectorElementType() == MVT::i1)
1435 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1437 // Do not attempt to custom lower other non-512-bit vectors
1438 if (!VT.is512BitVector())
1441 if ( EltSize >= 32) {
1442 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1443 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1444 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1445 setOperationAction(ISD::VSELECT, VT, Legal);
1446 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1447 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1448 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1451 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1452 MVT VT = (MVT::SimpleValueType)i;
1454 // Do not attempt to promote non-256-bit vectors
1455 if (!VT.is512BitVector())
1458 setOperationAction(ISD::SELECT, VT, Promote);
1459 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1463 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1464 // of this type with custom code.
1465 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1466 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1467 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1471 // We want to custom lower some of our intrinsics.
1472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1474 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1476 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1477 // handle type legalization for these operations here.
1479 // FIXME: We really should do custom legalization for addition and
1480 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1481 // than generic legalization for 64-bit multiplication-with-overflow, though.
1482 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1483 // Add/Sub/Mul with overflow operations are custom lowered.
1485 setOperationAction(ISD::SADDO, VT, Custom);
1486 setOperationAction(ISD::UADDO, VT, Custom);
1487 setOperationAction(ISD::SSUBO, VT, Custom);
1488 setOperationAction(ISD::USUBO, VT, Custom);
1489 setOperationAction(ISD::SMULO, VT, Custom);
1490 setOperationAction(ISD::UMULO, VT, Custom);
1493 // There are no 8-bit 3-address imul/mul instructions
1494 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1495 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1497 if (!Subtarget->is64Bit()) {
1498 // These libcalls are not available in 32-bit.
1499 setLibcallName(RTLIB::SHL_I128, 0);
1500 setLibcallName(RTLIB::SRL_I128, 0);
1501 setLibcallName(RTLIB::SRA_I128, 0);
1504 // Combine sin / cos into one node or libcall if possible.
1505 if (Subtarget->hasSinCos()) {
1506 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1507 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1508 if (Subtarget->isTargetDarwin()) {
1509 // For MacOSX, we don't want to the normal expansion of a libcall to
1510 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1512 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1513 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1517 // We have target-specific dag combine patterns for the following nodes:
1518 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1519 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1520 setTargetDAGCombine(ISD::VSELECT);
1521 setTargetDAGCombine(ISD::SELECT);
1522 setTargetDAGCombine(ISD::SHL);
1523 setTargetDAGCombine(ISD::SRA);
1524 setTargetDAGCombine(ISD::SRL);
1525 setTargetDAGCombine(ISD::OR);
1526 setTargetDAGCombine(ISD::AND);
1527 setTargetDAGCombine(ISD::ADD);
1528 setTargetDAGCombine(ISD::FADD);
1529 setTargetDAGCombine(ISD::FSUB);
1530 setTargetDAGCombine(ISD::FMA);
1531 setTargetDAGCombine(ISD::SUB);
1532 setTargetDAGCombine(ISD::LOAD);
1533 setTargetDAGCombine(ISD::STORE);
1534 setTargetDAGCombine(ISD::ZERO_EXTEND);
1535 setTargetDAGCombine(ISD::ANY_EXTEND);
1536 setTargetDAGCombine(ISD::SIGN_EXTEND);
1537 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1538 setTargetDAGCombine(ISD::TRUNCATE);
1539 setTargetDAGCombine(ISD::SINT_TO_FP);
1540 setTargetDAGCombine(ISD::SETCC);
1541 if (Subtarget->is64Bit())
1542 setTargetDAGCombine(ISD::MUL);
1543 setTargetDAGCombine(ISD::XOR);
1545 computeRegisterProperties();
1547 // On Darwin, -Os means optimize for size without hurting performance,
1548 // do not reduce the limit.
1549 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1550 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1551 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1552 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1553 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1554 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555 setPrefLoopAlignment(4); // 2^4 bytes.
1557 // Predictable cmov don't hurt on atom because it's in-order.
1558 PredictableSelectIsExpensive = !Subtarget->isAtom();
1560 setPrefFunctionAlignment(4); // 2^4 bytes.
1563 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1565 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1567 if (Subtarget->hasAVX512())
1568 switch(VT.getVectorNumElements()) {
1569 case 8: return MVT::v8i1;
1570 case 16: return MVT::v16i1;
1573 return VT.changeVectorElementTypeToInteger();
1576 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1577 /// the desired ByVal argument alignment.
1578 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1581 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1582 if (VTy->getBitWidth() == 128)
1584 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1585 unsigned EltAlign = 0;
1586 getMaxByValAlign(ATy->getElementType(), EltAlign);
1587 if (EltAlign > MaxAlign)
1588 MaxAlign = EltAlign;
1589 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1590 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1591 unsigned EltAlign = 0;
1592 getMaxByValAlign(STy->getElementType(i), EltAlign);
1593 if (EltAlign > MaxAlign)
1594 MaxAlign = EltAlign;
1601 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1602 /// function arguments in the caller parameter area. For X86, aggregates
1603 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1604 /// are at 4-byte boundaries.
1605 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1606 if (Subtarget->is64Bit()) {
1607 // Max of 8 and alignment of type.
1608 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1615 if (Subtarget->hasSSE1())
1616 getMaxByValAlign(Ty, Align);
1620 /// getOptimalMemOpType - Returns the target specific optimal type for load
1621 /// and store operations as a result of memset, memcpy, and memmove
1622 /// lowering. If DstAlign is zero that means it's safe to destination
1623 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1624 /// means there isn't a need to check it against alignment requirement,
1625 /// probably because the source does not need to be loaded. If 'IsMemset' is
1626 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1627 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1628 /// source is constant so it does not need to be loaded.
1629 /// It returns EVT::Other if the type should be determined using generic
1630 /// target-independent logic.
1632 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1633 unsigned DstAlign, unsigned SrcAlign,
1634 bool IsMemset, bool ZeroMemset,
1636 MachineFunction &MF) const {
1637 const Function *F = MF.getFunction();
1638 if ((!IsMemset || ZeroMemset) &&
1639 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1640 Attribute::NoImplicitFloat)) {
1642 (Subtarget->isUnalignedMemAccessFast() ||
1643 ((DstAlign == 0 || DstAlign >= 16) &&
1644 (SrcAlign == 0 || SrcAlign >= 16)))) {
1646 if (Subtarget->hasInt256())
1648 if (Subtarget->hasFp256())
1651 if (Subtarget->hasSSE2())
1653 if (Subtarget->hasSSE1())
1655 } else if (!MemcpyStrSrc && Size >= 8 &&
1656 !Subtarget->is64Bit() &&
1657 Subtarget->hasSSE2()) {
1658 // Do not use f64 to lower memcpy if source is string constant. It's
1659 // better to use i32 to avoid the loads.
1663 if (Subtarget->is64Bit() && Size >= 8)
1668 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1670 return X86ScalarSSEf32;
1671 else if (VT == MVT::f64)
1672 return X86ScalarSSEf64;
1677 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1681 *Fast = Subtarget->isUnalignedMemAccessFast();
1685 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1686 /// current function. The returned value is a member of the
1687 /// MachineJumpTableInfo::JTEntryKind enum.
1688 unsigned X86TargetLowering::getJumpTableEncoding() const {
1689 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1691 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1692 Subtarget->isPICStyleGOT())
1693 return MachineJumpTableInfo::EK_Custom32;
1695 // Otherwise, use the normal jump table encoding heuristics.
1696 return TargetLowering::getJumpTableEncoding();
1700 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1701 const MachineBasicBlock *MBB,
1702 unsigned uid,MCContext &Ctx) const{
1703 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1704 Subtarget->isPICStyleGOT());
1705 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1707 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1708 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1711 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1713 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1714 SelectionDAG &DAG) const {
1715 if (!Subtarget->is64Bit())
1716 // This doesn't have SDLoc associated with it, but is not really the
1717 // same as a Register.
1718 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1722 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1723 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1725 const MCExpr *X86TargetLowering::
1726 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1727 MCContext &Ctx) const {
1728 // X86-64 uses RIP relative addressing based on the jump table label.
1729 if (Subtarget->isPICStyleRIPRel())
1730 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1732 // Otherwise, the reference is relative to the PIC base.
1733 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1736 // FIXME: Why this routine is here? Move to RegInfo!
1737 std::pair<const TargetRegisterClass*, uint8_t>
1738 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1739 const TargetRegisterClass *RRC = 0;
1741 switch (VT.SimpleTy) {
1743 return TargetLowering::findRepresentativeClass(VT);
1744 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1745 RRC = Subtarget->is64Bit() ?
1746 (const TargetRegisterClass*)&X86::GR64RegClass :
1747 (const TargetRegisterClass*)&X86::GR32RegClass;
1750 RRC = &X86::VR64RegClass;
1752 case MVT::f32: case MVT::f64:
1753 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1754 case MVT::v4f32: case MVT::v2f64:
1755 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1757 RRC = &X86::VR128RegClass;
1760 return std::make_pair(RRC, Cost);
1763 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1764 unsigned &Offset) const {
1765 if (!Subtarget->isTargetLinux())
1768 if (Subtarget->is64Bit()) {
1769 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1771 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1783 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1784 unsigned DestAS) const {
1785 assert(SrcAS != DestAS && "Expected different address spaces!");
1787 return SrcAS < 256 && DestAS < 256;
1790 //===----------------------------------------------------------------------===//
1791 // Return Value Calling Convention Implementation
1792 //===----------------------------------------------------------------------===//
1794 #include "X86GenCallingConv.inc"
1797 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1798 MachineFunction &MF, bool isVarArg,
1799 const SmallVectorImpl<ISD::OutputArg> &Outs,
1800 LLVMContext &Context) const {
1801 SmallVector<CCValAssign, 16> RVLocs;
1802 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1804 return CCInfo.CheckReturn(Outs, RetCC_X86);
1807 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1808 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1813 X86TargetLowering::LowerReturn(SDValue Chain,
1814 CallingConv::ID CallConv, bool isVarArg,
1815 const SmallVectorImpl<ISD::OutputArg> &Outs,
1816 const SmallVectorImpl<SDValue> &OutVals,
1817 SDLoc dl, SelectionDAG &DAG) const {
1818 MachineFunction &MF = DAG.getMachineFunction();
1819 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1821 SmallVector<CCValAssign, 16> RVLocs;
1822 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1823 RVLocs, *DAG.getContext());
1824 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1827 SmallVector<SDValue, 6> RetOps;
1828 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1829 // Operand #1 = Bytes To Pop
1830 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1833 // Copy the result values into the output registers.
1834 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1835 CCValAssign &VA = RVLocs[i];
1836 assert(VA.isRegLoc() && "Can only return in registers!");
1837 SDValue ValToCopy = OutVals[i];
1838 EVT ValVT = ValToCopy.getValueType();
1840 // Promote values to the appropriate types
1841 if (VA.getLocInfo() == CCValAssign::SExt)
1842 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1843 else if (VA.getLocInfo() == CCValAssign::ZExt)
1844 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845 else if (VA.getLocInfo() == CCValAssign::AExt)
1846 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847 else if (VA.getLocInfo() == CCValAssign::BCvt)
1848 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1850 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1851 "Unexpected FP-extend for return value.");
1853 // If this is x86-64, and we disabled SSE, we can't return FP values,
1854 // or SSE or MMX vectors.
1855 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1856 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1857 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1858 report_fatal_error("SSE register return with SSE disabled");
1860 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1861 // llvm-gcc has never done it right and no one has noticed, so this
1862 // should be OK for now.
1863 if (ValVT == MVT::f64 &&
1864 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1865 report_fatal_error("SSE2 register return with SSE2 disabled");
1867 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1868 // the RET instruction and handled by the FP Stackifier.
1869 if (VA.getLocReg() == X86::ST0 ||
1870 VA.getLocReg() == X86::ST1) {
1871 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1872 // change the value to the FP stack register class.
1873 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1874 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1875 RetOps.push_back(ValToCopy);
1876 // Don't emit a copytoreg.
1880 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1881 // which is returned in RAX / RDX.
1882 if (Subtarget->is64Bit()) {
1883 if (ValVT == MVT::x86mmx) {
1884 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1885 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1886 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1888 // If we don't have SSE2 available, convert to v4f32 so the generated
1889 // register is legal.
1890 if (!Subtarget->hasSSE2())
1891 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1896 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1897 Flag = Chain.getValue(1);
1898 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1901 // The x86-64 ABIs require that for returning structs by value we copy
1902 // the sret argument into %rax/%eax (depending on ABI) for the return.
1903 // Win32 requires us to put the sret argument to %eax as well.
1904 // We saved the argument into a virtual register in the entry block,
1905 // so now we copy the value out and into %rax/%eax.
1906 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1907 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1908 MachineFunction &MF = DAG.getMachineFunction();
1909 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1910 unsigned Reg = FuncInfo->getSRetReturnReg();
1912 "SRetReturnReg should have been set in LowerFormalArguments().");
1913 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1916 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1917 X86::RAX : X86::EAX;
1918 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1919 Flag = Chain.getValue(1);
1921 // RAX/EAX now acts like a return value.
1922 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1925 RetOps[0] = Chain; // Update chain.
1927 // Add the flag if we have it.
1929 RetOps.push_back(Flag);
1931 return DAG.getNode(X86ISD::RET_FLAG, dl,
1932 MVT::Other, &RetOps[0], RetOps.size());
1935 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1936 if (N->getNumValues() != 1)
1938 if (!N->hasNUsesOfValue(1, 0))
1941 SDValue TCChain = Chain;
1942 SDNode *Copy = *N->use_begin();
1943 if (Copy->getOpcode() == ISD::CopyToReg) {
1944 // If the copy has a glue operand, we conservatively assume it isn't safe to
1945 // perform a tail call.
1946 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1948 TCChain = Copy->getOperand(0);
1949 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1952 bool HasRet = false;
1953 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1955 if (UI->getOpcode() != X86ISD::RET_FLAG)
1968 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1969 ISD::NodeType ExtendKind) const {
1971 // TODO: Is this also valid on 32-bit?
1972 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1973 ReturnMVT = MVT::i8;
1975 ReturnMVT = MVT::i32;
1977 MVT MinVT = getRegisterType(ReturnMVT);
1978 return VT.bitsLT(MinVT) ? MinVT : VT;
1981 /// LowerCallResult - Lower the result values of a call into the
1982 /// appropriate copies out of appropriate physical registers.
1985 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1986 CallingConv::ID CallConv, bool isVarArg,
1987 const SmallVectorImpl<ISD::InputArg> &Ins,
1988 SDLoc dl, SelectionDAG &DAG,
1989 SmallVectorImpl<SDValue> &InVals) const {
1991 // Assign locations to each value returned by this call.
1992 SmallVector<CCValAssign, 16> RVLocs;
1993 bool Is64Bit = Subtarget->is64Bit();
1994 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1995 getTargetMachine(), RVLocs, *DAG.getContext());
1996 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1998 // Copy all of the result registers out of their specified physreg.
1999 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2000 CCValAssign &VA = RVLocs[i];
2001 EVT CopyVT = VA.getValVT();
2003 // If this is x86-64, and we disabled SSE, we can't return FP values
2004 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2005 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2006 report_fatal_error("SSE register return with SSE disabled");
2011 // If this is a call to a function that returns an fp value on the floating
2012 // point stack, we must guarantee the value is popped from the stack, so
2013 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2014 // if the return value is not used. We use the FpPOP_RETVAL instruction
2016 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2017 // If we prefer to use the value in xmm registers, copy it out as f80 and
2018 // use a truncate to move it from fp stack reg to xmm reg.
2019 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2020 SDValue Ops[] = { Chain, InFlag };
2021 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2022 MVT::Other, MVT::Glue, Ops), 1);
2023 Val = Chain.getValue(0);
2025 // Round the f80 to the right size, which also moves it to the appropriate
2027 if (CopyVT != VA.getValVT())
2028 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2029 // This truncation won't change the value.
2030 DAG.getIntPtrConstant(1));
2032 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2033 CopyVT, InFlag).getValue(1);
2034 Val = Chain.getValue(0);
2036 InFlag = Chain.getValue(2);
2037 InVals.push_back(Val);
2043 //===----------------------------------------------------------------------===//
2044 // C & StdCall & Fast Calling Convention implementation
2045 //===----------------------------------------------------------------------===//
2046 // StdCall calling convention seems to be standard for many Windows' API
2047 // routines and around. It differs from C calling convention just a little:
2048 // callee should clean up the stack, not caller. Symbols should be also
2049 // decorated in some fancy way :) It doesn't support any vector arguments.
2050 // For info on fast calling convention see Fast Calling Convention (tail call)
2051 // implementation LowerX86_32FastCCCallTo.
2053 /// CallIsStructReturn - Determines whether a call uses struct return
2055 enum StructReturnType {
2060 static StructReturnType
2061 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2063 return NotStructReturn;
2065 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2066 if (!Flags.isSRet())
2067 return NotStructReturn;
2068 if (Flags.isInReg())
2069 return RegStructReturn;
2070 return StackStructReturn;
2073 /// ArgsAreStructReturn - Determines whether a function uses struct
2074 /// return semantics.
2075 static StructReturnType
2076 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2078 return NotStructReturn;
2080 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2081 if (!Flags.isSRet())
2082 return NotStructReturn;
2083 if (Flags.isInReg())
2084 return RegStructReturn;
2085 return StackStructReturn;
2088 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2089 /// by "Src" to address "Dst" with size and alignment information specified by
2090 /// the specific parameter attribute. The copy will be passed as a byval
2091 /// function parameter.
2093 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2094 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2096 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2098 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2099 /*isVolatile*/false, /*AlwaysInline=*/true,
2100 MachinePointerInfo(), MachinePointerInfo());
2103 /// IsTailCallConvention - Return true if the calling convention is one that
2104 /// supports tail call optimization.
2105 static bool IsTailCallConvention(CallingConv::ID CC) {
2106 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2107 CC == CallingConv::HiPE);
2110 /// \brief Return true if the calling convention is a C calling convention.
2111 static bool IsCCallConvention(CallingConv::ID CC) {
2112 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2113 CC == CallingConv::X86_64_SysV);
2116 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2117 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2121 CallingConv::ID CalleeCC = CS.getCallingConv();
2122 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2128 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2129 /// a tailcall target by changing its ABI.
2130 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2131 bool GuaranteedTailCallOpt) {
2132 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2136 X86TargetLowering::LowerMemArgument(SDValue Chain,
2137 CallingConv::ID CallConv,
2138 const SmallVectorImpl<ISD::InputArg> &Ins,
2139 SDLoc dl, SelectionDAG &DAG,
2140 const CCValAssign &VA,
2141 MachineFrameInfo *MFI,
2143 // Create the nodes corresponding to a load from this parameter slot.
2144 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2145 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2146 getTargetMachine().Options.GuaranteedTailCallOpt);
2147 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2150 // If value is passed by pointer we have address passed instead of the value
2152 if (VA.getLocInfo() == CCValAssign::Indirect)
2153 ValVT = VA.getLocVT();
2155 ValVT = VA.getValVT();
2157 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2158 // changed with more analysis.
2159 // In case of tail call optimization mark all arguments mutable. Since they
2160 // could be overwritten by lowering of arguments in case of a tail call.
2161 if (Flags.isByVal()) {
2162 unsigned Bytes = Flags.getByValSize();
2163 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2164 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2165 return DAG.getFrameIndex(FI, getPointerTy());
2167 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2168 VA.getLocMemOffset(), isImmutable);
2169 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2170 return DAG.getLoad(ValVT, dl, Chain, FIN,
2171 MachinePointerInfo::getFixedStack(FI),
2172 false, false, false, 0);
2177 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2178 CallingConv::ID CallConv,
2180 const SmallVectorImpl<ISD::InputArg> &Ins,
2183 SmallVectorImpl<SDValue> &InVals)
2185 MachineFunction &MF = DAG.getMachineFunction();
2186 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2188 const Function* Fn = MF.getFunction();
2189 if (Fn->hasExternalLinkage() &&
2190 Subtarget->isTargetCygMing() &&
2191 Fn->getName() == "main")
2192 FuncInfo->setForceFramePointer(true);
2194 MachineFrameInfo *MFI = MF.getFrameInfo();
2195 bool Is64Bit = Subtarget->is64Bit();
2196 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2198 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2199 "Var args not supported with calling convention fastcc, ghc or hipe");
2201 // Assign locations to all of the incoming arguments.
2202 SmallVector<CCValAssign, 16> ArgLocs;
2203 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2204 ArgLocs, *DAG.getContext());
2206 // Allocate shadow area for Win64
2208 CCInfo.AllocateStack(32, 8);
2210 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2212 unsigned LastVal = ~0U;
2214 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2215 CCValAssign &VA = ArgLocs[i];
2216 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2218 assert(VA.getValNo() != LastVal &&
2219 "Don't support value assigned to multiple locs yet");
2221 LastVal = VA.getValNo();
2223 if (VA.isRegLoc()) {
2224 EVT RegVT = VA.getLocVT();
2225 const TargetRegisterClass *RC;
2226 if (RegVT == MVT::i32)
2227 RC = &X86::GR32RegClass;
2228 else if (Is64Bit && RegVT == MVT::i64)
2229 RC = &X86::GR64RegClass;
2230 else if (RegVT == MVT::f32)
2231 RC = &X86::FR32RegClass;
2232 else if (RegVT == MVT::f64)
2233 RC = &X86::FR64RegClass;
2234 else if (RegVT.is512BitVector())
2235 RC = &X86::VR512RegClass;
2236 else if (RegVT.is256BitVector())
2237 RC = &X86::VR256RegClass;
2238 else if (RegVT.is128BitVector())
2239 RC = &X86::VR128RegClass;
2240 else if (RegVT == MVT::x86mmx)
2241 RC = &X86::VR64RegClass;
2242 else if (RegVT == MVT::i1)
2243 RC = &X86::VK1RegClass;
2244 else if (RegVT == MVT::v8i1)
2245 RC = &X86::VK8RegClass;
2246 else if (RegVT == MVT::v16i1)
2247 RC = &X86::VK16RegClass;
2249 llvm_unreachable("Unknown argument type!");
2251 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2252 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2254 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2255 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2257 if (VA.getLocInfo() == CCValAssign::SExt)
2258 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2259 DAG.getValueType(VA.getValVT()));
2260 else if (VA.getLocInfo() == CCValAssign::ZExt)
2261 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2262 DAG.getValueType(VA.getValVT()));
2263 else if (VA.getLocInfo() == CCValAssign::BCvt)
2264 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2266 if (VA.isExtInLoc()) {
2267 // Handle MMX values passed in XMM regs.
2268 if (RegVT.isVector())
2269 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2271 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2274 assert(VA.isMemLoc());
2275 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2278 // If value is passed via pointer - do a load.
2279 if (VA.getLocInfo() == CCValAssign::Indirect)
2280 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2281 MachinePointerInfo(), false, false, false, 0);
2283 InVals.push_back(ArgValue);
2286 // The x86-64 ABIs require that for returning structs by value we copy
2287 // the sret argument into %rax/%eax (depending on ABI) for the return.
2288 // Win32 requires us to put the sret argument to %eax as well.
2289 // Save the argument into a virtual register so that we can access it
2290 // from the return points.
2291 if (MF.getFunction()->hasStructRetAttr() &&
2292 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2293 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2294 unsigned Reg = FuncInfo->getSRetReturnReg();
2296 MVT PtrTy = getPointerTy();
2297 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2298 FuncInfo->setSRetReturnReg(Reg);
2300 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2301 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2304 unsigned StackSize = CCInfo.getNextStackOffset();
2305 // Align stack specially for tail calls.
2306 if (FuncIsMadeTailCallSafe(CallConv,
2307 MF.getTarget().Options.GuaranteedTailCallOpt))
2308 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2310 // If the function takes variable number of arguments, make a frame index for
2311 // the start of the first vararg value... for expansion of llvm.va_start.
2313 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2314 CallConv != CallingConv::X86_ThisCall)) {
2315 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2318 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2320 // FIXME: We should really autogenerate these arrays
2321 static const MCPhysReg GPR64ArgRegsWin64[] = {
2322 X86::RCX, X86::RDX, X86::R8, X86::R9
2324 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2325 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2327 static const MCPhysReg XMMArgRegs64Bit[] = {
2328 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2329 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2331 const MCPhysReg *GPR64ArgRegs;
2332 unsigned NumXMMRegs = 0;
2335 // The XMM registers which might contain var arg parameters are shadowed
2336 // in their paired GPR. So we only need to save the GPR to their home
2338 TotalNumIntRegs = 4;
2339 GPR64ArgRegs = GPR64ArgRegsWin64;
2341 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2342 GPR64ArgRegs = GPR64ArgRegs64Bit;
2344 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2347 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2350 bool NoImplicitFloatOps = Fn->getAttributes().
2351 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2352 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2353 "SSE register cannot be used when SSE is disabled!");
2354 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2355 NoImplicitFloatOps) &&
2356 "SSE register cannot be used when SSE is disabled!");
2357 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2358 !Subtarget->hasSSE1())
2359 // Kernel mode asks for SSE to be disabled, so don't push them
2361 TotalNumXMMRegs = 0;
2364 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2365 // Get to the caller-allocated home save location. Add 8 to account
2366 // for the return address.
2367 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2368 FuncInfo->setRegSaveFrameIndex(
2369 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2370 // Fixup to set vararg frame on shadow area (4 x i64).
2372 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2374 // For X86-64, if there are vararg parameters that are passed via
2375 // registers, then we must store them to their spots on the stack so
2376 // they may be loaded by deferencing the result of va_next.
2377 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2378 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2379 FuncInfo->setRegSaveFrameIndex(
2380 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2384 // Store the integer parameter registers.
2385 SmallVector<SDValue, 8> MemOps;
2386 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2388 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2389 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2390 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2391 DAG.getIntPtrConstant(Offset));
2392 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2393 &X86::GR64RegClass);
2394 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2396 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2397 MachinePointerInfo::getFixedStack(
2398 FuncInfo->getRegSaveFrameIndex(), Offset),
2400 MemOps.push_back(Store);
2404 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2405 // Now store the XMM (fp + vector) parameter registers.
2406 SmallVector<SDValue, 11> SaveXMMOps;
2407 SaveXMMOps.push_back(Chain);
2409 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2410 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2411 SaveXMMOps.push_back(ALVal);
2413 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2414 FuncInfo->getRegSaveFrameIndex()));
2415 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416 FuncInfo->getVarArgsFPOffset()));
2418 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2419 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2420 &X86::VR128RegClass);
2421 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2422 SaveXMMOps.push_back(Val);
2424 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2426 &SaveXMMOps[0], SaveXMMOps.size()));
2429 if (!MemOps.empty())
2430 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2431 &MemOps[0], MemOps.size());
2435 // Some CCs need callee pop.
2436 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2437 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2438 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2440 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2441 // If this is an sret function, the return should pop the hidden pointer.
2442 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2443 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2444 argsAreStructReturn(Ins) == StackStructReturn)
2445 FuncInfo->setBytesToPopOnReturn(4);
2449 // RegSaveFrameIndex is X86-64 only.
2450 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2451 if (CallConv == CallingConv::X86_FastCall ||
2452 CallConv == CallingConv::X86_ThisCall)
2453 // fastcc functions can't have varargs.
2454 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2457 FuncInfo->setArgumentStackSize(StackSize);
2463 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2464 SDValue StackPtr, SDValue Arg,
2465 SDLoc dl, SelectionDAG &DAG,
2466 const CCValAssign &VA,
2467 ISD::ArgFlagsTy Flags) const {
2468 unsigned LocMemOffset = VA.getLocMemOffset();
2469 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2470 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2471 if (Flags.isByVal())
2472 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2474 return DAG.getStore(Chain, dl, Arg, PtrOff,
2475 MachinePointerInfo::getStack(LocMemOffset),
2479 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2480 /// optimization is performed and it is required.
2482 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2483 SDValue &OutRetAddr, SDValue Chain,
2484 bool IsTailCall, bool Is64Bit,
2485 int FPDiff, SDLoc dl) const {
2486 // Adjust the Return address stack slot.
2487 EVT VT = getPointerTy();
2488 OutRetAddr = getReturnAddressFrameIndex(DAG);
2490 // Load the "old" Return address.
2491 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2492 false, false, false, 0);
2493 return SDValue(OutRetAddr.getNode(), 1);
2496 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2497 /// optimization is performed and it is required (FPDiff!=0).
2499 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2500 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2501 unsigned SlotSize, int FPDiff, SDLoc dl) {
2502 // Store the return address to the appropriate stack slot.
2503 if (!FPDiff) return Chain;
2504 // Calculate the new stack slot for the return address.
2505 int NewReturnAddrFI =
2506 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2508 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2509 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2510 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2516 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2517 SmallVectorImpl<SDValue> &InVals) const {
2518 SelectionDAG &DAG = CLI.DAG;
2520 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2521 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2522 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2523 SDValue Chain = CLI.Chain;
2524 SDValue Callee = CLI.Callee;
2525 CallingConv::ID CallConv = CLI.CallConv;
2526 bool &isTailCall = CLI.IsTailCall;
2527 bool isVarArg = CLI.IsVarArg;
2529 MachineFunction &MF = DAG.getMachineFunction();
2530 bool Is64Bit = Subtarget->is64Bit();
2531 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2532 StructReturnType SR = callIsStructReturn(Outs);
2533 bool IsSibcall = false;
2535 if (MF.getTarget().Options.DisableTailCalls)
2539 // Check if it's really possible to do a tail call.
2540 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2541 isVarArg, SR != NotStructReturn,
2542 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2543 Outs, OutVals, Ins, DAG);
2545 // Sibcalls are automatically detected tailcalls which do not require
2547 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2554 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2555 "Var args not supported with calling convention fastcc, ghc or hipe");
2557 // Analyze operands of the call, assigning locations to each operand.
2558 SmallVector<CCValAssign, 16> ArgLocs;
2559 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2560 ArgLocs, *DAG.getContext());
2562 // Allocate shadow area for Win64
2564 CCInfo.AllocateStack(32, 8);
2566 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2568 // Get a count of how many bytes are to be pushed on the stack.
2569 unsigned NumBytes = CCInfo.getNextStackOffset();
2571 // This is a sibcall. The memory operands are available in caller's
2572 // own caller's stack.
2574 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2575 IsTailCallConvention(CallConv))
2576 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2579 if (isTailCall && !IsSibcall) {
2580 // Lower arguments at fp - stackoffset + fpdiff.
2581 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2582 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2584 FPDiff = NumBytesCallerPushed - NumBytes;
2586 // Set the delta of movement of the returnaddr stackslot.
2587 // But only set if delta is greater than previous delta.
2588 if (FPDiff < X86Info->getTCReturnAddrDelta())
2589 X86Info->setTCReturnAddrDelta(FPDiff);
2592 unsigned NumBytesToPush = NumBytes;
2593 unsigned NumBytesToPop = NumBytes;
2595 // If we have an inalloca argument, all stack space has already been allocated
2596 // for us and be right at the top of the stack. We don't support multiple
2597 // arguments passed in memory when using inalloca.
2598 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2600 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2601 "an inalloca argument must be the only memory argument");
2605 Chain = DAG.getCALLSEQ_START(
2606 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2608 SDValue RetAddrFrIdx;
2609 // Load return address for tail calls.
2610 if (isTailCall && FPDiff)
2611 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2612 Is64Bit, FPDiff, dl);
2614 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2615 SmallVector<SDValue, 8> MemOpChains;
2618 // Walk the register/memloc assignments, inserting copies/loads. In the case
2619 // of tail call optimization arguments are handle later.
2620 const X86RegisterInfo *RegInfo =
2621 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2622 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2623 // Skip inalloca arguments, they have already been written.
2624 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2625 if (Flags.isInAlloca())
2628 CCValAssign &VA = ArgLocs[i];
2629 EVT RegVT = VA.getLocVT();
2630 SDValue Arg = OutVals[i];
2631 bool isByVal = Flags.isByVal();
2633 // Promote the value if needed.
2634 switch (VA.getLocInfo()) {
2635 default: llvm_unreachable("Unknown loc info!");
2636 case CCValAssign::Full: break;
2637 case CCValAssign::SExt:
2638 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2640 case CCValAssign::ZExt:
2641 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2643 case CCValAssign::AExt:
2644 if (RegVT.is128BitVector()) {
2645 // Special case: passing MMX values in XMM registers.
2646 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2647 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2648 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2650 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2652 case CCValAssign::BCvt:
2653 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2655 case CCValAssign::Indirect: {
2656 // Store the argument.
2657 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2658 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2659 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2660 MachinePointerInfo::getFixedStack(FI),
2667 if (VA.isRegLoc()) {
2668 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2669 if (isVarArg && IsWin64) {
2670 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2671 // shadow reg if callee is a varargs function.
2672 unsigned ShadowReg = 0;
2673 switch (VA.getLocReg()) {
2674 case X86::XMM0: ShadowReg = X86::RCX; break;
2675 case X86::XMM1: ShadowReg = X86::RDX; break;
2676 case X86::XMM2: ShadowReg = X86::R8; break;
2677 case X86::XMM3: ShadowReg = X86::R9; break;
2680 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2682 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2683 assert(VA.isMemLoc());
2684 if (StackPtr.getNode() == 0)
2685 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2687 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2688 dl, DAG, VA, Flags));
2692 if (!MemOpChains.empty())
2693 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2694 &MemOpChains[0], MemOpChains.size());
2696 if (Subtarget->isPICStyleGOT()) {
2697 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2700 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2701 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2703 // If we are tail calling and generating PIC/GOT style code load the
2704 // address of the callee into ECX. The value in ecx is used as target of
2705 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2706 // for tail calls on PIC/GOT architectures. Normally we would just put the
2707 // address of GOT into ebx and then call target@PLT. But for tail calls
2708 // ebx would be restored (since ebx is callee saved) before jumping to the
2711 // Note: The actual moving to ECX is done further down.
2712 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2713 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2714 !G->getGlobal()->hasProtectedVisibility())
2715 Callee = LowerGlobalAddress(Callee, DAG);
2716 else if (isa<ExternalSymbolSDNode>(Callee))
2717 Callee = LowerExternalSymbol(Callee, DAG);
2721 if (Is64Bit && isVarArg && !IsWin64) {
2722 // From AMD64 ABI document:
2723 // For calls that may call functions that use varargs or stdargs
2724 // (prototype-less calls or calls to functions containing ellipsis (...) in
2725 // the declaration) %al is used as hidden argument to specify the number
2726 // of SSE registers used. The contents of %al do not need to match exactly
2727 // the number of registers, but must be an ubound on the number of SSE
2728 // registers used and is in the range 0 - 8 inclusive.
2730 // Count the number of XMM registers allocated.
2731 static const MCPhysReg XMMArgRegs[] = {
2732 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2733 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2735 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2736 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2737 && "SSE registers cannot be used when SSE is disabled");
2739 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2740 DAG.getConstant(NumXMMRegs, MVT::i8)));
2743 // For tail calls lower the arguments to the 'real' stack slot.
2745 // Force all the incoming stack arguments to be loaded from the stack
2746 // before any new outgoing arguments are stored to the stack, because the
2747 // outgoing stack slots may alias the incoming argument stack slots, and
2748 // the alias isn't otherwise explicit. This is slightly more conservative
2749 // than necessary, because it means that each store effectively depends
2750 // on every argument instead of just those arguments it would clobber.
2751 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2753 SmallVector<SDValue, 8> MemOpChains2;
2756 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2757 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2758 CCValAssign &VA = ArgLocs[i];
2761 assert(VA.isMemLoc());
2762 SDValue Arg = OutVals[i];
2763 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2764 // Create frame index.
2765 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2766 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2767 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2768 FIN = DAG.getFrameIndex(FI, getPointerTy());
2770 if (Flags.isByVal()) {
2771 // Copy relative to framepointer.
2772 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2773 if (StackPtr.getNode() == 0)
2774 StackPtr = DAG.getCopyFromReg(Chain, dl,
2775 RegInfo->getStackRegister(),
2777 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2779 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2783 // Store relative to framepointer.
2784 MemOpChains2.push_back(
2785 DAG.getStore(ArgChain, dl, Arg, FIN,
2786 MachinePointerInfo::getFixedStack(FI),
2792 if (!MemOpChains2.empty())
2793 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2794 &MemOpChains2[0], MemOpChains2.size());
2796 // Store the return address to the appropriate stack slot.
2797 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2798 getPointerTy(), RegInfo->getSlotSize(),
2802 // Build a sequence of copy-to-reg nodes chained together with token chain
2803 // and flag operands which copy the outgoing args into registers.
2805 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2806 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2807 RegsToPass[i].second, InFlag);
2808 InFlag = Chain.getValue(1);
2811 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2812 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2813 // In the 64-bit large code model, we have to make all calls
2814 // through a register, since the call instruction's 32-bit
2815 // pc-relative offset may not be large enough to hold the whole
2817 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2818 // If the callee is a GlobalAddress node (quite common, every direct call
2819 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2822 // We should use extra load for direct calls to dllimported functions in
2824 const GlobalValue *GV = G->getGlobal();
2825 if (!GV->hasDLLImportStorageClass()) {
2826 unsigned char OpFlags = 0;
2827 bool ExtraLoad = false;
2828 unsigned WrapperKind = ISD::DELETED_NODE;
2830 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2831 // external symbols most go through the PLT in PIC mode. If the symbol
2832 // has hidden or protected visibility, or if it is static or local, then
2833 // we don't need to use the PLT - we can directly call it.
2834 if (Subtarget->isTargetELF() &&
2835 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2836 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2837 OpFlags = X86II::MO_PLT;
2838 } else if (Subtarget->isPICStyleStubAny() &&
2839 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2840 (!Subtarget->getTargetTriple().isMacOSX() ||
2841 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2842 // PC-relative references to external symbols should go through $stub,
2843 // unless we're building with the leopard linker or later, which
2844 // automatically synthesizes these stubs.
2845 OpFlags = X86II::MO_DARWIN_STUB;
2846 } else if (Subtarget->isPICStyleRIPRel() &&
2847 isa<Function>(GV) &&
2848 cast<Function>(GV)->getAttributes().
2849 hasAttribute(AttributeSet::FunctionIndex,
2850 Attribute::NonLazyBind)) {
2851 // If the function is marked as non-lazy, generate an indirect call
2852 // which loads from the GOT directly. This avoids runtime overhead
2853 // at the cost of eager binding (and one extra byte of encoding).
2854 OpFlags = X86II::MO_GOTPCREL;
2855 WrapperKind = X86ISD::WrapperRIP;
2859 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2860 G->getOffset(), OpFlags);
2862 // Add a wrapper if needed.
2863 if (WrapperKind != ISD::DELETED_NODE)
2864 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2865 // Add extra indirection if needed.
2867 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2868 MachinePointerInfo::getGOT(),
2869 false, false, false, 0);
2871 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2872 unsigned char OpFlags = 0;
2874 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2875 // external symbols should go through the PLT.
2876 if (Subtarget->isTargetELF() &&
2877 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2878 OpFlags = X86II::MO_PLT;
2879 } else if (Subtarget->isPICStyleStubAny() &&
2880 (!Subtarget->getTargetTriple().isMacOSX() ||
2881 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2882 // PC-relative references to external symbols should go through $stub,
2883 // unless we're building with the leopard linker or later, which
2884 // automatically synthesizes these stubs.
2885 OpFlags = X86II::MO_DARWIN_STUB;
2888 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2892 // Returns a chain & a flag for retval copy to use.
2893 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2894 SmallVector<SDValue, 8> Ops;
2896 if (!IsSibcall && isTailCall) {
2897 Chain = DAG.getCALLSEQ_END(Chain,
2898 DAG.getIntPtrConstant(NumBytesToPop, true),
2899 DAG.getIntPtrConstant(0, true), InFlag, dl);
2900 InFlag = Chain.getValue(1);
2903 Ops.push_back(Chain);
2904 Ops.push_back(Callee);
2907 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2909 // Add argument registers to the end of the list so that they are known live
2911 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2912 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2913 RegsToPass[i].second.getValueType()));
2915 // Add a register mask operand representing the call-preserved registers.
2916 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2917 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2918 assert(Mask && "Missing call preserved mask for calling convention");
2919 Ops.push_back(DAG.getRegisterMask(Mask));
2921 if (InFlag.getNode())
2922 Ops.push_back(InFlag);
2926 //// If this is the first return lowered for this function, add the regs
2927 //// to the liveout set for the function.
2928 // This isn't right, although it's probably harmless on x86; liveouts
2929 // should be computed from returns not tail calls. Consider a void
2930 // function making a tail call to a function returning int.
2931 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2934 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2935 InFlag = Chain.getValue(1);
2937 // Create the CALLSEQ_END node.
2938 unsigned NumBytesForCalleeToPop;
2939 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2940 getTargetMachine().Options.GuaranteedTailCallOpt))
2941 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2942 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2943 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2944 SR == StackStructReturn)
2945 // If this is a call to a struct-return function, the callee
2946 // pops the hidden struct pointer, so we have to push it back.
2947 // This is common for Darwin/X86, Linux & Mingw32 targets.
2948 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2949 NumBytesForCalleeToPop = 4;
2951 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2953 // Returns a flag for retval copy to use.
2955 Chain = DAG.getCALLSEQ_END(Chain,
2956 DAG.getIntPtrConstant(NumBytesToPop, true),
2957 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2960 InFlag = Chain.getValue(1);
2963 // Handle result values, copying them out of physregs into vregs that we
2965 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2966 Ins, dl, DAG, InVals);
2969 //===----------------------------------------------------------------------===//
2970 // Fast Calling Convention (tail call) implementation
2971 //===----------------------------------------------------------------------===//
2973 // Like std call, callee cleans arguments, convention except that ECX is
2974 // reserved for storing the tail called function address. Only 2 registers are
2975 // free for argument passing (inreg). Tail call optimization is performed
2977 // * tailcallopt is enabled
2978 // * caller/callee are fastcc
2979 // On X86_64 architecture with GOT-style position independent code only local
2980 // (within module) calls are supported at the moment.
2981 // To keep the stack aligned according to platform abi the function
2982 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2983 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2984 // If a tail called function callee has more arguments than the caller the
2985 // caller needs to make sure that there is room to move the RETADDR to. This is
2986 // achieved by reserving an area the size of the argument delta right after the
2987 // original REtADDR, but before the saved framepointer or the spilled registers
2988 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3000 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3001 /// for a 16 byte align requirement.
3003 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3004 SelectionDAG& DAG) const {
3005 MachineFunction &MF = DAG.getMachineFunction();
3006 const TargetMachine &TM = MF.getTarget();
3007 const X86RegisterInfo *RegInfo =
3008 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3009 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3010 unsigned StackAlignment = TFI.getStackAlignment();
3011 uint64_t AlignMask = StackAlignment - 1;
3012 int64_t Offset = StackSize;
3013 unsigned SlotSize = RegInfo->getSlotSize();
3014 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3015 // Number smaller than 12 so just add the difference.
3016 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3018 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3019 Offset = ((~AlignMask) & Offset) + StackAlignment +
3020 (StackAlignment-SlotSize);
3025 /// MatchingStackOffset - Return true if the given stack call argument is
3026 /// already available in the same position (relatively) of the caller's
3027 /// incoming argument stack.
3029 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3030 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3031 const X86InstrInfo *TII) {
3032 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3034 if (Arg.getOpcode() == ISD::CopyFromReg) {
3035 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3036 if (!TargetRegisterInfo::isVirtualRegister(VR))
3038 MachineInstr *Def = MRI->getVRegDef(VR);
3041 if (!Flags.isByVal()) {
3042 if (!TII->isLoadFromStackSlot(Def, FI))
3045 unsigned Opcode = Def->getOpcode();
3046 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3047 Def->getOperand(1).isFI()) {
3048 FI = Def->getOperand(1).getIndex();
3049 Bytes = Flags.getByValSize();
3053 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3054 if (Flags.isByVal())
3055 // ByVal argument is passed in as a pointer but it's now being
3056 // dereferenced. e.g.
3057 // define @foo(%struct.X* %A) {
3058 // tail call @bar(%struct.X* byval %A)
3061 SDValue Ptr = Ld->getBasePtr();
3062 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3065 FI = FINode->getIndex();
3066 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3067 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3068 FI = FINode->getIndex();
3069 Bytes = Flags.getByValSize();
3073 assert(FI != INT_MAX);
3074 if (!MFI->isFixedObjectIndex(FI))
3076 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3079 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3080 /// for tail call optimization. Targets which want to do tail call
3081 /// optimization should implement this function.
3083 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3084 CallingConv::ID CalleeCC,
3086 bool isCalleeStructRet,
3087 bool isCallerStructRet,
3089 const SmallVectorImpl<ISD::OutputArg> &Outs,
3090 const SmallVectorImpl<SDValue> &OutVals,
3091 const SmallVectorImpl<ISD::InputArg> &Ins,
3092 SelectionDAG &DAG) const {
3093 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3096 // If -tailcallopt is specified, make fastcc functions tail-callable.
3097 const MachineFunction &MF = DAG.getMachineFunction();
3098 const Function *CallerF = MF.getFunction();
3100 // If the function return type is x86_fp80 and the callee return type is not,
3101 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3102 // perform a tailcall optimization here.
3103 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3106 CallingConv::ID CallerCC = CallerF->getCallingConv();
3107 bool CCMatch = CallerCC == CalleeCC;
3108 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3109 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3111 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3112 if (IsTailCallConvention(CalleeCC) && CCMatch)
3117 // Look for obvious safe cases to perform tail call optimization that do not
3118 // require ABI changes. This is what gcc calls sibcall.
3120 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3121 // emit a special epilogue.
3122 const X86RegisterInfo *RegInfo =
3123 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3124 if (RegInfo->needsStackRealignment(MF))
3127 // Also avoid sibcall optimization if either caller or callee uses struct
3128 // return semantics.
3129 if (isCalleeStructRet || isCallerStructRet)
3132 // An stdcall/thiscall caller is expected to clean up its arguments; the
3133 // callee isn't going to do that.
3134 // FIXME: this is more restrictive than needed. We could produce a tailcall
3135 // when the stack adjustment matches. For example, with a thiscall that takes
3136 // only one argument.
3137 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3138 CallerCC == CallingConv::X86_ThisCall))
3141 // Do not sibcall optimize vararg calls unless all arguments are passed via
3143 if (isVarArg && !Outs.empty()) {
3145 // Optimizing for varargs on Win64 is unlikely to be safe without
3146 // additional testing.
3147 if (IsCalleeWin64 || IsCallerWin64)
3150 SmallVector<CCValAssign, 16> ArgLocs;
3151 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3152 getTargetMachine(), ArgLocs, *DAG.getContext());
3154 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3155 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3156 if (!ArgLocs[i].isRegLoc())
3160 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3161 // stack. Therefore, if it's not used by the call it is not safe to optimize
3162 // this into a sibcall.
3163 bool Unused = false;
3164 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3171 SmallVector<CCValAssign, 16> RVLocs;
3172 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3173 getTargetMachine(), RVLocs, *DAG.getContext());
3174 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3175 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3176 CCValAssign &VA = RVLocs[i];
3177 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3182 // If the calling conventions do not match, then we'd better make sure the
3183 // results are returned in the same way as what the caller expects.
3185 SmallVector<CCValAssign, 16> RVLocs1;
3186 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3187 getTargetMachine(), RVLocs1, *DAG.getContext());
3188 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3190 SmallVector<CCValAssign, 16> RVLocs2;
3191 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3192 getTargetMachine(), RVLocs2, *DAG.getContext());
3193 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3195 if (RVLocs1.size() != RVLocs2.size())
3197 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3198 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3200 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3202 if (RVLocs1[i].isRegLoc()) {
3203 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3206 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3212 // If the callee takes no arguments then go on to check the results of the
3214 if (!Outs.empty()) {
3215 // Check if stack adjustment is needed. For now, do not do this if any
3216 // argument is passed on the stack.
3217 SmallVector<CCValAssign, 16> ArgLocs;
3218 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3219 getTargetMachine(), ArgLocs, *DAG.getContext());
3221 // Allocate shadow area for Win64
3223 CCInfo.AllocateStack(32, 8);
3225 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3226 if (CCInfo.getNextStackOffset()) {
3227 MachineFunction &MF = DAG.getMachineFunction();
3228 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3231 // Check if the arguments are already laid out in the right way as
3232 // the caller's fixed stack objects.
3233 MachineFrameInfo *MFI = MF.getFrameInfo();
3234 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3235 const X86InstrInfo *TII =
3236 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3237 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3238 CCValAssign &VA = ArgLocs[i];
3239 SDValue Arg = OutVals[i];
3240 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3241 if (VA.getLocInfo() == CCValAssign::Indirect)
3243 if (!VA.isRegLoc()) {
3244 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3251 // If the tailcall address may be in a register, then make sure it's
3252 // possible to register allocate for it. In 32-bit, the call address can
3253 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3254 // callee-saved registers are restored. These happen to be the same
3255 // registers used to pass 'inreg' arguments so watch out for those.
3256 if (!Subtarget->is64Bit() &&
3257 ((!isa<GlobalAddressSDNode>(Callee) &&
3258 !isa<ExternalSymbolSDNode>(Callee)) ||
3259 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3260 unsigned NumInRegs = 0;
3261 // In PIC we need an extra register to formulate the address computation
3263 unsigned MaxInRegs =
3264 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3266 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3267 CCValAssign &VA = ArgLocs[i];
3270 unsigned Reg = VA.getLocReg();
3273 case X86::EAX: case X86::EDX: case X86::ECX:
3274 if (++NumInRegs == MaxInRegs)
3286 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3287 const TargetLibraryInfo *libInfo) const {
3288 return X86::createFastISel(funcInfo, libInfo);
3291 //===----------------------------------------------------------------------===//
3292 // Other Lowering Hooks
3293 //===----------------------------------------------------------------------===//
3295 static bool MayFoldLoad(SDValue Op) {
3296 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3299 static bool MayFoldIntoStore(SDValue Op) {
3300 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3303 static bool isTargetShuffle(unsigned Opcode) {
3305 default: return false;
3306 case X86ISD::PSHUFD:
3307 case X86ISD::PSHUFHW:
3308 case X86ISD::PSHUFLW:
3310 case X86ISD::PALIGNR:
3311 case X86ISD::MOVLHPS:
3312 case X86ISD::MOVLHPD:
3313 case X86ISD::MOVHLPS:
3314 case X86ISD::MOVLPS:
3315 case X86ISD::MOVLPD:
3316 case X86ISD::MOVSHDUP:
3317 case X86ISD::MOVSLDUP:
3318 case X86ISD::MOVDDUP:
3321 case X86ISD::UNPCKL:
3322 case X86ISD::UNPCKH:
3323 case X86ISD::VPERMILP:
3324 case X86ISD::VPERM2X128:
3325 case X86ISD::VPERMI:
3330 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3331 SDValue V1, SelectionDAG &DAG) {
3333 default: llvm_unreachable("Unknown x86 shuffle node");
3334 case X86ISD::MOVSHDUP:
3335 case X86ISD::MOVSLDUP:
3336 case X86ISD::MOVDDUP:
3337 return DAG.getNode(Opc, dl, VT, V1);
3341 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3342 SDValue V1, unsigned TargetMask,
3343 SelectionDAG &DAG) {
3345 default: llvm_unreachable("Unknown x86 shuffle node");
3346 case X86ISD::PSHUFD:
3347 case X86ISD::PSHUFHW:
3348 case X86ISD::PSHUFLW:
3349 case X86ISD::VPERMILP:
3350 case X86ISD::VPERMI:
3351 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3355 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3356 SDValue V1, SDValue V2, unsigned TargetMask,
3357 SelectionDAG &DAG) {
3359 default: llvm_unreachable("Unknown x86 shuffle node");
3360 case X86ISD::PALIGNR:
3362 case X86ISD::VPERM2X128:
3363 return DAG.getNode(Opc, dl, VT, V1, V2,
3364 DAG.getConstant(TargetMask, MVT::i8));
3368 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3369 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3371 default: llvm_unreachable("Unknown x86 shuffle node");
3372 case X86ISD::MOVLHPS:
3373 case X86ISD::MOVLHPD:
3374 case X86ISD::MOVHLPS:
3375 case X86ISD::MOVLPS:
3376 case X86ISD::MOVLPD:
3379 case X86ISD::UNPCKL:
3380 case X86ISD::UNPCKH:
3381 return DAG.getNode(Opc, dl, VT, V1, V2);
3385 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3386 MachineFunction &MF = DAG.getMachineFunction();
3387 const X86RegisterInfo *RegInfo =
3388 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3389 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3390 int ReturnAddrIndex = FuncInfo->getRAIndex();
3392 if (ReturnAddrIndex == 0) {
3393 // Set up a frame object for the return address.
3394 unsigned SlotSize = RegInfo->getSlotSize();
3395 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3398 FuncInfo->setRAIndex(ReturnAddrIndex);
3401 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3404 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3405 bool hasSymbolicDisplacement) {
3406 // Offset should fit into 32 bit immediate field.
3407 if (!isInt<32>(Offset))
3410 // If we don't have a symbolic displacement - we don't have any extra
3412 if (!hasSymbolicDisplacement)
3415 // FIXME: Some tweaks might be needed for medium code model.
3416 if (M != CodeModel::Small && M != CodeModel::Kernel)
3419 // For small code model we assume that latest object is 16MB before end of 31
3420 // bits boundary. We may also accept pretty large negative constants knowing
3421 // that all objects are in the positive half of address space.
3422 if (M == CodeModel::Small && Offset < 16*1024*1024)
3425 // For kernel code model we know that all object resist in the negative half
3426 // of 32bits address space. We may not accept negative offsets, since they may
3427 // be just off and we may accept pretty large positive ones.
3428 if (M == CodeModel::Kernel && Offset > 0)
3434 /// isCalleePop - Determines whether the callee is required to pop its
3435 /// own arguments. Callee pop is necessary to support tail calls.
3436 bool X86::isCalleePop(CallingConv::ID CallingConv,
3437 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3441 switch (CallingConv) {
3444 case CallingConv::X86_StdCall:
3446 case CallingConv::X86_FastCall:
3448 case CallingConv::X86_ThisCall:
3450 case CallingConv::Fast:
3452 case CallingConv::GHC:
3454 case CallingConv::HiPE:
3459 /// \brief Return true if the condition is an unsigned comparison operation.
3460 static bool isX86CCUnsigned(unsigned X86CC) {
3462 default: llvm_unreachable("Invalid integer condition!");
3463 case X86::COND_E: return true;
3464 case X86::COND_G: return false;
3465 case X86::COND_GE: return false;
3466 case X86::COND_L: return false;
3467 case X86::COND_LE: return false;
3468 case X86::COND_NE: return true;
3469 case X86::COND_B: return true;
3470 case X86::COND_A: return true;
3471 case X86::COND_BE: return true;
3472 case X86::COND_AE: return true;
3474 llvm_unreachable("covered switch fell through?!");
3477 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3478 /// specific condition code, returning the condition code and the LHS/RHS of the
3479 /// comparison to make.
3480 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3481 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3483 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3484 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3485 // X > -1 -> X == 0, jump !sign.
3486 RHS = DAG.getConstant(0, RHS.getValueType());
3487 return X86::COND_NS;
3489 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3490 // X < 0 -> X == 0, jump on sign.
3493 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3495 RHS = DAG.getConstant(0, RHS.getValueType());
3496 return X86::COND_LE;
3500 switch (SetCCOpcode) {
3501 default: llvm_unreachable("Invalid integer condition!");
3502 case ISD::SETEQ: return X86::COND_E;
3503 case ISD::SETGT: return X86::COND_G;
3504 case ISD::SETGE: return X86::COND_GE;
3505 case ISD::SETLT: return X86::COND_L;
3506 case ISD::SETLE: return X86::COND_LE;
3507 case ISD::SETNE: return X86::COND_NE;
3508 case ISD::SETULT: return X86::COND_B;
3509 case ISD::SETUGT: return X86::COND_A;
3510 case ISD::SETULE: return X86::COND_BE;
3511 case ISD::SETUGE: return X86::COND_AE;
3515 // First determine if it is required or is profitable to flip the operands.
3517 // If LHS is a foldable load, but RHS is not, flip the condition.
3518 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3519 !ISD::isNON_EXTLoad(RHS.getNode())) {
3520 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3521 std::swap(LHS, RHS);
3524 switch (SetCCOpcode) {
3530 std::swap(LHS, RHS);
3534 // On a floating point condition, the flags are set as follows:
3536 // 0 | 0 | 0 | X > Y
3537 // 0 | 0 | 1 | X < Y
3538 // 1 | 0 | 0 | X == Y
3539 // 1 | 1 | 1 | unordered
3540 switch (SetCCOpcode) {
3541 default: llvm_unreachable("Condcode should be pre-legalized away");
3543 case ISD::SETEQ: return X86::COND_E;
3544 case ISD::SETOLT: // flipped
3546 case ISD::SETGT: return X86::COND_A;
3547 case ISD::SETOLE: // flipped
3549 case ISD::SETGE: return X86::COND_AE;
3550 case ISD::SETUGT: // flipped
3552 case ISD::SETLT: return X86::COND_B;
3553 case ISD::SETUGE: // flipped
3555 case ISD::SETLE: return X86::COND_BE;
3557 case ISD::SETNE: return X86::COND_NE;
3558 case ISD::SETUO: return X86::COND_P;
3559 case ISD::SETO: return X86::COND_NP;
3561 case ISD::SETUNE: return X86::COND_INVALID;
3565 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3566 /// code. Current x86 isa includes the following FP cmov instructions:
3567 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3568 static bool hasFPCMov(unsigned X86CC) {
3584 /// isFPImmLegal - Returns true if the target can instruction select the
3585 /// specified FP immediate natively. If false, the legalizer will
3586 /// materialize the FP immediate as a load from a constant pool.
3587 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3588 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3589 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3595 /// \brief Returns true if it is beneficial to convert a load of a constant
3596 /// to just the constant itself.
3597 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3599 assert(Ty->isIntegerTy());
3601 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3602 if (BitSize == 0 || BitSize > 64)
3607 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3608 /// the specified range (L, H].
3609 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3610 return (Val < 0) || (Val >= Low && Val < Hi);
3613 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3614 /// specified value.
3615 static bool isUndefOrEqual(int Val, int CmpVal) {
3616 return (Val < 0 || Val == CmpVal);
3619 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3620 /// from position Pos and ending in Pos+Size, falls within the specified
3621 /// sequential range (L, L+Pos]. or is undef.
3622 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3623 unsigned Pos, unsigned Size, int Low) {
3624 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3625 if (!isUndefOrEqual(Mask[i], Low))
3630 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3631 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3632 /// the second operand.
3633 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3634 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3635 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3636 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3637 return (Mask[0] < 2 && Mask[1] < 2);
3641 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3642 /// is suitable for input to PSHUFHW.
3643 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3644 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3647 // Lower quadword copied in order or undef.
3648 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3651 // Upper quadword shuffled.
3652 for (unsigned i = 4; i != 8; ++i)
3653 if (!isUndefOrInRange(Mask[i], 4, 8))
3656 if (VT == MVT::v16i16) {
3657 // Lower quadword copied in order or undef.
3658 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3661 // Upper quadword shuffled.
3662 for (unsigned i = 12; i != 16; ++i)
3663 if (!isUndefOrInRange(Mask[i], 12, 16))
3670 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3671 /// is suitable for input to PSHUFLW.
3672 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3673 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3676 // Upper quadword copied in order.
3677 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3680 // Lower quadword shuffled.
3681 for (unsigned i = 0; i != 4; ++i)
3682 if (!isUndefOrInRange(Mask[i], 0, 4))
3685 if (VT == MVT::v16i16) {
3686 // Upper quadword copied in order.
3687 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3690 // Lower quadword shuffled.
3691 for (unsigned i = 8; i != 12; ++i)
3692 if (!isUndefOrInRange(Mask[i], 8, 12))
3699 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3700 /// is suitable for input to PALIGNR.
3701 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3702 const X86Subtarget *Subtarget) {
3703 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3704 (VT.is256BitVector() && !Subtarget->hasInt256()))
3707 unsigned NumElts = VT.getVectorNumElements();
3708 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3709 unsigned NumLaneElts = NumElts/NumLanes;
3711 // Do not handle 64-bit element shuffles with palignr.
3712 if (NumLaneElts == 2)
3715 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3717 for (i = 0; i != NumLaneElts; ++i) {
3722 // Lane is all undef, go to next lane
3723 if (i == NumLaneElts)
3726 int Start = Mask[i+l];
3728 // Make sure its in this lane in one of the sources
3729 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3730 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3733 // If not lane 0, then we must match lane 0
3734 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3737 // Correct second source to be contiguous with first source
3738 if (Start >= (int)NumElts)
3739 Start -= NumElts - NumLaneElts;
3741 // Make sure we're shifting in the right direction.
3742 if (Start <= (int)(i+l))
3747 // Check the rest of the elements to see if they are consecutive.
3748 for (++i; i != NumLaneElts; ++i) {
3749 int Idx = Mask[i+l];
3751 // Make sure its in this lane
3752 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3753 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3756 // If not lane 0, then we must match lane 0
3757 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3760 if (Idx >= (int)NumElts)
3761 Idx -= NumElts - NumLaneElts;
3763 if (!isUndefOrEqual(Idx, Start+i))
3772 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3773 /// the two vector operands have swapped position.
3774 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3775 unsigned NumElems) {
3776 for (unsigned i = 0; i != NumElems; ++i) {
3780 else if (idx < (int)NumElems)
3781 Mask[i] = idx + NumElems;
3783 Mask[i] = idx - NumElems;
3787 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3788 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3789 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3790 /// reverse of what x86 shuffles want.
3791 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3793 unsigned NumElems = VT.getVectorNumElements();
3794 unsigned NumLanes = VT.getSizeInBits()/128;
3795 unsigned NumLaneElems = NumElems/NumLanes;
3797 if (NumLaneElems != 2 && NumLaneElems != 4)
3800 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3801 bool symetricMaskRequired =
3802 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3804 // VSHUFPSY divides the resulting vector into 4 chunks.
3805 // The sources are also splitted into 4 chunks, and each destination
3806 // chunk must come from a different source chunk.
3808 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3809 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3811 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3812 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3814 // VSHUFPDY divides the resulting vector into 4 chunks.
3815 // The sources are also splitted into 4 chunks, and each destination
3816 // chunk must come from a different source chunk.
3818 // SRC1 => X3 X2 X1 X0
3819 // SRC2 => Y3 Y2 Y1 Y0
3821 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3823 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3824 unsigned HalfLaneElems = NumLaneElems/2;
3825 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3826 for (unsigned i = 0; i != NumLaneElems; ++i) {
3827 int Idx = Mask[i+l];
3828 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3829 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3831 // For VSHUFPSY, the mask of the second half must be the same as the
3832 // first but with the appropriate offsets. This works in the same way as
3833 // VPERMILPS works with masks.
3834 if (!symetricMaskRequired || Idx < 0)
3836 if (MaskVal[i] < 0) {
3837 MaskVal[i] = Idx - l;
3840 if ((signed)(Idx - l) != MaskVal[i])
3848 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3850 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3851 if (!VT.is128BitVector())
3854 unsigned NumElems = VT.getVectorNumElements();
3859 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3860 return isUndefOrEqual(Mask[0], 6) &&
3861 isUndefOrEqual(Mask[1], 7) &&
3862 isUndefOrEqual(Mask[2], 2) &&
3863 isUndefOrEqual(Mask[3], 3);
3866 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3867 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3869 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3870 if (!VT.is128BitVector())
3873 unsigned NumElems = VT.getVectorNumElements();
3878 return isUndefOrEqual(Mask[0], 2) &&
3879 isUndefOrEqual(Mask[1], 3) &&
3880 isUndefOrEqual(Mask[2], 2) &&
3881 isUndefOrEqual(Mask[3], 3);
3884 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3885 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3886 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3887 if (!VT.is128BitVector())
3890 unsigned NumElems = VT.getVectorNumElements();
3892 if (NumElems != 2 && NumElems != 4)
3895 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3896 if (!isUndefOrEqual(Mask[i], i + NumElems))
3899 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3900 if (!isUndefOrEqual(Mask[i], i))
3906 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3907 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3908 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3909 if (!VT.is128BitVector())
3912 unsigned NumElems = VT.getVectorNumElements();
3914 if (NumElems != 2 && NumElems != 4)
3917 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3918 if (!isUndefOrEqual(Mask[i], i))
3921 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3922 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3929 // Some special combinations that can be optimized.
3932 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3933 SelectionDAG &DAG) {
3934 MVT VT = SVOp->getSimpleValueType(0);
3937 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3940 ArrayRef<int> Mask = SVOp->getMask();
3942 // These are the special masks that may be optimized.
3943 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3944 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3945 bool MatchEvenMask = true;
3946 bool MatchOddMask = true;
3947 for (int i=0; i<8; ++i) {
3948 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3949 MatchEvenMask = false;
3950 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3951 MatchOddMask = false;
3954 if (!MatchEvenMask && !MatchOddMask)
3957 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3959 SDValue Op0 = SVOp->getOperand(0);
3960 SDValue Op1 = SVOp->getOperand(1);
3962 if (MatchEvenMask) {
3963 // Shift the second operand right to 32 bits.
3964 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3965 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3967 // Shift the first operand left to 32 bits.
3968 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3969 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3971 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3972 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3975 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3976 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3977 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3978 bool HasInt256, bool V2IsSplat = false) {
3980 assert(VT.getSizeInBits() >= 128 &&
3981 "Unsupported vector type for unpckl");
3983 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3985 unsigned NumOf256BitLanes;
3986 unsigned NumElts = VT.getVectorNumElements();
3987 if (VT.is256BitVector()) {
3988 if (NumElts != 4 && NumElts != 8 &&
3989 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3992 NumOf256BitLanes = 1;
3993 } else if (VT.is512BitVector()) {
3994 assert(VT.getScalarType().getSizeInBits() >= 32 &&
3995 "Unsupported vector type for unpckh");
3997 NumOf256BitLanes = 2;
4000 NumOf256BitLanes = 1;
4003 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4004 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4006 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4007 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4008 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4009 int BitI = Mask[l256*NumEltsInStride+l+i];
4010 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4011 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4013 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4015 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4023 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4024 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4025 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4026 bool HasInt256, bool V2IsSplat = false) {
4027 assert(VT.getSizeInBits() >= 128 &&
4028 "Unsupported vector type for unpckh");
4030 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4032 unsigned NumOf256BitLanes;
4033 unsigned NumElts = VT.getVectorNumElements();
4034 if (VT.is256BitVector()) {
4035 if (NumElts != 4 && NumElts != 8 &&
4036 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4039 NumOf256BitLanes = 1;
4040 } else if (VT.is512BitVector()) {
4041 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4042 "Unsupported vector type for unpckh");
4044 NumOf256BitLanes = 2;
4047 NumOf256BitLanes = 1;
4050 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4051 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4053 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4054 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4055 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4056 int BitI = Mask[l256*NumEltsInStride+l+i];
4057 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4058 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4060 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4062 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4070 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4071 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4073 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4074 unsigned NumElts = VT.getVectorNumElements();
4075 bool Is256BitVec = VT.is256BitVector();
4077 if (VT.is512BitVector())
4079 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4080 "Unsupported vector type for unpckh");
4082 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4083 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4086 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4087 // FIXME: Need a better way to get rid of this, there's no latency difference
4088 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4089 // the former later. We should also remove the "_undef" special mask.
4090 if (NumElts == 4 && Is256BitVec)
4093 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4094 // independently on 128-bit lanes.
4095 unsigned NumLanes = VT.getSizeInBits()/128;
4096 unsigned NumLaneElts = NumElts/NumLanes;
4098 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4099 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4100 int BitI = Mask[l+i];
4101 int BitI1 = Mask[l+i+1];
4103 if (!isUndefOrEqual(BitI, j))
4105 if (!isUndefOrEqual(BitI1, j))
4113 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4114 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4116 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4117 unsigned NumElts = VT.getVectorNumElements();
4119 if (VT.is512BitVector())
4122 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4123 "Unsupported vector type for unpckh");
4125 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4126 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4129 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4130 // independently on 128-bit lanes.
4131 unsigned NumLanes = VT.getSizeInBits()/128;
4132 unsigned NumLaneElts = NumElts/NumLanes;
4134 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4135 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4136 int BitI = Mask[l+i];
4137 int BitI1 = Mask[l+i+1];
4138 if (!isUndefOrEqual(BitI, j))
4140 if (!isUndefOrEqual(BitI1, j))
4147 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4148 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4149 /// MOVSD, and MOVD, i.e. setting the lowest element.
4150 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4151 if (VT.getVectorElementType().getSizeInBits() < 32)
4153 if (!VT.is128BitVector())
4156 unsigned NumElts = VT.getVectorNumElements();
4158 if (!isUndefOrEqual(Mask[0], NumElts))
4161 for (unsigned i = 1; i != NumElts; ++i)
4162 if (!isUndefOrEqual(Mask[i], i))
4168 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4169 /// as permutations between 128-bit chunks or halves. As an example: this
4171 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4172 /// The first half comes from the second half of V1 and the second half from the
4173 /// the second half of V2.
4174 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4175 if (!HasFp256 || !VT.is256BitVector())
4178 // The shuffle result is divided into half A and half B. In total the two
4179 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4180 // B must come from C, D, E or F.
4181 unsigned HalfSize = VT.getVectorNumElements()/2;
4182 bool MatchA = false, MatchB = false;
4184 // Check if A comes from one of C, D, E, F.
4185 for (unsigned Half = 0; Half != 4; ++Half) {
4186 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4192 // Check if B comes from one of C, D, E, F.
4193 for (unsigned Half = 0; Half != 4; ++Half) {
4194 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4200 return MatchA && MatchB;
4203 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4204 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4205 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4206 MVT VT = SVOp->getSimpleValueType(0);
4208 unsigned HalfSize = VT.getVectorNumElements()/2;
4210 unsigned FstHalf = 0, SndHalf = 0;
4211 for (unsigned i = 0; i < HalfSize; ++i) {
4212 if (SVOp->getMaskElt(i) > 0) {
4213 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4217 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4218 if (SVOp->getMaskElt(i) > 0) {
4219 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4224 return (FstHalf | (SndHalf << 4));
4227 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4228 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4229 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4233 unsigned NumElts = VT.getVectorNumElements();
4235 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4236 for (unsigned i = 0; i != NumElts; ++i) {
4239 Imm8 |= Mask[i] << (i*2);
4244 unsigned LaneSize = 4;
4245 SmallVector<int, 4> MaskVal(LaneSize, -1);
4247 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4248 for (unsigned i = 0; i != LaneSize; ++i) {
4249 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4253 if (MaskVal[i] < 0) {
4254 MaskVal[i] = Mask[i+l] - l;
4255 Imm8 |= MaskVal[i] << (i*2);
4258 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4265 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4266 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4267 /// Note that VPERMIL mask matching is different depending whether theunderlying
4268 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4269 /// to the same elements of the low, but to the higher half of the source.
4270 /// In VPERMILPD the two lanes could be shuffled independently of each other
4271 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4272 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4273 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4274 if (VT.getSizeInBits() < 256 || EltSize < 32)
4276 bool symetricMaskRequired = (EltSize == 32);
4277 unsigned NumElts = VT.getVectorNumElements();
4279 unsigned NumLanes = VT.getSizeInBits()/128;
4280 unsigned LaneSize = NumElts/NumLanes;
4281 // 2 or 4 elements in one lane
4283 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4284 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4285 for (unsigned i = 0; i != LaneSize; ++i) {
4286 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4288 if (symetricMaskRequired) {
4289 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4290 ExpectedMaskVal[i] = Mask[i+l] - l;
4293 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4301 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4302 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4303 /// element of vector 2 and the other elements to come from vector 1 in order.
4304 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4305 bool V2IsSplat = false, bool V2IsUndef = false) {
4306 if (!VT.is128BitVector())
4309 unsigned NumOps = VT.getVectorNumElements();
4310 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4313 if (!isUndefOrEqual(Mask[0], 0))
4316 for (unsigned i = 1; i != NumOps; ++i)
4317 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4318 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4319 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4325 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4326 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4327 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4328 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4329 const X86Subtarget *Subtarget) {
4330 if (!Subtarget->hasSSE3())
4333 unsigned NumElems = VT.getVectorNumElements();
4335 if ((VT.is128BitVector() && NumElems != 4) ||
4336 (VT.is256BitVector() && NumElems != 8) ||
4337 (VT.is512BitVector() && NumElems != 16))
4340 // "i+1" is the value the indexed mask element must have
4341 for (unsigned i = 0; i != NumElems; i += 2)
4342 if (!isUndefOrEqual(Mask[i], i+1) ||
4343 !isUndefOrEqual(Mask[i+1], i+1))
4349 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4350 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4351 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4352 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4353 const X86Subtarget *Subtarget) {
4354 if (!Subtarget->hasSSE3())
4357 unsigned NumElems = VT.getVectorNumElements();
4359 if ((VT.is128BitVector() && NumElems != 4) ||
4360 (VT.is256BitVector() && NumElems != 8) ||
4361 (VT.is512BitVector() && NumElems != 16))
4364 // "i" is the value the indexed mask element must have
4365 for (unsigned i = 0; i != NumElems; i += 2)
4366 if (!isUndefOrEqual(Mask[i], i) ||
4367 !isUndefOrEqual(Mask[i+1], i))
4373 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4374 /// specifies a shuffle of elements that is suitable for input to 256-bit
4375 /// version of MOVDDUP.
4376 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4377 if (!HasFp256 || !VT.is256BitVector())
4380 unsigned NumElts = VT.getVectorNumElements();
4384 for (unsigned i = 0; i != NumElts/2; ++i)
4385 if (!isUndefOrEqual(Mask[i], 0))
4387 for (unsigned i = NumElts/2; i != NumElts; ++i)
4388 if (!isUndefOrEqual(Mask[i], NumElts/2))
4393 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4394 /// specifies a shuffle of elements that is suitable for input to 128-bit
4395 /// version of MOVDDUP.
4396 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4397 if (!VT.is128BitVector())
4400 unsigned e = VT.getVectorNumElements() / 2;
4401 for (unsigned i = 0; i != e; ++i)
4402 if (!isUndefOrEqual(Mask[i], i))
4404 for (unsigned i = 0; i != e; ++i)
4405 if (!isUndefOrEqual(Mask[e+i], i))
4410 /// isVEXTRACTIndex - Return true if the specified
4411 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4412 /// suitable for instruction that extract 128 or 256 bit vectors
4413 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4414 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4415 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4418 // The index should be aligned on a vecWidth-bit boundary.
4420 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4422 MVT VT = N->getSimpleValueType(0);
4423 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4424 bool Result = (Index * ElSize) % vecWidth == 0;
4429 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4430 /// operand specifies a subvector insert that is suitable for input to
4431 /// insertion of 128 or 256-bit subvectors
4432 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4433 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4434 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4436 // The index should be aligned on a vecWidth-bit boundary.
4438 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4440 MVT VT = N->getSimpleValueType(0);
4441 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4442 bool Result = (Index * ElSize) % vecWidth == 0;
4447 bool X86::isVINSERT128Index(SDNode *N) {
4448 return isVINSERTIndex(N, 128);
4451 bool X86::isVINSERT256Index(SDNode *N) {
4452 return isVINSERTIndex(N, 256);
4455 bool X86::isVEXTRACT128Index(SDNode *N) {
4456 return isVEXTRACTIndex(N, 128);
4459 bool X86::isVEXTRACT256Index(SDNode *N) {
4460 return isVEXTRACTIndex(N, 256);
4463 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4464 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4465 /// Handles 128-bit and 256-bit.
4466 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4467 MVT VT = N->getSimpleValueType(0);
4469 assert((VT.getSizeInBits() >= 128) &&
4470 "Unsupported vector type for PSHUF/SHUFP");
4472 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4473 // independently on 128-bit lanes.
4474 unsigned NumElts = VT.getVectorNumElements();
4475 unsigned NumLanes = VT.getSizeInBits()/128;
4476 unsigned NumLaneElts = NumElts/NumLanes;
4478 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4479 "Only supports 2, 4 or 8 elements per lane");
4481 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4483 for (unsigned i = 0; i != NumElts; ++i) {
4484 int Elt = N->getMaskElt(i);
4485 if (Elt < 0) continue;
4486 Elt &= NumLaneElts - 1;
4487 unsigned ShAmt = (i << Shift) % 8;
4488 Mask |= Elt << ShAmt;
4494 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4495 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4496 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4497 MVT VT = N->getSimpleValueType(0);
4499 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4500 "Unsupported vector type for PSHUFHW");
4502 unsigned NumElts = VT.getVectorNumElements();
4505 for (unsigned l = 0; l != NumElts; l += 8) {
4506 // 8 nodes per lane, but we only care about the last 4.
4507 for (unsigned i = 0; i < 4; ++i) {
4508 int Elt = N->getMaskElt(l+i+4);
4509 if (Elt < 0) continue;
4510 Elt &= 0x3; // only 2-bits.
4511 Mask |= Elt << (i * 2);
4518 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4519 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4520 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4521 MVT VT = N->getSimpleValueType(0);
4523 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4524 "Unsupported vector type for PSHUFHW");
4526 unsigned NumElts = VT.getVectorNumElements();
4529 for (unsigned l = 0; l != NumElts; l += 8) {
4530 // 8 nodes per lane, but we only care about the first 4.
4531 for (unsigned i = 0; i < 4; ++i) {
4532 int Elt = N->getMaskElt(l+i);
4533 if (Elt < 0) continue;
4534 Elt &= 0x3; // only 2-bits
4535 Mask |= Elt << (i * 2);
4542 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4543 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4544 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4545 MVT VT = SVOp->getSimpleValueType(0);
4546 unsigned EltSize = VT.is512BitVector() ? 1 :
4547 VT.getVectorElementType().getSizeInBits() >> 3;
4549 unsigned NumElts = VT.getVectorNumElements();
4550 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4551 unsigned NumLaneElts = NumElts/NumLanes;
4555 for (i = 0; i != NumElts; ++i) {
4556 Val = SVOp->getMaskElt(i);
4560 if (Val >= (int)NumElts)
4561 Val -= NumElts - NumLaneElts;
4563 assert(Val - i > 0 && "PALIGNR imm should be positive");
4564 return (Val - i) * EltSize;
4567 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4568 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4569 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4570 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4573 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4575 MVT VecVT = N->getOperand(0).getSimpleValueType();
4576 MVT ElVT = VecVT.getVectorElementType();
4578 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4579 return Index / NumElemsPerChunk;
4582 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4583 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4584 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4585 llvm_unreachable("Illegal insert subvector for VINSERT");
4588 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4590 MVT VecVT = N->getSimpleValueType(0);
4591 MVT ElVT = VecVT.getVectorElementType();
4593 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4594 return Index / NumElemsPerChunk;
4597 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4598 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4599 /// and VINSERTI128 instructions.
4600 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4601 return getExtractVEXTRACTImmediate(N, 128);
4604 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4605 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4606 /// and VINSERTI64x4 instructions.
4607 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4608 return getExtractVEXTRACTImmediate(N, 256);
4611 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4612 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4613 /// and VINSERTI128 instructions.
4614 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4615 return getInsertVINSERTImmediate(N, 128);
4618 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4619 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4620 /// and VINSERTI64x4 instructions.
4621 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4622 return getInsertVINSERTImmediate(N, 256);
4625 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4627 bool X86::isZeroNode(SDValue Elt) {
4628 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4629 return CN->isNullValue();
4630 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4631 return CFP->getValueAPF().isPosZero();
4635 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4636 /// their permute mask.
4637 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4638 SelectionDAG &DAG) {
4639 MVT VT = SVOp->getSimpleValueType(0);
4640 unsigned NumElems = VT.getVectorNumElements();
4641 SmallVector<int, 8> MaskVec;
4643 for (unsigned i = 0; i != NumElems; ++i) {
4644 int Idx = SVOp->getMaskElt(i);
4646 if (Idx < (int)NumElems)
4651 MaskVec.push_back(Idx);
4653 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4654 SVOp->getOperand(0), &MaskVec[0]);
4657 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4658 /// match movhlps. The lower half elements should come from upper half of
4659 /// V1 (and in order), and the upper half elements should come from the upper
4660 /// half of V2 (and in order).
4661 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4662 if (!VT.is128BitVector())
4664 if (VT.getVectorNumElements() != 4)
4666 for (unsigned i = 0, e = 2; i != e; ++i)
4667 if (!isUndefOrEqual(Mask[i], i+2))
4669 for (unsigned i = 2; i != 4; ++i)
4670 if (!isUndefOrEqual(Mask[i], i+4))
4675 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4676 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4678 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4679 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4681 N = N->getOperand(0).getNode();
4682 if (!ISD::isNON_EXTLoad(N))
4685 *LD = cast<LoadSDNode>(N);
4689 // Test whether the given value is a vector value which will be legalized
4691 static bool WillBeConstantPoolLoad(SDNode *N) {
4692 if (N->getOpcode() != ISD::BUILD_VECTOR)
4695 // Check for any non-constant elements.
4696 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4697 switch (N->getOperand(i).getNode()->getOpcode()) {
4699 case ISD::ConstantFP:
4706 // Vectors of all-zeros and all-ones are materialized with special
4707 // instructions rather than being loaded.
4708 return !ISD::isBuildVectorAllZeros(N) &&
4709 !ISD::isBuildVectorAllOnes(N);
4712 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4713 /// match movlp{s|d}. The lower half elements should come from lower half of
4714 /// V1 (and in order), and the upper half elements should come from the upper
4715 /// half of V2 (and in order). And since V1 will become the source of the
4716 /// MOVLP, it must be either a vector load or a scalar load to vector.
4717 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4718 ArrayRef<int> Mask, MVT VT) {
4719 if (!VT.is128BitVector())
4722 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4724 // Is V2 is a vector load, don't do this transformation. We will try to use
4725 // load folding shufps op.
4726 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4729 unsigned NumElems = VT.getVectorNumElements();
4731 if (NumElems != 2 && NumElems != 4)
4733 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4734 if (!isUndefOrEqual(Mask[i], i))
4736 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4737 if (!isUndefOrEqual(Mask[i], i+NumElems))
4742 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4744 static bool isSplatVector(SDNode *N) {
4745 if (N->getOpcode() != ISD::BUILD_VECTOR)
4748 SDValue SplatValue = N->getOperand(0);
4749 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4750 if (N->getOperand(i) != SplatValue)
4755 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4756 /// to an zero vector.
4757 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4758 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4759 SDValue V1 = N->getOperand(0);
4760 SDValue V2 = N->getOperand(1);
4761 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4762 for (unsigned i = 0; i != NumElems; ++i) {
4763 int Idx = N->getMaskElt(i);
4764 if (Idx >= (int)NumElems) {
4765 unsigned Opc = V2.getOpcode();
4766 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4768 if (Opc != ISD::BUILD_VECTOR ||
4769 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4771 } else if (Idx >= 0) {
4772 unsigned Opc = V1.getOpcode();
4773 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4775 if (Opc != ISD::BUILD_VECTOR ||
4776 !X86::isZeroNode(V1.getOperand(Idx)))
4783 /// getZeroVector - Returns a vector of specified type with all zero elements.
4785 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4786 SelectionDAG &DAG, SDLoc dl) {
4787 assert(VT.isVector() && "Expected a vector type");
4789 // Always build SSE zero vectors as <4 x i32> bitcasted
4790 // to their dest type. This ensures they get CSE'd.
4792 if (VT.is128BitVector()) { // SSE
4793 if (Subtarget->hasSSE2()) { // SSE2
4794 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4795 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4797 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4798 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4800 } else if (VT.is256BitVector()) { // AVX
4801 if (Subtarget->hasInt256()) { // AVX2
4802 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4803 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4804 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4805 array_lengthof(Ops));
4807 // 256-bit logic and arithmetic instructions in AVX are all
4808 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4809 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4810 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4811 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4812 array_lengthof(Ops));
4814 } else if (VT.is512BitVector()) { // AVX-512
4815 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4816 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4817 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4818 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4819 } else if (VT.getScalarType() == MVT::i1) {
4820 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4821 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4822 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4823 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4824 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4825 Ops, VT.getVectorNumElements());
4827 llvm_unreachable("Unexpected vector type");
4829 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4832 /// getOnesVector - Returns a vector of specified type with all bits set.
4833 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4834 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4835 /// Then bitcast to their original type, ensuring they get CSE'd.
4836 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4838 assert(VT.isVector() && "Expected a vector type");
4840 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4842 if (VT.is256BitVector()) {
4843 if (HasInt256) { // AVX2
4844 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4845 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4846 array_lengthof(Ops));
4848 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4849 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4851 } else if (VT.is128BitVector()) {
4852 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4854 llvm_unreachable("Unexpected vector type");
4856 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4859 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4860 /// that point to V2 points to its first element.
4861 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4862 for (unsigned i = 0; i != NumElems; ++i) {
4863 if (Mask[i] > (int)NumElems) {
4869 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4870 /// operation of specified width.
4871 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4873 unsigned NumElems = VT.getVectorNumElements();
4874 SmallVector<int, 8> Mask;
4875 Mask.push_back(NumElems);
4876 for (unsigned i = 1; i != NumElems; ++i)
4878 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4881 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4882 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4884 unsigned NumElems = VT.getVectorNumElements();
4885 SmallVector<int, 8> Mask;
4886 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4888 Mask.push_back(i + NumElems);
4890 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4893 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4894 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4896 unsigned NumElems = VT.getVectorNumElements();
4897 SmallVector<int, 8> Mask;
4898 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4899 Mask.push_back(i + Half);
4900 Mask.push_back(i + NumElems + Half);
4902 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4905 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4906 // a generic shuffle instruction because the target has no such instructions.
4907 // Generate shuffles which repeat i16 and i8 several times until they can be
4908 // represented by v4f32 and then be manipulated by target suported shuffles.
4909 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4910 MVT VT = V.getSimpleValueType();
4911 int NumElems = VT.getVectorNumElements();
4914 while (NumElems > 4) {
4915 if (EltNo < NumElems/2) {
4916 V = getUnpackl(DAG, dl, VT, V, V);
4918 V = getUnpackh(DAG, dl, VT, V, V);
4919 EltNo -= NumElems/2;
4926 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4927 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4928 MVT VT = V.getSimpleValueType();
4931 if (VT.is128BitVector()) {
4932 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4933 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4934 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4936 } else if (VT.is256BitVector()) {
4937 // To use VPERMILPS to splat scalars, the second half of indicies must
4938 // refer to the higher part, which is a duplication of the lower one,
4939 // because VPERMILPS can only handle in-lane permutations.
4940 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4941 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4943 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4944 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4947 llvm_unreachable("Vector size not supported");
4949 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4952 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4953 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4954 MVT SrcVT = SV->getSimpleValueType(0);
4955 SDValue V1 = SV->getOperand(0);
4958 int EltNo = SV->getSplatIndex();
4959 int NumElems = SrcVT.getVectorNumElements();
4960 bool Is256BitVec = SrcVT.is256BitVector();
4962 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4963 "Unknown how to promote splat for type");
4965 // Extract the 128-bit part containing the splat element and update
4966 // the splat element index when it refers to the higher register.
4968 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4969 if (EltNo >= NumElems/2)
4970 EltNo -= NumElems/2;
4973 // All i16 and i8 vector types can't be used directly by a generic shuffle
4974 // instruction because the target has no such instruction. Generate shuffles
4975 // which repeat i16 and i8 several times until they fit in i32, and then can
4976 // be manipulated by target suported shuffles.
4977 MVT EltVT = SrcVT.getVectorElementType();
4978 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4979 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4981 // Recreate the 256-bit vector and place the same 128-bit vector
4982 // into the low and high part. This is necessary because we want
4983 // to use VPERM* to shuffle the vectors
4985 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4988 return getLegalSplat(DAG, V1, EltNo);
4991 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4992 /// vector of zero or undef vector. This produces a shuffle where the low
4993 /// element of V2 is swizzled into the zero/undef vector, landing at element
4994 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4995 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4997 const X86Subtarget *Subtarget,
4998 SelectionDAG &DAG) {
4999 MVT VT = V2.getSimpleValueType();
5001 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5002 unsigned NumElems = VT.getVectorNumElements();
5003 SmallVector<int, 16> MaskVec;
5004 for (unsigned i = 0; i != NumElems; ++i)
5005 // If this is the insertion idx, put the low elt of V2 here.
5006 MaskVec.push_back(i == Idx ? NumElems : i);
5007 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5010 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5011 /// target specific opcode. Returns true if the Mask could be calculated.
5012 /// Sets IsUnary to true if only uses one source.
5013 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5014 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5015 unsigned NumElems = VT.getVectorNumElements();
5019 switch(N->getOpcode()) {
5021 ImmN = N->getOperand(N->getNumOperands()-1);
5022 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5024 case X86ISD::UNPCKH:
5025 DecodeUNPCKHMask(VT, Mask);
5027 case X86ISD::UNPCKL:
5028 DecodeUNPCKLMask(VT, Mask);
5030 case X86ISD::MOVHLPS:
5031 DecodeMOVHLPSMask(NumElems, Mask);
5033 case X86ISD::MOVLHPS:
5034 DecodeMOVLHPSMask(NumElems, Mask);
5036 case X86ISD::PALIGNR:
5037 ImmN = N->getOperand(N->getNumOperands()-1);
5038 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5040 case X86ISD::PSHUFD:
5041 case X86ISD::VPERMILP:
5042 ImmN = N->getOperand(N->getNumOperands()-1);
5043 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5046 case X86ISD::PSHUFHW:
5047 ImmN = N->getOperand(N->getNumOperands()-1);
5048 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5051 case X86ISD::PSHUFLW:
5052 ImmN = N->getOperand(N->getNumOperands()-1);
5053 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5056 case X86ISD::VPERMI:
5057 ImmN = N->getOperand(N->getNumOperands()-1);
5058 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5062 case X86ISD::MOVSD: {
5063 // The index 0 always comes from the first element of the second source,
5064 // this is why MOVSS and MOVSD are used in the first place. The other
5065 // elements come from the other positions of the first source vector
5066 Mask.push_back(NumElems);
5067 for (unsigned i = 1; i != NumElems; ++i) {
5072 case X86ISD::VPERM2X128:
5073 ImmN = N->getOperand(N->getNumOperands()-1);
5074 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5075 if (Mask.empty()) return false;
5077 case X86ISD::MOVDDUP:
5078 case X86ISD::MOVLHPD:
5079 case X86ISD::MOVLPD:
5080 case X86ISD::MOVLPS:
5081 case X86ISD::MOVSHDUP:
5082 case X86ISD::MOVSLDUP:
5083 // Not yet implemented
5085 default: llvm_unreachable("unknown target shuffle node");
5091 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5092 /// element of the result of the vector shuffle.
5093 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5096 return SDValue(); // Limit search depth.
5098 SDValue V = SDValue(N, 0);
5099 EVT VT = V.getValueType();
5100 unsigned Opcode = V.getOpcode();
5102 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5103 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5104 int Elt = SV->getMaskElt(Index);
5107 return DAG.getUNDEF(VT.getVectorElementType());
5109 unsigned NumElems = VT.getVectorNumElements();
5110 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5111 : SV->getOperand(1);
5112 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5115 // Recurse into target specific vector shuffles to find scalars.
5116 if (isTargetShuffle(Opcode)) {
5117 MVT ShufVT = V.getSimpleValueType();
5118 unsigned NumElems = ShufVT.getVectorNumElements();
5119 SmallVector<int, 16> ShuffleMask;
5122 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5125 int Elt = ShuffleMask[Index];
5127 return DAG.getUNDEF(ShufVT.getVectorElementType());
5129 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5131 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5135 // Actual nodes that may contain scalar elements
5136 if (Opcode == ISD::BITCAST) {
5137 V = V.getOperand(0);
5138 EVT SrcVT = V.getValueType();
5139 unsigned NumElems = VT.getVectorNumElements();
5141 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5145 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5146 return (Index == 0) ? V.getOperand(0)
5147 : DAG.getUNDEF(VT.getVectorElementType());
5149 if (V.getOpcode() == ISD::BUILD_VECTOR)
5150 return V.getOperand(Index);
5155 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5156 /// shuffle operation which come from a consecutively from a zero. The
5157 /// search can start in two different directions, from left or right.
5158 /// We count undefs as zeros until PreferredNum is reached.
5159 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5160 unsigned NumElems, bool ZerosFromLeft,
5162 unsigned PreferredNum = -1U) {
5163 unsigned NumZeros = 0;
5164 for (unsigned i = 0; i != NumElems; ++i) {
5165 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5166 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5170 if (X86::isZeroNode(Elt))
5172 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5173 NumZeros = std::min(NumZeros + 1, PreferredNum);
5181 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5182 /// correspond consecutively to elements from one of the vector operands,
5183 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5185 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5186 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5187 unsigned NumElems, unsigned &OpNum) {
5188 bool SeenV1 = false;
5189 bool SeenV2 = false;
5191 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5192 int Idx = SVOp->getMaskElt(i);
5193 // Ignore undef indicies
5197 if (Idx < (int)NumElems)
5202 // Only accept consecutive elements from the same vector
5203 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5207 OpNum = SeenV1 ? 0 : 1;
5211 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5212 /// logical left shift of a vector.
5213 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5214 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5216 SVOp->getSimpleValueType(0).getVectorNumElements();
5217 unsigned NumZeros = getNumOfConsecutiveZeros(
5218 SVOp, NumElems, false /* check zeros from right */, DAG,
5219 SVOp->getMaskElt(0));
5225 // Considering the elements in the mask that are not consecutive zeros,
5226 // check if they consecutively come from only one of the source vectors.
5228 // V1 = {X, A, B, C} 0
5230 // vector_shuffle V1, V2 <1, 2, 3, X>
5232 if (!isShuffleMaskConsecutive(SVOp,
5233 0, // Mask Start Index
5234 NumElems-NumZeros, // Mask End Index(exclusive)
5235 NumZeros, // Where to start looking in the src vector
5236 NumElems, // Number of elements in vector
5237 OpSrc)) // Which source operand ?
5242 ShVal = SVOp->getOperand(OpSrc);
5246 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5247 /// logical left shift of a vector.
5248 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5249 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5251 SVOp->getSimpleValueType(0).getVectorNumElements();
5252 unsigned NumZeros = getNumOfConsecutiveZeros(
5253 SVOp, NumElems, true /* check zeros from left */, DAG,
5254 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5260 // Considering the elements in the mask that are not consecutive zeros,
5261 // check if they consecutively come from only one of the source vectors.
5263 // 0 { A, B, X, X } = V2
5265 // vector_shuffle V1, V2 <X, X, 4, 5>
5267 if (!isShuffleMaskConsecutive(SVOp,
5268 NumZeros, // Mask Start Index
5269 NumElems, // Mask End Index(exclusive)
5270 0, // Where to start looking in the src vector
5271 NumElems, // Number of elements in vector
5272 OpSrc)) // Which source operand ?
5277 ShVal = SVOp->getOperand(OpSrc);
5281 /// isVectorShift - Returns true if the shuffle can be implemented as a
5282 /// logical left or right shift of a vector.
5283 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5284 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5285 // Although the logic below support any bitwidth size, there are no
5286 // shift instructions which handle more than 128-bit vectors.
5287 if (!SVOp->getSimpleValueType(0).is128BitVector())
5290 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5291 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5297 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5299 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5300 unsigned NumNonZero, unsigned NumZero,
5302 const X86Subtarget* Subtarget,
5303 const TargetLowering &TLI) {
5310 for (unsigned i = 0; i < 16; ++i) {
5311 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5312 if (ThisIsNonZero && First) {
5314 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5316 V = DAG.getUNDEF(MVT::v8i16);
5321 SDValue ThisElt(0, 0), LastElt(0, 0);
5322 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5323 if (LastIsNonZero) {
5324 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5325 MVT::i16, Op.getOperand(i-1));
5327 if (ThisIsNonZero) {
5328 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5329 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5330 ThisElt, DAG.getConstant(8, MVT::i8));
5332 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5336 if (ThisElt.getNode())
5337 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5338 DAG.getIntPtrConstant(i/2));
5342 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5345 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5347 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5348 unsigned NumNonZero, unsigned NumZero,
5350 const X86Subtarget* Subtarget,
5351 const TargetLowering &TLI) {
5358 for (unsigned i = 0; i < 8; ++i) {
5359 bool isNonZero = (NonZeros & (1 << i)) != 0;
5363 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5365 V = DAG.getUNDEF(MVT::v8i16);
5368 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5369 MVT::v8i16, V, Op.getOperand(i),
5370 DAG.getIntPtrConstant(i));
5377 /// getVShift - Return a vector logical shift node.
5379 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5380 unsigned NumBits, SelectionDAG &DAG,
5381 const TargetLowering &TLI, SDLoc dl) {
5382 assert(VT.is128BitVector() && "Unknown type for VShift");
5383 EVT ShVT = MVT::v2i64;
5384 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5385 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5386 return DAG.getNode(ISD::BITCAST, dl, VT,
5387 DAG.getNode(Opc, dl, ShVT, SrcOp,
5388 DAG.getConstant(NumBits,
5389 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5393 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5395 // Check if the scalar load can be widened into a vector load. And if
5396 // the address is "base + cst" see if the cst can be "absorbed" into
5397 // the shuffle mask.
5398 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5399 SDValue Ptr = LD->getBasePtr();
5400 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5402 EVT PVT = LD->getValueType(0);
5403 if (PVT != MVT::i32 && PVT != MVT::f32)
5408 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5409 FI = FINode->getIndex();
5411 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5412 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5413 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5414 Offset = Ptr.getConstantOperandVal(1);
5415 Ptr = Ptr.getOperand(0);
5420 // FIXME: 256-bit vector instructions don't require a strict alignment,
5421 // improve this code to support it better.
5422 unsigned RequiredAlign = VT.getSizeInBits()/8;
5423 SDValue Chain = LD->getChain();
5424 // Make sure the stack object alignment is at least 16 or 32.
5425 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5426 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5427 if (MFI->isFixedObjectIndex(FI)) {
5428 // Can't change the alignment. FIXME: It's possible to compute
5429 // the exact stack offset and reference FI + adjust offset instead.
5430 // If someone *really* cares about this. That's the way to implement it.
5433 MFI->setObjectAlignment(FI, RequiredAlign);
5437 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5438 // Ptr + (Offset & ~15).
5441 if ((Offset % RequiredAlign) & 3)
5443 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5445 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5446 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5448 int EltNo = (Offset - StartOffset) >> 2;
5449 unsigned NumElems = VT.getVectorNumElements();
5451 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5452 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5453 LD->getPointerInfo().getWithOffset(StartOffset),
5454 false, false, false, 0);
5456 SmallVector<int, 8> Mask;
5457 for (unsigned i = 0; i != NumElems; ++i)
5458 Mask.push_back(EltNo);
5460 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5466 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5467 /// vector of type 'VT', see if the elements can be replaced by a single large
5468 /// load which has the same value as a build_vector whose operands are 'elts'.
5470 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5472 /// FIXME: we'd also like to handle the case where the last elements are zero
5473 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5474 /// There's even a handy isZeroNode for that purpose.
5475 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5476 SDLoc &DL, SelectionDAG &DAG,
5477 bool isAfterLegalize) {
5478 EVT EltVT = VT.getVectorElementType();
5479 unsigned NumElems = Elts.size();
5481 LoadSDNode *LDBase = NULL;
5482 unsigned LastLoadedElt = -1U;
5484 // For each element in the initializer, see if we've found a load or an undef.
5485 // If we don't find an initial load element, or later load elements are
5486 // non-consecutive, bail out.
5487 for (unsigned i = 0; i < NumElems; ++i) {
5488 SDValue Elt = Elts[i];
5490 if (!Elt.getNode() ||
5491 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5494 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5496 LDBase = cast<LoadSDNode>(Elt.getNode());
5500 if (Elt.getOpcode() == ISD::UNDEF)
5503 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5504 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5509 // If we have found an entire vector of loads and undefs, then return a large
5510 // load of the entire vector width starting at the base pointer. If we found
5511 // consecutive loads for the low half, generate a vzext_load node.
5512 if (LastLoadedElt == NumElems - 1) {
5514 if (isAfterLegalize &&
5515 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5518 SDValue NewLd = SDValue();
5520 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5521 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5522 LDBase->getPointerInfo(),
5523 LDBase->isVolatile(), LDBase->isNonTemporal(),
5524 LDBase->isInvariant(), 0);
5525 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5526 LDBase->getPointerInfo(),
5527 LDBase->isVolatile(), LDBase->isNonTemporal(),
5528 LDBase->isInvariant(), LDBase->getAlignment());
5530 if (LDBase->hasAnyUseOfValue(1)) {
5531 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5533 SDValue(NewLd.getNode(), 1));
5534 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5535 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5536 SDValue(NewLd.getNode(), 1));
5541 if (NumElems == 4 && LastLoadedElt == 1 &&
5542 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5543 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5544 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5546 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5547 array_lengthof(Ops), MVT::i64,
5548 LDBase->getPointerInfo(),
5549 LDBase->getAlignment(),
5550 false/*isVolatile*/, true/*ReadMem*/,
5553 // Make sure the newly-created LOAD is in the same position as LDBase in
5554 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5555 // update uses of LDBase's output chain to use the TokenFactor.
5556 if (LDBase->hasAnyUseOfValue(1)) {
5557 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5558 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5559 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5560 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5561 SDValue(ResNode.getNode(), 1));
5564 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5569 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5570 /// to generate a splat value for the following cases:
5571 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5572 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5573 /// a scalar load, or a constant.
5574 /// The VBROADCAST node is returned when a pattern is found,
5575 /// or SDValue() otherwise.
5576 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5577 SelectionDAG &DAG) {
5578 if (!Subtarget->hasFp256())
5581 MVT VT = Op.getSimpleValueType();
5584 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5585 "Unsupported vector type for broadcast.");
5590 switch (Op.getOpcode()) {
5592 // Unknown pattern found.
5595 case ISD::BUILD_VECTOR: {
5596 // The BUILD_VECTOR node must be a splat.
5597 if (!isSplatVector(Op.getNode()))
5600 Ld = Op.getOperand(0);
5601 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5602 Ld.getOpcode() == ISD::ConstantFP);
5604 // The suspected load node has several users. Make sure that all
5605 // of its users are from the BUILD_VECTOR node.
5606 // Constants may have multiple users.
5607 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5612 case ISD::VECTOR_SHUFFLE: {
5613 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5615 // Shuffles must have a splat mask where the first element is
5617 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5620 SDValue Sc = Op.getOperand(0);
5621 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5622 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5624 if (!Subtarget->hasInt256())
5627 // Use the register form of the broadcast instruction available on AVX2.
5628 if (VT.getSizeInBits() >= 256)
5629 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5630 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5633 Ld = Sc.getOperand(0);
5634 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5635 Ld.getOpcode() == ISD::ConstantFP);
5637 // The scalar_to_vector node and the suspected
5638 // load node must have exactly one user.
5639 // Constants may have multiple users.
5641 // AVX-512 has register version of the broadcast
5642 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5643 Ld.getValueType().getSizeInBits() >= 32;
5644 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5651 bool IsGE256 = (VT.getSizeInBits() >= 256);
5653 // Handle the broadcasting a single constant scalar from the constant pool
5654 // into a vector. On Sandybridge it is still better to load a constant vector
5655 // from the constant pool and not to broadcast it from a scalar.
5656 if (ConstSplatVal && Subtarget->hasInt256()) {
5657 EVT CVT = Ld.getValueType();
5658 assert(!CVT.isVector() && "Must not broadcast a vector type");
5659 unsigned ScalarSize = CVT.getSizeInBits();
5661 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5662 const Constant *C = 0;
5663 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5664 C = CI->getConstantIntValue();
5665 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5666 C = CF->getConstantFPValue();
5668 assert(C && "Invalid constant type");
5670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5671 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5672 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5673 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5674 MachinePointerInfo::getConstantPool(),
5675 false, false, false, Alignment);
5677 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5681 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5682 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5684 // Handle AVX2 in-register broadcasts.
5685 if (!IsLoad && Subtarget->hasInt256() &&
5686 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5687 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5689 // The scalar source must be a normal load.
5693 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5694 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5696 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5697 // double since there is no vbroadcastsd xmm
5698 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5699 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5700 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5703 // Unsupported broadcast.
5707 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5708 /// underlying vector and index.
5710 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5712 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5714 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5715 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5718 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5720 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5722 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5723 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5726 // In this case the vector is the extract_subvector expression and the index
5727 // is 2, as specified by the shuffle.
5728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5729 SDValue ShuffleVec = SVOp->getOperand(0);
5730 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5731 assert(ShuffleVecVT.getVectorElementType() ==
5732 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5734 int ShuffleIdx = SVOp->getMaskElt(Idx);
5735 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5736 ExtractedFromVec = ShuffleVec;
5742 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5743 MVT VT = Op.getSimpleValueType();
5745 // Skip if insert_vec_elt is not supported.
5746 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5747 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5751 unsigned NumElems = Op.getNumOperands();
5755 SmallVector<unsigned, 4> InsertIndices;
5756 SmallVector<int, 8> Mask(NumElems, -1);
5758 for (unsigned i = 0; i != NumElems; ++i) {
5759 unsigned Opc = Op.getOperand(i).getOpcode();
5761 if (Opc == ISD::UNDEF)
5764 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5765 // Quit if more than 1 elements need inserting.
5766 if (InsertIndices.size() > 1)
5769 InsertIndices.push_back(i);
5773 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5774 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5775 // Quit if non-constant index.
5776 if (!isa<ConstantSDNode>(ExtIdx))
5778 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5780 // Quit if extracted from vector of different type.
5781 if (ExtractedFromVec.getValueType() != VT)
5784 if (VecIn1.getNode() == 0)
5785 VecIn1 = ExtractedFromVec;
5786 else if (VecIn1 != ExtractedFromVec) {
5787 if (VecIn2.getNode() == 0)
5788 VecIn2 = ExtractedFromVec;
5789 else if (VecIn2 != ExtractedFromVec)
5790 // Quit if more than 2 vectors to shuffle
5794 if (ExtractedFromVec == VecIn1)
5796 else if (ExtractedFromVec == VecIn2)
5797 Mask[i] = Idx + NumElems;
5800 if (VecIn1.getNode() == 0)
5803 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5804 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5805 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5806 unsigned Idx = InsertIndices[i];
5807 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5808 DAG.getIntPtrConstant(Idx));
5814 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5816 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5818 MVT VT = Op.getSimpleValueType();
5819 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5820 "Unexpected type in LowerBUILD_VECTORvXi1!");
5823 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5824 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5825 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5826 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5827 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5828 Ops, VT.getVectorNumElements());
5831 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5832 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5833 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5834 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5835 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5836 Ops, VT.getVectorNumElements());
5839 bool AllContants = true;
5840 uint64_t Immediate = 0;
5841 int NonConstIdx = -1;
5842 bool IsSplat = true;
5843 unsigned NumNonConsts = 0;
5844 unsigned NumConsts = 0;
5845 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5846 SDValue In = Op.getOperand(idx);
5847 if (In.getOpcode() == ISD::UNDEF)
5849 if (!isa<ConstantSDNode>(In)) {
5850 AllContants = false;
5856 if (cast<ConstantSDNode>(In)->getZExtValue())
5857 Immediate |= (1ULL << idx);
5859 if (In != Op.getOperand(0))
5864 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5865 DAG.getConstant(Immediate, MVT::i16));
5866 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5867 DAG.getIntPtrConstant(0));
5870 if (NumNonConsts == 1 && NonConstIdx != 0) {
5873 SDValue VecAsImm = DAG.getConstant(Immediate,
5874 MVT::getIntegerVT(VT.getSizeInBits()));
5875 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5878 DstVec = DAG.getUNDEF(VT);
5879 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5880 Op.getOperand(NonConstIdx),
5881 DAG.getIntPtrConstant(NonConstIdx));
5883 if (!IsSplat && (NonConstIdx != 0))
5884 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5885 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5888 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5889 DAG.getConstant(-1, SelectVT),
5890 DAG.getConstant(0, SelectVT));
5892 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5893 DAG.getConstant((Immediate | 1), SelectVT),
5894 DAG.getConstant(Immediate, SelectVT));
5895 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5899 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5902 MVT VT = Op.getSimpleValueType();
5903 MVT ExtVT = VT.getVectorElementType();
5904 unsigned NumElems = Op.getNumOperands();
5906 // Generate vectors for predicate vectors.
5907 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5908 return LowerBUILD_VECTORvXi1(Op, DAG);
5910 // Vectors containing all zeros can be matched by pxor and xorps later
5911 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5912 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5913 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5914 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5917 return getZeroVector(VT, Subtarget, DAG, dl);
5920 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5921 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5922 // vpcmpeqd on 256-bit vectors.
5923 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5924 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5927 if (!VT.is512BitVector())
5928 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5931 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5932 if (Broadcast.getNode())
5935 unsigned EVTBits = ExtVT.getSizeInBits();
5937 unsigned NumZero = 0;
5938 unsigned NumNonZero = 0;
5939 unsigned NonZeros = 0;
5940 bool IsAllConstants = true;
5941 SmallSet<SDValue, 8> Values;
5942 for (unsigned i = 0; i < NumElems; ++i) {
5943 SDValue Elt = Op.getOperand(i);
5944 if (Elt.getOpcode() == ISD::UNDEF)
5947 if (Elt.getOpcode() != ISD::Constant &&
5948 Elt.getOpcode() != ISD::ConstantFP)
5949 IsAllConstants = false;
5950 if (X86::isZeroNode(Elt))
5953 NonZeros |= (1 << i);
5958 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5959 if (NumNonZero == 0)
5960 return DAG.getUNDEF(VT);
5962 // Special case for single non-zero, non-undef, element.
5963 if (NumNonZero == 1) {
5964 unsigned Idx = countTrailingZeros(NonZeros);
5965 SDValue Item = Op.getOperand(Idx);
5967 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5968 // the value are obviously zero, truncate the value to i32 and do the
5969 // insertion that way. Only do this if the value is non-constant or if the
5970 // value is a constant being inserted into element 0. It is cheaper to do
5971 // a constant pool load than it is to do a movd + shuffle.
5972 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5973 (!IsAllConstants || Idx == 0)) {
5974 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5976 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5977 EVT VecVT = MVT::v4i32;
5978 unsigned VecElts = 4;
5980 // Truncate the value (which may itself be a constant) to i32, and
5981 // convert it to a vector with movd (S2V+shuffle to zero extend).
5982 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5983 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5984 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5986 // Now we have our 32-bit value zero extended in the low element of
5987 // a vector. If Idx != 0, swizzle it into place.
5989 SmallVector<int, 4> Mask;
5990 Mask.push_back(Idx);
5991 for (unsigned i = 1; i != VecElts; ++i)
5993 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5996 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6000 // If we have a constant or non-constant insertion into the low element of
6001 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6002 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6003 // depending on what the source datatype is.
6006 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6008 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6009 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6010 if (VT.is256BitVector() || VT.is512BitVector()) {
6011 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6012 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6013 Item, DAG.getIntPtrConstant(0));
6015 assert(VT.is128BitVector() && "Expected an SSE value type!");
6016 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6017 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6018 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6021 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6022 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6023 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6024 if (VT.is256BitVector()) {
6025 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6026 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6028 assert(VT.is128BitVector() && "Expected an SSE value type!");
6029 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6031 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6035 // Is it a vector logical left shift?
6036 if (NumElems == 2 && Idx == 1 &&
6037 X86::isZeroNode(Op.getOperand(0)) &&
6038 !X86::isZeroNode(Op.getOperand(1))) {
6039 unsigned NumBits = VT.getSizeInBits();
6040 return getVShift(true, VT,
6041 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6042 VT, Op.getOperand(1)),
6043 NumBits/2, DAG, *this, dl);
6046 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6049 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6050 // is a non-constant being inserted into an element other than the low one,
6051 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6052 // movd/movss) to move this into the low element, then shuffle it into
6054 if (EVTBits == 32) {
6055 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6057 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6058 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6059 SmallVector<int, 8> MaskVec;
6060 for (unsigned i = 0; i != NumElems; ++i)
6061 MaskVec.push_back(i == Idx ? 0 : 1);
6062 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6066 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6067 if (Values.size() == 1) {
6068 if (EVTBits == 32) {
6069 // Instead of a shuffle like this:
6070 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6071 // Check if it's possible to issue this instead.
6072 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6073 unsigned Idx = countTrailingZeros(NonZeros);
6074 SDValue Item = Op.getOperand(Idx);
6075 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6076 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6081 // A vector full of immediates; various special cases are already
6082 // handled, so this is best done with a single constant-pool load.
6086 // For AVX-length vectors, build the individual 128-bit pieces and use
6087 // shuffles to put them in place.
6088 if (VT.is256BitVector() || VT.is512BitVector()) {
6089 SmallVector<SDValue, 64> V;
6090 for (unsigned i = 0; i != NumElems; ++i)
6091 V.push_back(Op.getOperand(i));
6093 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6095 // Build both the lower and upper subvector.
6096 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6097 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6100 // Recreate the wider vector with the lower and upper part.
6101 if (VT.is256BitVector())
6102 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6103 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6106 // Let legalizer expand 2-wide build_vectors.
6107 if (EVTBits == 64) {
6108 if (NumNonZero == 1) {
6109 // One half is zero or undef.
6110 unsigned Idx = countTrailingZeros(NonZeros);
6111 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6112 Op.getOperand(Idx));
6113 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6118 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6119 if (EVTBits == 8 && NumElems == 16) {
6120 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6122 if (V.getNode()) return V;
6125 if (EVTBits == 16 && NumElems == 8) {
6126 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6128 if (V.getNode()) return V;
6131 // If element VT is == 32 bits, turn it into a number of shuffles.
6132 SmallVector<SDValue, 8> V(NumElems);
6133 if (NumElems == 4 && NumZero > 0) {
6134 for (unsigned i = 0; i < 4; ++i) {
6135 bool isZero = !(NonZeros & (1 << i));
6137 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6139 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6142 for (unsigned i = 0; i < 2; ++i) {
6143 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6146 V[i] = V[i*2]; // Must be a zero vector.
6149 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6152 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6155 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6160 bool Reverse1 = (NonZeros & 0x3) == 2;
6161 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6165 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6166 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6168 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6171 if (Values.size() > 1 && VT.is128BitVector()) {
6172 // Check for a build vector of consecutive loads.
6173 for (unsigned i = 0; i < NumElems; ++i)
6174 V[i] = Op.getOperand(i);
6176 // Check for elements which are consecutive loads.
6177 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6181 // Check for a build vector from mostly shuffle plus few inserting.
6182 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6186 // For SSE 4.1, use insertps to put the high elements into the low element.
6187 if (getSubtarget()->hasSSE41()) {
6189 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6190 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6192 Result = DAG.getUNDEF(VT);
6194 for (unsigned i = 1; i < NumElems; ++i) {
6195 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6196 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6197 Op.getOperand(i), DAG.getIntPtrConstant(i));
6202 // Otherwise, expand into a number of unpckl*, start by extending each of
6203 // our (non-undef) elements to the full vector width with the element in the
6204 // bottom slot of the vector (which generates no code for SSE).
6205 for (unsigned i = 0; i < NumElems; ++i) {
6206 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6207 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6209 V[i] = DAG.getUNDEF(VT);
6212 // Next, we iteratively mix elements, e.g. for v4f32:
6213 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6214 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6215 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6216 unsigned EltStride = NumElems >> 1;
6217 while (EltStride != 0) {
6218 for (unsigned i = 0; i < EltStride; ++i) {
6219 // If V[i+EltStride] is undef and this is the first round of mixing,
6220 // then it is safe to just drop this shuffle: V[i] is already in the
6221 // right place, the one element (since it's the first round) being
6222 // inserted as undef can be dropped. This isn't safe for successive
6223 // rounds because they will permute elements within both vectors.
6224 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6225 EltStride == NumElems/2)
6228 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6237 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6238 // to create 256-bit vectors from two other 128-bit ones.
6239 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6241 MVT ResVT = Op.getSimpleValueType();
6243 assert((ResVT.is256BitVector() ||
6244 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6246 SDValue V1 = Op.getOperand(0);
6247 SDValue V2 = Op.getOperand(1);
6248 unsigned NumElems = ResVT.getVectorNumElements();
6249 if(ResVT.is256BitVector())
6250 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6252 if (Op.getNumOperands() == 4) {
6253 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6254 ResVT.getVectorNumElements()/2);
6255 SDValue V3 = Op.getOperand(2);
6256 SDValue V4 = Op.getOperand(3);
6257 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6258 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6260 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6263 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6264 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6265 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6266 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6267 Op.getNumOperands() == 4)));
6269 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6270 // from two other 128-bit ones.
6272 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6273 return LowerAVXCONCAT_VECTORS(Op, DAG);
6276 // Try to lower a shuffle node into a simple blend instruction.
6278 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6279 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6280 SDValue V1 = SVOp->getOperand(0);
6281 SDValue V2 = SVOp->getOperand(1);
6283 MVT VT = SVOp->getSimpleValueType(0);
6284 MVT EltVT = VT.getVectorElementType();
6285 unsigned NumElems = VT.getVectorNumElements();
6287 // There is no blend with immediate in AVX-512.
6288 if (VT.is512BitVector())
6291 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6293 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6296 // Check the mask for BLEND and build the value.
6297 unsigned MaskValue = 0;
6298 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6299 unsigned NumLanes = (NumElems-1)/8 + 1;
6300 unsigned NumElemsInLane = NumElems / NumLanes;
6302 // Blend for v16i16 should be symetric for the both lanes.
6303 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6305 int SndLaneEltIdx = (NumLanes == 2) ?
6306 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6307 int EltIdx = SVOp->getMaskElt(i);
6309 if ((EltIdx < 0 || EltIdx == (int)i) &&
6310 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6313 if (((unsigned)EltIdx == (i + NumElems)) &&
6314 (SndLaneEltIdx < 0 ||
6315 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6316 MaskValue |= (1<<i);
6321 // Convert i32 vectors to floating point if it is not AVX2.
6322 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6324 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6325 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6327 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6328 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6331 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6332 DAG.getConstant(MaskValue, MVT::i32));
6333 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6336 /// In vector type \p VT, return true if the element at index \p InputIdx
6337 /// falls on a different 128-bit lane than \p OutputIdx.
6338 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6339 unsigned OutputIdx) {
6340 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6341 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6344 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6345 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6346 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6347 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6349 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6350 SelectionDAG &DAG) {
6351 MVT VT = V1.getSimpleValueType();
6352 assert(VT.is128BitVector() || VT.is256BitVector());
6354 MVT EltVT = VT.getVectorElementType();
6355 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6356 unsigned NumElts = VT.getVectorNumElements();
6358 SmallVector<SDValue, 32> PshufbMask;
6359 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6360 int InputIdx = MaskVals[OutputIdx];
6361 unsigned InputByteIdx;
6363 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6364 InputByteIdx = 0x80;
6366 // Cross lane is not allowed.
6367 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6369 InputByteIdx = InputIdx * EltSizeInBytes;
6370 // Index is an byte offset within the 128-bit lane.
6371 InputByteIdx &= 0xf;
6374 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6375 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6376 if (InputByteIdx != 0x80)
6381 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6383 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6384 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6385 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6386 PshufbMask.data(), PshufbMask.size()));
6389 // v8i16 shuffles - Prefer shuffles in the following order:
6390 // 1. [all] pshuflw, pshufhw, optional move
6391 // 2. [ssse3] 1 x pshufb
6392 // 3. [ssse3] 2 x pshufb + 1 x por
6393 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6395 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6396 SelectionDAG &DAG) {
6397 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6398 SDValue V1 = SVOp->getOperand(0);
6399 SDValue V2 = SVOp->getOperand(1);
6401 SmallVector<int, 8> MaskVals;
6403 // Determine if more than 1 of the words in each of the low and high quadwords
6404 // of the result come from the same quadword of one of the two inputs. Undef
6405 // mask values count as coming from any quadword, for better codegen.
6407 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6408 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6409 unsigned LoQuad[] = { 0, 0, 0, 0 };
6410 unsigned HiQuad[] = { 0, 0, 0, 0 };
6411 // Indices of quads used.
6412 std::bitset<4> InputQuads;
6413 for (unsigned i = 0; i < 8; ++i) {
6414 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6415 int EltIdx = SVOp->getMaskElt(i);
6416 MaskVals.push_back(EltIdx);
6425 InputQuads.set(EltIdx / 4);
6428 int BestLoQuad = -1;
6429 unsigned MaxQuad = 1;
6430 for (unsigned i = 0; i < 4; ++i) {
6431 if (LoQuad[i] > MaxQuad) {
6433 MaxQuad = LoQuad[i];
6437 int BestHiQuad = -1;
6439 for (unsigned i = 0; i < 4; ++i) {
6440 if (HiQuad[i] > MaxQuad) {
6442 MaxQuad = HiQuad[i];
6446 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6447 // of the two input vectors, shuffle them into one input vector so only a
6448 // single pshufb instruction is necessary. If there are more than 2 input
6449 // quads, disable the next transformation since it does not help SSSE3.
6450 bool V1Used = InputQuads[0] || InputQuads[1];
6451 bool V2Used = InputQuads[2] || InputQuads[3];
6452 if (Subtarget->hasSSSE3()) {
6453 if (InputQuads.count() == 2 && V1Used && V2Used) {
6454 BestLoQuad = InputQuads[0] ? 0 : 1;
6455 BestHiQuad = InputQuads[2] ? 2 : 3;
6457 if (InputQuads.count() > 2) {
6463 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6464 // the shuffle mask. If a quad is scored as -1, that means that it contains
6465 // words from all 4 input quadwords.
6467 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6469 BestLoQuad < 0 ? 0 : BestLoQuad,
6470 BestHiQuad < 0 ? 1 : BestHiQuad
6472 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6473 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6474 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6475 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6477 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6478 // source words for the shuffle, to aid later transformations.
6479 bool AllWordsInNewV = true;
6480 bool InOrder[2] = { true, true };
6481 for (unsigned i = 0; i != 8; ++i) {
6482 int idx = MaskVals[i];
6484 InOrder[i/4] = false;
6485 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6487 AllWordsInNewV = false;
6491 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6492 if (AllWordsInNewV) {
6493 for (int i = 0; i != 8; ++i) {
6494 int idx = MaskVals[i];
6497 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6498 if ((idx != i) && idx < 4)
6500 if ((idx != i) && idx > 3)
6509 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6510 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6511 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6512 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6513 unsigned TargetMask = 0;
6514 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6515 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6516 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6517 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6518 getShufflePSHUFLWImmediate(SVOp);
6519 V1 = NewV.getOperand(0);
6520 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6524 // Promote splats to a larger type which usually leads to more efficient code.
6525 // FIXME: Is this true if pshufb is available?
6526 if (SVOp->isSplat())
6527 return PromoteSplat(SVOp, DAG);
6529 // If we have SSSE3, and all words of the result are from 1 input vector,
6530 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6531 // is present, fall back to case 4.
6532 if (Subtarget->hasSSSE3()) {
6533 SmallVector<SDValue,16> pshufbMask;
6535 // If we have elements from both input vectors, set the high bit of the
6536 // shuffle mask element to zero out elements that come from V2 in the V1
6537 // mask, and elements that come from V1 in the V2 mask, so that the two
6538 // results can be OR'd together.
6539 bool TwoInputs = V1Used && V2Used;
6540 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6542 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6544 // Calculate the shuffle mask for the second input, shuffle it, and
6545 // OR it with the first shuffled input.
6546 CommuteVectorShuffleMask(MaskVals, 8);
6547 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6548 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6549 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6552 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6553 // and update MaskVals with new element order.
6554 std::bitset<8> InOrder;
6555 if (BestLoQuad >= 0) {
6556 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6557 for (int i = 0; i != 4; ++i) {
6558 int idx = MaskVals[i];
6561 } else if ((idx / 4) == BestLoQuad) {
6566 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6569 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6570 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6571 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6573 getShufflePSHUFLWImmediate(SVOp), DAG);
6577 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6578 // and update MaskVals with the new element order.
6579 if (BestHiQuad >= 0) {
6580 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6581 for (unsigned i = 4; i != 8; ++i) {
6582 int idx = MaskVals[i];
6585 } else if ((idx / 4) == BestHiQuad) {
6586 MaskV[i] = (idx & 3) + 4;
6590 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6593 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6594 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6595 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6597 getShufflePSHUFHWImmediate(SVOp), DAG);
6601 // In case BestHi & BestLo were both -1, which means each quadword has a word
6602 // from each of the four input quadwords, calculate the InOrder bitvector now
6603 // before falling through to the insert/extract cleanup.
6604 if (BestLoQuad == -1 && BestHiQuad == -1) {
6606 for (int i = 0; i != 8; ++i)
6607 if (MaskVals[i] < 0 || MaskVals[i] == i)
6611 // The other elements are put in the right place using pextrw and pinsrw.
6612 for (unsigned i = 0; i != 8; ++i) {
6615 int EltIdx = MaskVals[i];
6618 SDValue ExtOp = (EltIdx < 8) ?
6619 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6620 DAG.getIntPtrConstant(EltIdx)) :
6621 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6622 DAG.getIntPtrConstant(EltIdx - 8));
6623 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6624 DAG.getIntPtrConstant(i));
6629 /// \brief v16i16 shuffles
6631 /// FIXME: We only support generation of a single pshufb currently. We can
6632 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6633 /// well (e.g 2 x pshufb + 1 x por).
6635 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6636 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6637 SDValue V1 = SVOp->getOperand(0);
6638 SDValue V2 = SVOp->getOperand(1);
6641 if (V2.getOpcode() != ISD::UNDEF)
6644 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6645 return getPSHUFB(MaskVals, V1, dl, DAG);
6648 // v16i8 shuffles - Prefer shuffles in the following order:
6649 // 1. [ssse3] 1 x pshufb
6650 // 2. [ssse3] 2 x pshufb + 1 x por
6651 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6652 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6653 const X86Subtarget* Subtarget,
6654 SelectionDAG &DAG) {
6655 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6656 SDValue V1 = SVOp->getOperand(0);
6657 SDValue V2 = SVOp->getOperand(1);
6659 ArrayRef<int> MaskVals = SVOp->getMask();
6661 // Promote splats to a larger type which usually leads to more efficient code.
6662 // FIXME: Is this true if pshufb is available?
6663 if (SVOp->isSplat())
6664 return PromoteSplat(SVOp, DAG);
6666 // If we have SSSE3, case 1 is generated when all result bytes come from
6667 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6668 // present, fall back to case 3.
6670 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6671 if (Subtarget->hasSSSE3()) {
6672 SmallVector<SDValue,16> pshufbMask;
6674 // If all result elements are from one input vector, then only translate
6675 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6677 // Otherwise, we have elements from both input vectors, and must zero out
6678 // elements that come from V2 in the first mask, and V1 in the second mask
6679 // so that we can OR them together.
6680 for (unsigned i = 0; i != 16; ++i) {
6681 int EltIdx = MaskVals[i];
6682 if (EltIdx < 0 || EltIdx >= 16)
6684 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6686 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6687 DAG.getNode(ISD::BUILD_VECTOR, dl,
6688 MVT::v16i8, &pshufbMask[0], 16));
6690 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6691 // the 2nd operand if it's undefined or zero.
6692 if (V2.getOpcode() == ISD::UNDEF ||
6693 ISD::isBuildVectorAllZeros(V2.getNode()))
6696 // Calculate the shuffle mask for the second input, shuffle it, and
6697 // OR it with the first shuffled input.
6699 for (unsigned i = 0; i != 16; ++i) {
6700 int EltIdx = MaskVals[i];
6701 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6702 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6704 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6705 DAG.getNode(ISD::BUILD_VECTOR, dl,
6706 MVT::v16i8, &pshufbMask[0], 16));
6707 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6710 // No SSSE3 - Calculate in place words and then fix all out of place words
6711 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6712 // the 16 different words that comprise the two doublequadword input vectors.
6713 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6714 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6716 for (int i = 0; i != 8; ++i) {
6717 int Elt0 = MaskVals[i*2];
6718 int Elt1 = MaskVals[i*2+1];
6720 // This word of the result is all undef, skip it.
6721 if (Elt0 < 0 && Elt1 < 0)
6724 // This word of the result is already in the correct place, skip it.
6725 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6728 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6729 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6732 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6733 // using a single extract together, load it and store it.
6734 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6735 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6736 DAG.getIntPtrConstant(Elt1 / 2));
6737 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6738 DAG.getIntPtrConstant(i));
6742 // If Elt1 is defined, extract it from the appropriate source. If the
6743 // source byte is not also odd, shift the extracted word left 8 bits
6744 // otherwise clear the bottom 8 bits if we need to do an or.
6746 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6747 DAG.getIntPtrConstant(Elt1 / 2));
6748 if ((Elt1 & 1) == 0)
6749 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6751 TLI.getShiftAmountTy(InsElt.getValueType())));
6753 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6754 DAG.getConstant(0xFF00, MVT::i16));
6756 // If Elt0 is defined, extract it from the appropriate source. If the
6757 // source byte is not also even, shift the extracted word right 8 bits. If
6758 // Elt1 was also defined, OR the extracted values together before
6759 // inserting them in the result.
6761 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6762 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6763 if ((Elt0 & 1) != 0)
6764 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6766 TLI.getShiftAmountTy(InsElt0.getValueType())));
6768 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6769 DAG.getConstant(0x00FF, MVT::i16));
6770 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6773 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6774 DAG.getIntPtrConstant(i));
6776 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6779 // v32i8 shuffles - Translate to VPSHUFB if possible.
6781 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6782 const X86Subtarget *Subtarget,
6783 SelectionDAG &DAG) {
6784 MVT VT = SVOp->getSimpleValueType(0);
6785 SDValue V1 = SVOp->getOperand(0);
6786 SDValue V2 = SVOp->getOperand(1);
6788 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6790 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6791 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6792 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6794 // VPSHUFB may be generated if
6795 // (1) one of input vector is undefined or zeroinitializer.
6796 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6797 // And (2) the mask indexes don't cross the 128-bit lane.
6798 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6799 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6802 if (V1IsAllZero && !V2IsAllZero) {
6803 CommuteVectorShuffleMask(MaskVals, 32);
6806 return getPSHUFB(MaskVals, V1, dl, DAG);
6809 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6810 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6811 /// done when every pair / quad of shuffle mask elements point to elements in
6812 /// the right sequence. e.g.
6813 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6815 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6816 SelectionDAG &DAG) {
6817 MVT VT = SVOp->getSimpleValueType(0);
6819 unsigned NumElems = VT.getVectorNumElements();
6822 switch (VT.SimpleTy) {
6823 default: llvm_unreachable("Unexpected!");
6824 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6825 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6826 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6827 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6828 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6829 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6832 SmallVector<int, 8> MaskVec;
6833 for (unsigned i = 0; i != NumElems; i += Scale) {
6835 for (unsigned j = 0; j != Scale; ++j) {
6836 int EltIdx = SVOp->getMaskElt(i+j);
6840 StartIdx = (EltIdx / Scale);
6841 if (EltIdx != (int)(StartIdx*Scale + j))
6844 MaskVec.push_back(StartIdx);
6847 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6848 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6849 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6852 /// getVZextMovL - Return a zero-extending vector move low node.
6854 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6855 SDValue SrcOp, SelectionDAG &DAG,
6856 const X86Subtarget *Subtarget, SDLoc dl) {
6857 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6858 LoadSDNode *LD = NULL;
6859 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6860 LD = dyn_cast<LoadSDNode>(SrcOp);
6862 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6864 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6865 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6866 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6867 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6868 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6870 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6871 return DAG.getNode(ISD::BITCAST, dl, VT,
6872 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6873 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6881 return DAG.getNode(ISD::BITCAST, dl, VT,
6882 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6883 DAG.getNode(ISD::BITCAST, dl,
6887 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6888 /// which could not be matched by any known target speficic shuffle
6890 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6892 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6893 if (NewOp.getNode())
6896 MVT VT = SVOp->getSimpleValueType(0);
6898 unsigned NumElems = VT.getVectorNumElements();
6899 unsigned NumLaneElems = NumElems / 2;
6902 MVT EltVT = VT.getVectorElementType();
6903 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6906 SmallVector<int, 16> Mask;
6907 for (unsigned l = 0; l < 2; ++l) {
6908 // Build a shuffle mask for the output, discovering on the fly which
6909 // input vectors to use as shuffle operands (recorded in InputUsed).
6910 // If building a suitable shuffle vector proves too hard, then bail
6911 // out with UseBuildVector set.
6912 bool UseBuildVector = false;
6913 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6914 unsigned LaneStart = l * NumLaneElems;
6915 for (unsigned i = 0; i != NumLaneElems; ++i) {
6916 // The mask element. This indexes into the input.
6917 int Idx = SVOp->getMaskElt(i+LaneStart);
6919 // the mask element does not index into any input vector.
6924 // The input vector this mask element indexes into.
6925 int Input = Idx / NumLaneElems;
6927 // Turn the index into an offset from the start of the input vector.
6928 Idx -= Input * NumLaneElems;
6930 // Find or create a shuffle vector operand to hold this input.
6932 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6933 if (InputUsed[OpNo] == Input)
6934 // This input vector is already an operand.
6936 if (InputUsed[OpNo] < 0) {
6937 // Create a new operand for this input vector.
6938 InputUsed[OpNo] = Input;
6943 if (OpNo >= array_lengthof(InputUsed)) {
6944 // More than two input vectors used! Give up on trying to create a
6945 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6946 UseBuildVector = true;
6950 // Add the mask index for the new shuffle vector.
6951 Mask.push_back(Idx + OpNo * NumLaneElems);
6954 if (UseBuildVector) {
6955 SmallVector<SDValue, 16> SVOps;
6956 for (unsigned i = 0; i != NumLaneElems; ++i) {
6957 // The mask element. This indexes into the input.
6958 int Idx = SVOp->getMaskElt(i+LaneStart);
6960 SVOps.push_back(DAG.getUNDEF(EltVT));
6964 // The input vector this mask element indexes into.
6965 int Input = Idx / NumElems;
6967 // Turn the index into an offset from the start of the input vector.
6968 Idx -= Input * NumElems;
6970 // Extract the vector element by hand.
6971 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6972 SVOp->getOperand(Input),
6973 DAG.getIntPtrConstant(Idx)));
6976 // Construct the output using a BUILD_VECTOR.
6977 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6979 } else if (InputUsed[0] < 0) {
6980 // No input vectors were used! The result is undefined.
6981 Output[l] = DAG.getUNDEF(NVT);
6983 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6984 (InputUsed[0] % 2) * NumLaneElems,
6986 // If only one input was used, use an undefined vector for the other.
6987 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6988 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6989 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6990 // At least one input vector was used. Create a new shuffle vector.
6991 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6997 // Concatenate the result back
6998 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7001 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7002 /// 4 elements, and match them with several different shuffle types.
7004 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7005 SDValue V1 = SVOp->getOperand(0);
7006 SDValue V2 = SVOp->getOperand(1);
7008 MVT VT = SVOp->getSimpleValueType(0);
7010 assert(VT.is128BitVector() && "Unsupported vector size");
7012 std::pair<int, int> Locs[4];
7013 int Mask1[] = { -1, -1, -1, -1 };
7014 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7018 for (unsigned i = 0; i != 4; ++i) {
7019 int Idx = PermMask[i];
7021 Locs[i] = std::make_pair(-1, -1);
7023 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7025 Locs[i] = std::make_pair(0, NumLo);
7029 Locs[i] = std::make_pair(1, NumHi);
7031 Mask1[2+NumHi] = Idx;
7037 if (NumLo <= 2 && NumHi <= 2) {
7038 // If no more than two elements come from either vector. This can be
7039 // implemented with two shuffles. First shuffle gather the elements.
7040 // The second shuffle, which takes the first shuffle as both of its
7041 // vector operands, put the elements into the right order.
7042 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7044 int Mask2[] = { -1, -1, -1, -1 };
7046 for (unsigned i = 0; i != 4; ++i)
7047 if (Locs[i].first != -1) {
7048 unsigned Idx = (i < 2) ? 0 : 4;
7049 Idx += Locs[i].first * 2 + Locs[i].second;
7053 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7056 if (NumLo == 3 || NumHi == 3) {
7057 // Otherwise, we must have three elements from one vector, call it X, and
7058 // one element from the other, call it Y. First, use a shufps to build an
7059 // intermediate vector with the one element from Y and the element from X
7060 // that will be in the same half in the final destination (the indexes don't
7061 // matter). Then, use a shufps to build the final vector, taking the half
7062 // containing the element from Y from the intermediate, and the other half
7065 // Normalize it so the 3 elements come from V1.
7066 CommuteVectorShuffleMask(PermMask, 4);
7070 // Find the element from V2.
7072 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7073 int Val = PermMask[HiIndex];
7080 Mask1[0] = PermMask[HiIndex];
7082 Mask1[2] = PermMask[HiIndex^1];
7084 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7087 Mask1[0] = PermMask[0];
7088 Mask1[1] = PermMask[1];
7089 Mask1[2] = HiIndex & 1 ? 6 : 4;
7090 Mask1[3] = HiIndex & 1 ? 4 : 6;
7091 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7094 Mask1[0] = HiIndex & 1 ? 2 : 0;
7095 Mask1[1] = HiIndex & 1 ? 0 : 2;
7096 Mask1[2] = PermMask[2];
7097 Mask1[3] = PermMask[3];
7102 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7105 // Break it into (shuffle shuffle_hi, shuffle_lo).
7106 int LoMask[] = { -1, -1, -1, -1 };
7107 int HiMask[] = { -1, -1, -1, -1 };
7109 int *MaskPtr = LoMask;
7110 unsigned MaskIdx = 0;
7113 for (unsigned i = 0; i != 4; ++i) {
7120 int Idx = PermMask[i];
7122 Locs[i] = std::make_pair(-1, -1);
7123 } else if (Idx < 4) {
7124 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7125 MaskPtr[LoIdx] = Idx;
7128 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7129 MaskPtr[HiIdx] = Idx;
7134 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7135 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7136 int MaskOps[] = { -1, -1, -1, -1 };
7137 for (unsigned i = 0; i != 4; ++i)
7138 if (Locs[i].first != -1)
7139 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7140 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7143 static bool MayFoldVectorLoad(SDValue V) {
7144 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7145 V = V.getOperand(0);
7147 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7148 V = V.getOperand(0);
7149 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7150 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7151 // BUILD_VECTOR (load), undef
7152 V = V.getOperand(0);
7154 return MayFoldLoad(V);
7158 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7159 MVT VT = Op.getSimpleValueType();
7161 // Canonizalize to v2f64.
7162 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7163 return DAG.getNode(ISD::BITCAST, dl, VT,
7164 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7169 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7171 SDValue V1 = Op.getOperand(0);
7172 SDValue V2 = Op.getOperand(1);
7173 MVT VT = Op.getSimpleValueType();
7175 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7177 if (HasSSE2 && VT == MVT::v2f64)
7178 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7180 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7181 return DAG.getNode(ISD::BITCAST, dl, VT,
7182 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7183 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7184 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7188 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7189 SDValue V1 = Op.getOperand(0);
7190 SDValue V2 = Op.getOperand(1);
7191 MVT VT = Op.getSimpleValueType();
7193 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7194 "unsupported shuffle type");
7196 if (V2.getOpcode() == ISD::UNDEF)
7200 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7204 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7205 SDValue V1 = Op.getOperand(0);
7206 SDValue V2 = Op.getOperand(1);
7207 MVT VT = Op.getSimpleValueType();
7208 unsigned NumElems = VT.getVectorNumElements();
7210 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7211 // operand of these instructions is only memory, so check if there's a
7212 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7214 bool CanFoldLoad = false;
7216 // Trivial case, when V2 comes from a load.
7217 if (MayFoldVectorLoad(V2))
7220 // When V1 is a load, it can be folded later into a store in isel, example:
7221 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7223 // (MOVLPSmr addr:$src1, VR128:$src2)
7224 // So, recognize this potential and also use MOVLPS or MOVLPD
7225 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7228 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7230 if (HasSSE2 && NumElems == 2)
7231 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7234 // If we don't care about the second element, proceed to use movss.
7235 if (SVOp->getMaskElt(1) != -1)
7236 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7239 // movl and movlp will both match v2i64, but v2i64 is never matched by
7240 // movl earlier because we make it strict to avoid messing with the movlp load
7241 // folding logic (see the code above getMOVLP call). Match it here then,
7242 // this is horrible, but will stay like this until we move all shuffle
7243 // matching to x86 specific nodes. Note that for the 1st condition all
7244 // types are matched with movsd.
7246 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7247 // as to remove this logic from here, as much as possible
7248 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7249 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7250 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7253 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7255 // Invert the operand order and use SHUFPS to match it.
7256 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7257 getShuffleSHUFImmediate(SVOp), DAG);
7260 // Reduce a vector shuffle to zext.
7261 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7262 SelectionDAG &DAG) {
7263 // PMOVZX is only available from SSE41.
7264 if (!Subtarget->hasSSE41())
7267 MVT VT = Op.getSimpleValueType();
7269 // Only AVX2 support 256-bit vector integer extending.
7270 if (!Subtarget->hasInt256() && VT.is256BitVector())
7273 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7275 SDValue V1 = Op.getOperand(0);
7276 SDValue V2 = Op.getOperand(1);
7277 unsigned NumElems = VT.getVectorNumElements();
7279 // Extending is an unary operation and the element type of the source vector
7280 // won't be equal to or larger than i64.
7281 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7282 VT.getVectorElementType() == MVT::i64)
7285 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7286 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7287 while ((1U << Shift) < NumElems) {
7288 if (SVOp->getMaskElt(1U << Shift) == 1)
7291 // The maximal ratio is 8, i.e. from i8 to i64.
7296 // Check the shuffle mask.
7297 unsigned Mask = (1U << Shift) - 1;
7298 for (unsigned i = 0; i != NumElems; ++i) {
7299 int EltIdx = SVOp->getMaskElt(i);
7300 if ((i & Mask) != 0 && EltIdx != -1)
7302 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7306 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7307 MVT NeVT = MVT::getIntegerVT(NBits);
7308 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7310 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7313 // Simplify the operand as it's prepared to be fed into shuffle.
7314 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7315 if (V1.getOpcode() == ISD::BITCAST &&
7316 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7317 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7318 V1.getOperand(0).getOperand(0)
7319 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7320 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7321 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7322 ConstantSDNode *CIdx =
7323 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7324 // If it's foldable, i.e. normal load with single use, we will let code
7325 // selection to fold it. Otherwise, we will short the conversion sequence.
7326 if (CIdx && CIdx->getZExtValue() == 0 &&
7327 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7328 MVT FullVT = V.getSimpleValueType();
7329 MVT V1VT = V1.getSimpleValueType();
7330 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7331 // The "ext_vec_elt" node is wider than the result node.
7332 // In this case we should extract subvector from V.
7333 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7334 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7335 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7336 FullVT.getVectorNumElements()/Ratio);
7337 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7338 DAG.getIntPtrConstant(0));
7340 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7344 return DAG.getNode(ISD::BITCAST, DL, VT,
7345 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7349 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7350 SelectionDAG &DAG) {
7351 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7352 MVT VT = Op.getSimpleValueType();
7354 SDValue V1 = Op.getOperand(0);
7355 SDValue V2 = Op.getOperand(1);
7357 if (isZeroShuffle(SVOp))
7358 return getZeroVector(VT, Subtarget, DAG, dl);
7360 // Handle splat operations
7361 if (SVOp->isSplat()) {
7362 // Use vbroadcast whenever the splat comes from a foldable load
7363 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7364 if (Broadcast.getNode())
7368 // Check integer expanding shuffles.
7369 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7370 if (NewOp.getNode())
7373 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7375 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7376 VT == MVT::v16i16 || VT == MVT::v32i8) {
7377 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7378 if (NewOp.getNode())
7379 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7380 } else if ((VT == MVT::v4i32 ||
7381 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7382 // FIXME: Figure out a cleaner way to do this.
7383 // Try to make use of movq to zero out the top part.
7384 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7385 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7386 if (NewOp.getNode()) {
7387 MVT NewVT = NewOp.getSimpleValueType();
7388 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7389 NewVT, true, false))
7390 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7391 DAG, Subtarget, dl);
7393 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7394 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7395 if (NewOp.getNode()) {
7396 MVT NewVT = NewOp.getSimpleValueType();
7397 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7398 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7399 DAG, Subtarget, dl);
7407 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7408 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7409 SDValue V1 = Op.getOperand(0);
7410 SDValue V2 = Op.getOperand(1);
7411 MVT VT = Op.getSimpleValueType();
7413 unsigned NumElems = VT.getVectorNumElements();
7414 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7415 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7416 bool V1IsSplat = false;
7417 bool V2IsSplat = false;
7418 bool HasSSE2 = Subtarget->hasSSE2();
7419 bool HasFp256 = Subtarget->hasFp256();
7420 bool HasInt256 = Subtarget->hasInt256();
7421 MachineFunction &MF = DAG.getMachineFunction();
7422 bool OptForSize = MF.getFunction()->getAttributes().
7423 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7425 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7427 if (V1IsUndef && V2IsUndef)
7428 return DAG.getUNDEF(VT);
7430 // When we create a shuffle node we put the UNDEF node to second operand,
7431 // but in some cases the first operand may be transformed to UNDEF.
7432 // In this case we should just commute the node.
7434 return CommuteVectorShuffle(SVOp, DAG);
7436 // Vector shuffle lowering takes 3 steps:
7438 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7439 // narrowing and commutation of operands should be handled.
7440 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7442 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7443 // so the shuffle can be broken into other shuffles and the legalizer can
7444 // try the lowering again.
7446 // The general idea is that no vector_shuffle operation should be left to
7447 // be matched during isel, all of them must be converted to a target specific
7450 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7451 // narrowing and commutation of operands should be handled. The actual code
7452 // doesn't include all of those, work in progress...
7453 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7454 if (NewOp.getNode())
7457 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7459 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7460 // unpckh_undef). Only use pshufd if speed is more important than size.
7461 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7462 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7463 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7464 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7466 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7467 V2IsUndef && MayFoldVectorLoad(V1))
7468 return getMOVDDup(Op, dl, V1, DAG);
7470 if (isMOVHLPS_v_undef_Mask(M, VT))
7471 return getMOVHighToLow(Op, dl, DAG);
7473 // Use to match splats
7474 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7475 (VT == MVT::v2f64 || VT == MVT::v2i64))
7476 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7478 if (isPSHUFDMask(M, VT)) {
7479 // The actual implementation will match the mask in the if above and then
7480 // during isel it can match several different instructions, not only pshufd
7481 // as its name says, sad but true, emulate the behavior for now...
7482 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7483 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7485 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7487 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7488 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7490 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7491 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7494 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7498 if (isPALIGNRMask(M, VT, Subtarget))
7499 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7500 getShufflePALIGNRImmediate(SVOp),
7503 // Check if this can be converted into a logical shift.
7504 bool isLeft = false;
7507 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7508 if (isShift && ShVal.hasOneUse()) {
7509 // If the shifted value has multiple uses, it may be cheaper to use
7510 // v_set0 + movlhps or movhlps, etc.
7511 MVT EltVT = VT.getVectorElementType();
7512 ShAmt *= EltVT.getSizeInBits();
7513 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7516 if (isMOVLMask(M, VT)) {
7517 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7518 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7519 if (!isMOVLPMask(M, VT)) {
7520 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7521 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7523 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7524 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7528 // FIXME: fold these into legal mask.
7529 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7530 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7532 if (isMOVHLPSMask(M, VT))
7533 return getMOVHighToLow(Op, dl, DAG);
7535 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7536 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7538 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7539 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7541 if (isMOVLPMask(M, VT))
7542 return getMOVLP(Op, dl, DAG, HasSSE2);
7544 if (ShouldXformToMOVHLPS(M, VT) ||
7545 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7546 return CommuteVectorShuffle(SVOp, DAG);
7549 // No better options. Use a vshldq / vsrldq.
7550 MVT EltVT = VT.getVectorElementType();
7551 ShAmt *= EltVT.getSizeInBits();
7552 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7555 bool Commuted = false;
7556 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7557 // 1,1,1,1 -> v8i16 though.
7558 V1IsSplat = isSplatVector(V1.getNode());
7559 V2IsSplat = isSplatVector(V2.getNode());
7561 // Canonicalize the splat or undef, if present, to be on the RHS.
7562 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7563 CommuteVectorShuffleMask(M, NumElems);
7565 std::swap(V1IsSplat, V2IsSplat);
7569 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7570 // Shuffling low element of v1 into undef, just return v1.
7573 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7574 // the instruction selector will not match, so get a canonical MOVL with
7575 // swapped operands to undo the commute.
7576 return getMOVL(DAG, dl, VT, V2, V1);
7579 if (isUNPCKLMask(M, VT, HasInt256))
7580 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7582 if (isUNPCKHMask(M, VT, HasInt256))
7583 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7586 // Normalize mask so all entries that point to V2 points to its first
7587 // element then try to match unpck{h|l} again. If match, return a
7588 // new vector_shuffle with the corrected mask.p
7589 SmallVector<int, 8> NewMask(M.begin(), M.end());
7590 NormalizeMask(NewMask, NumElems);
7591 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7592 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7593 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7594 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7598 // Commute is back and try unpck* again.
7599 // FIXME: this seems wrong.
7600 CommuteVectorShuffleMask(M, NumElems);
7602 std::swap(V1IsSplat, V2IsSplat);
7604 if (isUNPCKLMask(M, VT, HasInt256))
7605 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7607 if (isUNPCKHMask(M, VT, HasInt256))
7608 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7611 // Normalize the node to match x86 shuffle ops if needed
7612 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7613 return CommuteVectorShuffle(SVOp, DAG);
7615 // The checks below are all present in isShuffleMaskLegal, but they are
7616 // inlined here right now to enable us to directly emit target specific
7617 // nodes, and remove one by one until they don't return Op anymore.
7619 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7620 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7621 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7622 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7625 if (isPSHUFHWMask(M, VT, HasInt256))
7626 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7627 getShufflePSHUFHWImmediate(SVOp),
7630 if (isPSHUFLWMask(M, VT, HasInt256))
7631 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7632 getShufflePSHUFLWImmediate(SVOp),
7635 if (isSHUFPMask(M, VT))
7636 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7637 getShuffleSHUFImmediate(SVOp), DAG);
7639 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7640 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7641 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7642 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7644 //===--------------------------------------------------------------------===//
7645 // Generate target specific nodes for 128 or 256-bit shuffles only
7646 // supported in the AVX instruction set.
7649 // Handle VMOVDDUPY permutations
7650 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7651 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7653 // Handle VPERMILPS/D* permutations
7654 if (isVPERMILPMask(M, VT)) {
7655 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7656 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7657 getShuffleSHUFImmediate(SVOp), DAG);
7658 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7659 getShuffleSHUFImmediate(SVOp), DAG);
7662 // Handle VPERM2F128/VPERM2I128 permutations
7663 if (isVPERM2X128Mask(M, VT, HasFp256))
7664 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7665 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7667 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7668 if (BlendOp.getNode())
7672 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7673 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7675 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7676 VT.is512BitVector()) {
7677 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7678 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7679 SmallVector<SDValue, 16> permclMask;
7680 for (unsigned i = 0; i != NumElems; ++i) {
7681 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7684 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7685 &permclMask[0], NumElems);
7687 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7688 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7689 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7690 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7691 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7694 //===--------------------------------------------------------------------===//
7695 // Since no target specific shuffle was selected for this generic one,
7696 // lower it into other known shuffles. FIXME: this isn't true yet, but
7697 // this is the plan.
7700 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7701 if (VT == MVT::v8i16) {
7702 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7703 if (NewOp.getNode())
7707 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7708 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7709 if (NewOp.getNode())
7713 if (VT == MVT::v16i8) {
7714 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7715 if (NewOp.getNode())
7719 if (VT == MVT::v32i8) {
7720 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7721 if (NewOp.getNode())
7725 // Handle all 128-bit wide vectors with 4 elements, and match them with
7726 // several different shuffle types.
7727 if (NumElems == 4 && VT.is128BitVector())
7728 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7730 // Handle general 256-bit shuffles
7731 if (VT.is256BitVector())
7732 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7737 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7738 MVT VT = Op.getSimpleValueType();
7741 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7744 if (VT.getSizeInBits() == 8) {
7745 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7746 Op.getOperand(0), Op.getOperand(1));
7747 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7748 DAG.getValueType(VT));
7749 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7752 if (VT.getSizeInBits() == 16) {
7753 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7754 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7756 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7757 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7758 DAG.getNode(ISD::BITCAST, dl,
7762 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7763 Op.getOperand(0), Op.getOperand(1));
7764 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7765 DAG.getValueType(VT));
7766 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7769 if (VT == MVT::f32) {
7770 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7771 // the result back to FR32 register. It's only worth matching if the
7772 // result has a single use which is a store or a bitcast to i32. And in
7773 // the case of a store, it's not worth it if the index is a constant 0,
7774 // because a MOVSSmr can be used instead, which is smaller and faster.
7775 if (!Op.hasOneUse())
7777 SDNode *User = *Op.getNode()->use_begin();
7778 if ((User->getOpcode() != ISD::STORE ||
7779 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7780 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7781 (User->getOpcode() != ISD::BITCAST ||
7782 User->getValueType(0) != MVT::i32))
7784 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7785 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7788 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7791 if (VT == MVT::i32 || VT == MVT::i64) {
7792 // ExtractPS/pextrq works with constant index.
7793 if (isa<ConstantSDNode>(Op.getOperand(1)))
7799 /// Extract one bit from mask vector, like v16i1 or v8i1.
7800 /// AVX-512 feature.
7802 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7803 SDValue Vec = Op.getOperand(0);
7805 MVT VecVT = Vec.getSimpleValueType();
7806 SDValue Idx = Op.getOperand(1);
7807 MVT EltVT = Op.getSimpleValueType();
7809 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7811 // variable index can't be handled in mask registers,
7812 // extend vector to VR512
7813 if (!isa<ConstantSDNode>(Idx)) {
7814 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7815 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7816 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7817 ExtVT.getVectorElementType(), Ext, Idx);
7818 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7821 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7822 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7823 unsigned MaxSift = rc->getSize()*8 - 1;
7824 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7825 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7826 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7827 DAG.getConstant(MaxSift, MVT::i8));
7828 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7829 DAG.getIntPtrConstant(0));
7833 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7834 SelectionDAG &DAG) const {
7836 SDValue Vec = Op.getOperand(0);
7837 MVT VecVT = Vec.getSimpleValueType();
7838 SDValue Idx = Op.getOperand(1);
7840 if (Op.getSimpleValueType() == MVT::i1)
7841 return ExtractBitFromMaskVector(Op, DAG);
7843 if (!isa<ConstantSDNode>(Idx)) {
7844 if (VecVT.is512BitVector() ||
7845 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7846 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7849 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7850 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7851 MaskEltVT.getSizeInBits());
7853 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7854 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7855 getZeroVector(MaskVT, Subtarget, DAG, dl),
7856 Idx, DAG.getConstant(0, getPointerTy()));
7857 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7858 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7859 Perm, DAG.getConstant(0, getPointerTy()));
7864 // If this is a 256-bit vector result, first extract the 128-bit vector and
7865 // then extract the element from the 128-bit vector.
7866 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7868 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7869 // Get the 128-bit vector.
7870 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7871 MVT EltVT = VecVT.getVectorElementType();
7873 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7875 //if (IdxVal >= NumElems/2)
7876 // IdxVal -= NumElems/2;
7877 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7878 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7879 DAG.getConstant(IdxVal, MVT::i32));
7882 assert(VecVT.is128BitVector() && "Unexpected vector length");
7884 if (Subtarget->hasSSE41()) {
7885 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7890 MVT VT = Op.getSimpleValueType();
7891 // TODO: handle v16i8.
7892 if (VT.getSizeInBits() == 16) {
7893 SDValue Vec = Op.getOperand(0);
7894 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7896 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7897 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7898 DAG.getNode(ISD::BITCAST, dl,
7901 // Transform it so it match pextrw which produces a 32-bit result.
7902 MVT EltVT = MVT::i32;
7903 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7904 Op.getOperand(0), Op.getOperand(1));
7905 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7906 DAG.getValueType(VT));
7907 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7910 if (VT.getSizeInBits() == 32) {
7911 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7915 // SHUFPS the element to the lowest double word, then movss.
7916 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7917 MVT VVT = Op.getOperand(0).getSimpleValueType();
7918 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7919 DAG.getUNDEF(VVT), Mask);
7920 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7921 DAG.getIntPtrConstant(0));
7924 if (VT.getSizeInBits() == 64) {
7925 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7926 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7927 // to match extract_elt for f64.
7928 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7932 // UNPCKHPD the element to the lowest double word, then movsd.
7933 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7934 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7935 int Mask[2] = { 1, -1 };
7936 MVT VVT = Op.getOperand(0).getSimpleValueType();
7937 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7938 DAG.getUNDEF(VVT), Mask);
7939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7940 DAG.getIntPtrConstant(0));
7946 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7947 MVT VT = Op.getSimpleValueType();
7948 MVT EltVT = VT.getVectorElementType();
7951 SDValue N0 = Op.getOperand(0);
7952 SDValue N1 = Op.getOperand(1);
7953 SDValue N2 = Op.getOperand(2);
7955 if (!VT.is128BitVector())
7958 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7959 isa<ConstantSDNode>(N2)) {
7961 if (VT == MVT::v8i16)
7962 Opc = X86ISD::PINSRW;
7963 else if (VT == MVT::v16i8)
7964 Opc = X86ISD::PINSRB;
7966 Opc = X86ISD::PINSRB;
7968 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7970 if (N1.getValueType() != MVT::i32)
7971 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7972 if (N2.getValueType() != MVT::i32)
7973 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7974 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7977 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7978 // Bits [7:6] of the constant are the source select. This will always be
7979 // zero here. The DAG Combiner may combine an extract_elt index into these
7980 // bits. For example (insert (extract, 3), 2) could be matched by putting
7981 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7982 // Bits [5:4] of the constant are the destination select. This is the
7983 // value of the incoming immediate.
7984 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7985 // combine either bitwise AND or insert of float 0.0 to set these bits.
7986 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7987 // Create this as a scalar to vector..
7988 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7989 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7992 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7993 // PINSR* works with constant index.
7999 /// Insert one bit to mask vector, like v16i1 or v8i1.
8000 /// AVX-512 feature.
8002 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8004 SDValue Vec = Op.getOperand(0);
8005 SDValue Elt = Op.getOperand(1);
8006 SDValue Idx = Op.getOperand(2);
8007 MVT VecVT = Vec.getSimpleValueType();
8009 if (!isa<ConstantSDNode>(Idx)) {
8010 // Non constant index. Extend source and destination,
8011 // insert element and then truncate the result.
8012 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8013 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8014 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8015 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8016 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8017 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8020 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8021 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8022 if (Vec.getOpcode() == ISD::UNDEF)
8023 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8024 DAG.getConstant(IdxVal, MVT::i8));
8025 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8026 unsigned MaxSift = rc->getSize()*8 - 1;
8027 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8028 DAG.getConstant(MaxSift, MVT::i8));
8029 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8030 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8031 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8034 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8035 MVT VT = Op.getSimpleValueType();
8036 MVT EltVT = VT.getVectorElementType();
8038 if (EltVT == MVT::i1)
8039 return InsertBitToMaskVector(Op, DAG);
8042 SDValue N0 = Op.getOperand(0);
8043 SDValue N1 = Op.getOperand(1);
8044 SDValue N2 = Op.getOperand(2);
8046 // If this is a 256-bit vector result, first extract the 128-bit vector,
8047 // insert the element into the extracted half and then place it back.
8048 if (VT.is256BitVector() || VT.is512BitVector()) {
8049 if (!isa<ConstantSDNode>(N2))
8052 // Get the desired 128-bit vector half.
8053 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8054 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8056 // Insert the element into the desired half.
8057 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8058 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8060 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8061 DAG.getConstant(IdxIn128, MVT::i32));
8063 // Insert the changed part back to the 256-bit vector
8064 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8067 if (Subtarget->hasSSE41())
8068 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8070 if (EltVT == MVT::i8)
8073 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8074 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8075 // as its second argument.
8076 if (N1.getValueType() != MVT::i32)
8077 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8078 if (N2.getValueType() != MVT::i32)
8079 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8080 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8085 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8087 MVT OpVT = Op.getSimpleValueType();
8089 // If this is a 256-bit vector result, first insert into a 128-bit
8090 // vector and then insert into the 256-bit vector.
8091 if (!OpVT.is128BitVector()) {
8092 // Insert into a 128-bit vector.
8093 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8094 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8095 OpVT.getVectorNumElements() / SizeFactor);
8097 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8099 // Insert the 128-bit vector.
8100 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8103 if (OpVT == MVT::v1i64 &&
8104 Op.getOperand(0).getValueType() == MVT::i64)
8105 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8107 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8108 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8109 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8110 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8113 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8114 // a simple subregister reference or explicit instructions to grab
8115 // upper bits of a vector.
8116 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8117 SelectionDAG &DAG) {
8119 SDValue In = Op.getOperand(0);
8120 SDValue Idx = Op.getOperand(1);
8121 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8122 MVT ResVT = Op.getSimpleValueType();
8123 MVT InVT = In.getSimpleValueType();
8125 if (Subtarget->hasFp256()) {
8126 if (ResVT.is128BitVector() &&
8127 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8128 isa<ConstantSDNode>(Idx)) {
8129 return Extract128BitVector(In, IdxVal, DAG, dl);
8131 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8132 isa<ConstantSDNode>(Idx)) {
8133 return Extract256BitVector(In, IdxVal, DAG, dl);
8139 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8140 // simple superregister reference or explicit instructions to insert
8141 // the upper bits of a vector.
8142 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8143 SelectionDAG &DAG) {
8144 if (Subtarget->hasFp256()) {
8145 SDLoc dl(Op.getNode());
8146 SDValue Vec = Op.getNode()->getOperand(0);
8147 SDValue SubVec = Op.getNode()->getOperand(1);
8148 SDValue Idx = Op.getNode()->getOperand(2);
8150 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8151 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8152 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8153 isa<ConstantSDNode>(Idx)) {
8154 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8155 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8158 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8159 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8160 isa<ConstantSDNode>(Idx)) {
8161 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8162 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8168 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8169 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8170 // one of the above mentioned nodes. It has to be wrapped because otherwise
8171 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8172 // be used to form addressing mode. These wrapped nodes will be selected
8175 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8176 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8178 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8180 unsigned char OpFlag = 0;
8181 unsigned WrapperKind = X86ISD::Wrapper;
8182 CodeModel::Model M = getTargetMachine().getCodeModel();
8184 if (Subtarget->isPICStyleRIPRel() &&
8185 (M == CodeModel::Small || M == CodeModel::Kernel))
8186 WrapperKind = X86ISD::WrapperRIP;
8187 else if (Subtarget->isPICStyleGOT())
8188 OpFlag = X86II::MO_GOTOFF;
8189 else if (Subtarget->isPICStyleStubPIC())
8190 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8192 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8194 CP->getOffset(), OpFlag);
8196 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8197 // With PIC, the address is actually $g + Offset.
8199 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8200 DAG.getNode(X86ISD::GlobalBaseReg,
8201 SDLoc(), getPointerTy()),
8208 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8209 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8211 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8213 unsigned char OpFlag = 0;
8214 unsigned WrapperKind = X86ISD::Wrapper;
8215 CodeModel::Model M = getTargetMachine().getCodeModel();
8217 if (Subtarget->isPICStyleRIPRel() &&
8218 (M == CodeModel::Small || M == CodeModel::Kernel))
8219 WrapperKind = X86ISD::WrapperRIP;
8220 else if (Subtarget->isPICStyleGOT())
8221 OpFlag = X86II::MO_GOTOFF;
8222 else if (Subtarget->isPICStyleStubPIC())
8223 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8225 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8228 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8230 // With PIC, the address is actually $g + Offset.
8232 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8233 DAG.getNode(X86ISD::GlobalBaseReg,
8234 SDLoc(), getPointerTy()),
8241 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8242 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8244 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8246 unsigned char OpFlag = 0;
8247 unsigned WrapperKind = X86ISD::Wrapper;
8248 CodeModel::Model M = getTargetMachine().getCodeModel();
8250 if (Subtarget->isPICStyleRIPRel() &&
8251 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8252 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8253 OpFlag = X86II::MO_GOTPCREL;
8254 WrapperKind = X86ISD::WrapperRIP;
8255 } else if (Subtarget->isPICStyleGOT()) {
8256 OpFlag = X86II::MO_GOT;
8257 } else if (Subtarget->isPICStyleStubPIC()) {
8258 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8259 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8260 OpFlag = X86II::MO_DARWIN_NONLAZY;
8263 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8266 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8268 // With PIC, the address is actually $g + Offset.
8269 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8270 !Subtarget->is64Bit()) {
8271 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8272 DAG.getNode(X86ISD::GlobalBaseReg,
8273 SDLoc(), getPointerTy()),
8277 // For symbols that require a load from a stub to get the address, emit the
8279 if (isGlobalStubReference(OpFlag))
8280 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8281 MachinePointerInfo::getGOT(), false, false, false, 0);
8287 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8288 // Create the TargetBlockAddressAddress node.
8289 unsigned char OpFlags =
8290 Subtarget->ClassifyBlockAddressReference();
8291 CodeModel::Model M = getTargetMachine().getCodeModel();
8292 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8293 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8295 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8298 if (Subtarget->isPICStyleRIPRel() &&
8299 (M == CodeModel::Small || M == CodeModel::Kernel))
8300 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8302 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8304 // With PIC, the address is actually $g + Offset.
8305 if (isGlobalRelativeToPICBase(OpFlags)) {
8306 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8307 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8315 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8316 int64_t Offset, SelectionDAG &DAG) const {
8317 // Create the TargetGlobalAddress node, folding in the constant
8318 // offset if it is legal.
8319 unsigned char OpFlags =
8320 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8321 CodeModel::Model M = getTargetMachine().getCodeModel();
8323 if (OpFlags == X86II::MO_NO_FLAG &&
8324 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8325 // A direct static reference to a global.
8326 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8329 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8332 if (Subtarget->isPICStyleRIPRel() &&
8333 (M == CodeModel::Small || M == CodeModel::Kernel))
8334 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8336 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8338 // With PIC, the address is actually $g + Offset.
8339 if (isGlobalRelativeToPICBase(OpFlags)) {
8340 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8341 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8345 // For globals that require a load from a stub to get the address, emit the
8347 if (isGlobalStubReference(OpFlags))
8348 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8349 MachinePointerInfo::getGOT(), false, false, false, 0);
8351 // If there was a non-zero offset that we didn't fold, create an explicit
8354 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8355 DAG.getConstant(Offset, getPointerTy()));
8361 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8362 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8363 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8364 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8368 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8369 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8370 unsigned char OperandFlags, bool LocalDynamic = false) {
8371 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8372 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8374 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8375 GA->getValueType(0),
8379 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8383 SDValue Ops[] = { Chain, TGA, *InFlag };
8384 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8386 SDValue Ops[] = { Chain, TGA };
8387 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8390 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8391 MFI->setAdjustsStack(true);
8393 SDValue Flag = Chain.getValue(1);
8394 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8397 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8399 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8402 SDLoc dl(GA); // ? function entry point might be better
8403 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8404 DAG.getNode(X86ISD::GlobalBaseReg,
8405 SDLoc(), PtrVT), InFlag);
8406 InFlag = Chain.getValue(1);
8408 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8411 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8413 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8415 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8416 X86::RAX, X86II::MO_TLSGD);
8419 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8425 // Get the start address of the TLS block for this module.
8426 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8427 .getInfo<X86MachineFunctionInfo>();
8428 MFI->incNumLocalDynamicTLSAccesses();
8432 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8433 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8436 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8437 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8438 InFlag = Chain.getValue(1);
8439 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8440 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8443 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8447 unsigned char OperandFlags = X86II::MO_DTPOFF;
8448 unsigned WrapperKind = X86ISD::Wrapper;
8449 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8450 GA->getValueType(0),
8451 GA->getOffset(), OperandFlags);
8452 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8454 // Add x@dtpoff with the base.
8455 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8458 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8459 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8460 const EVT PtrVT, TLSModel::Model model,
8461 bool is64Bit, bool isPIC) {
8464 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8465 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8466 is64Bit ? 257 : 256));
8468 SDValue ThreadPointer =
8469 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8470 MachinePointerInfo(Ptr), false, false, false, 0);
8472 unsigned char OperandFlags = 0;
8473 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8475 unsigned WrapperKind = X86ISD::Wrapper;
8476 if (model == TLSModel::LocalExec) {
8477 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8478 } else if (model == TLSModel::InitialExec) {
8480 OperandFlags = X86II::MO_GOTTPOFF;
8481 WrapperKind = X86ISD::WrapperRIP;
8483 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8486 llvm_unreachable("Unexpected model");
8489 // emit "addl x@ntpoff,%eax" (local exec)
8490 // or "addl x@indntpoff,%eax" (initial exec)
8491 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8493 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8494 GA->getOffset(), OperandFlags);
8495 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8497 if (model == TLSModel::InitialExec) {
8498 if (isPIC && !is64Bit) {
8499 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8500 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8504 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8505 MachinePointerInfo::getGOT(), false, false, false, 0);
8508 // The address of the thread local variable is the add of the thread
8509 // pointer with the offset of the variable.
8510 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8514 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8516 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8517 const GlobalValue *GV = GA->getGlobal();
8519 if (Subtarget->isTargetELF()) {
8520 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8523 case TLSModel::GeneralDynamic:
8524 if (Subtarget->is64Bit())
8525 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8526 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8527 case TLSModel::LocalDynamic:
8528 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8529 Subtarget->is64Bit());
8530 case TLSModel::InitialExec:
8531 case TLSModel::LocalExec:
8532 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8533 Subtarget->is64Bit(),
8534 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8536 llvm_unreachable("Unknown TLS model.");
8539 if (Subtarget->isTargetDarwin()) {
8540 // Darwin only has one model of TLS. Lower to that.
8541 unsigned char OpFlag = 0;
8542 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8543 X86ISD::WrapperRIP : X86ISD::Wrapper;
8545 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8547 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8548 !Subtarget->is64Bit();
8550 OpFlag = X86II::MO_TLVP_PIC_BASE;
8552 OpFlag = X86II::MO_TLVP;
8554 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8555 GA->getValueType(0),
8556 GA->getOffset(), OpFlag);
8557 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8559 // With PIC32, the address is actually $g + Offset.
8561 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8562 DAG.getNode(X86ISD::GlobalBaseReg,
8563 SDLoc(), getPointerTy()),
8566 // Lowering the machine isd will make sure everything is in the right
8568 SDValue Chain = DAG.getEntryNode();
8569 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8570 SDValue Args[] = { Chain, Offset };
8571 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8573 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8574 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8575 MFI->setAdjustsStack(true);
8577 // And our return value (tls address) is in the standard call return value
8579 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8580 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8584 if (Subtarget->isTargetKnownWindowsMSVC() ||
8585 Subtarget->isTargetWindowsGNU()) {
8586 // Just use the implicit TLS architecture
8587 // Need to generate someting similar to:
8588 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8590 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8591 // mov rcx, qword [rdx+rcx*8]
8592 // mov eax, .tls$:tlsvar
8593 // [rax+rcx] contains the address
8594 // Windows 64bit: gs:0x58
8595 // Windows 32bit: fs:__tls_array
8597 // If GV is an alias then use the aliasee for determining
8598 // thread-localness.
8599 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8600 GV = GA->getAliasedGlobal();
8602 SDValue Chain = DAG.getEntryNode();
8604 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8605 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8606 // use its literal value of 0x2C.
8607 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8608 ? Type::getInt8PtrTy(*DAG.getContext(),
8610 : Type::getInt32PtrTy(*DAG.getContext(),
8614 Subtarget->is64Bit()
8615 ? DAG.getIntPtrConstant(0x58)
8616 : (Subtarget->isTargetWindowsGNU()
8617 ? DAG.getIntPtrConstant(0x2C)
8618 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8620 SDValue ThreadPointer =
8621 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8622 MachinePointerInfo(Ptr), false, false, false, 0);
8624 // Load the _tls_index variable
8625 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8626 if (Subtarget->is64Bit())
8627 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8628 IDX, MachinePointerInfo(), MVT::i32,
8631 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8632 false, false, false, 0);
8634 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8636 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8638 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8639 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8640 false, false, false, 0);
8642 // Get the offset of start of .tls section
8643 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8644 GA->getValueType(0),
8645 GA->getOffset(), X86II::MO_SECREL);
8646 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8648 // The address of the thread local variable is the add of the thread
8649 // pointer with the offset of the variable.
8650 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8653 llvm_unreachable("TLS not implemented for this target.");
8656 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8657 /// and take a 2 x i32 value to shift plus a shift amount.
8658 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8659 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8660 MVT VT = Op.getSimpleValueType();
8661 unsigned VTBits = VT.getSizeInBits();
8663 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8664 SDValue ShOpLo = Op.getOperand(0);
8665 SDValue ShOpHi = Op.getOperand(1);
8666 SDValue ShAmt = Op.getOperand(2);
8667 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8668 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8670 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8671 DAG.getConstant(VTBits - 1, MVT::i8));
8672 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8673 DAG.getConstant(VTBits - 1, MVT::i8))
8674 : DAG.getConstant(0, VT);
8677 if (Op.getOpcode() == ISD::SHL_PARTS) {
8678 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8679 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8681 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8682 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8685 // If the shift amount is larger or equal than the width of a part we can't
8686 // rely on the results of shld/shrd. Insert a test and select the appropriate
8687 // values for large shift amounts.
8688 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8689 DAG.getConstant(VTBits, MVT::i8));
8690 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8691 AndNode, DAG.getConstant(0, MVT::i8));
8694 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8695 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8696 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8698 if (Op.getOpcode() == ISD::SHL_PARTS) {
8699 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8700 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8702 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8703 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8706 SDValue Ops[2] = { Lo, Hi };
8707 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8710 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8711 SelectionDAG &DAG) const {
8712 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8714 if (SrcVT.isVector())
8717 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8718 "Unknown SINT_TO_FP to lower!");
8720 // These are really Legal; return the operand so the caller accepts it as
8722 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8724 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8725 Subtarget->is64Bit()) {
8730 unsigned Size = SrcVT.getSizeInBits()/8;
8731 MachineFunction &MF = DAG.getMachineFunction();
8732 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8733 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8734 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8736 MachinePointerInfo::getFixedStack(SSFI),
8738 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8741 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8743 SelectionDAG &DAG) const {
8747 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8749 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8751 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8753 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8755 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8756 MachineMemOperand *MMO;
8758 int SSFI = FI->getIndex();
8760 DAG.getMachineFunction()
8761 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8762 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8764 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8765 StackSlot = StackSlot.getOperand(1);
8767 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8768 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8770 Tys, Ops, array_lengthof(Ops),
8774 Chain = Result.getValue(1);
8775 SDValue InFlag = Result.getValue(2);
8777 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8778 // shouldn't be necessary except that RFP cannot be live across
8779 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8780 MachineFunction &MF = DAG.getMachineFunction();
8781 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8782 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8783 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8784 Tys = DAG.getVTList(MVT::Other);
8786 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8788 MachineMemOperand *MMO =
8789 DAG.getMachineFunction()
8790 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8791 MachineMemOperand::MOStore, SSFISize, SSFISize);
8793 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8794 Ops, array_lengthof(Ops),
8795 Op.getValueType(), MMO);
8796 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8797 MachinePointerInfo::getFixedStack(SSFI),
8798 false, false, false, 0);
8804 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8805 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8806 SelectionDAG &DAG) const {
8807 // This algorithm is not obvious. Here it is what we're trying to output:
8810 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8811 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8815 pshufd $0x4e, %xmm0, %xmm1
8821 LLVMContext *Context = DAG.getContext();
8823 // Build some magic constants.
8824 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8825 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8826 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8828 SmallVector<Constant*,2> CV1;
8830 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8831 APInt(64, 0x4330000000000000ULL))));
8833 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8834 APInt(64, 0x4530000000000000ULL))));
8835 Constant *C1 = ConstantVector::get(CV1);
8836 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8838 // Load the 64-bit value into an XMM register.
8839 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8841 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8842 MachinePointerInfo::getConstantPool(),
8843 false, false, false, 16);
8844 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8845 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8848 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8849 MachinePointerInfo::getConstantPool(),
8850 false, false, false, 16);
8851 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8852 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8855 if (Subtarget->hasSSE3()) {
8856 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8857 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8859 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8860 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8862 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8863 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8867 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8868 DAG.getIntPtrConstant(0));
8871 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8872 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8873 SelectionDAG &DAG) const {
8875 // FP constant to bias correct the final result.
8876 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8879 // Load the 32-bit value into an XMM register.
8880 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8883 // Zero out the upper parts of the register.
8884 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8886 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8887 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8888 DAG.getIntPtrConstant(0));
8890 // Or the load with the bias.
8891 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8892 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8893 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8895 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8896 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8897 MVT::v2f64, Bias)));
8898 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8899 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8900 DAG.getIntPtrConstant(0));
8902 // Subtract the bias.
8903 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8905 // Handle final rounding.
8906 EVT DestVT = Op.getValueType();
8908 if (DestVT.bitsLT(MVT::f64))
8909 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8910 DAG.getIntPtrConstant(0));
8911 if (DestVT.bitsGT(MVT::f64))
8912 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8914 // Handle final rounding.
8918 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8919 SelectionDAG &DAG) const {
8920 SDValue N0 = Op.getOperand(0);
8921 MVT SVT = N0.getSimpleValueType();
8924 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8925 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8926 "Custom UINT_TO_FP is not supported!");
8928 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8929 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8930 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8933 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8934 SelectionDAG &DAG) const {
8935 SDValue N0 = Op.getOperand(0);
8938 if (Op.getValueType().isVector())
8939 return lowerUINT_TO_FP_vec(Op, DAG);
8941 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8942 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8943 // the optimization here.
8944 if (DAG.SignBitIsZero(N0))
8945 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8947 MVT SrcVT = N0.getSimpleValueType();
8948 MVT DstVT = Op.getSimpleValueType();
8949 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8950 return LowerUINT_TO_FP_i64(Op, DAG);
8951 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8952 return LowerUINT_TO_FP_i32(Op, DAG);
8953 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8956 // Make a 64-bit buffer, and use it to build an FILD.
8957 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8958 if (SrcVT == MVT::i32) {
8959 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8960 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8961 getPointerTy(), StackSlot, WordOff);
8962 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8963 StackSlot, MachinePointerInfo(),
8965 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8966 OffsetSlot, MachinePointerInfo(),
8968 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8972 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8973 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8974 StackSlot, MachinePointerInfo(),
8976 // For i64 source, we need to add the appropriate power of 2 if the input
8977 // was negative. This is the same as the optimization in
8978 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8979 // we must be careful to do the computation in x87 extended precision, not
8980 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8981 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8982 MachineMemOperand *MMO =
8983 DAG.getMachineFunction()
8984 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8985 MachineMemOperand::MOLoad, 8, 8);
8987 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8988 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8989 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8990 array_lengthof(Ops), MVT::i64, MMO);
8992 APInt FF(32, 0x5F800000ULL);
8994 // Check whether the sign bit is set.
8995 SDValue SignSet = DAG.getSetCC(dl,
8996 getSetCCResultType(*DAG.getContext(), MVT::i64),
8997 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9000 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9001 SDValue FudgePtr = DAG.getConstantPool(
9002 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9005 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9006 SDValue Zero = DAG.getIntPtrConstant(0);
9007 SDValue Four = DAG.getIntPtrConstant(4);
9008 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9010 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9012 // Load the value out, extending it from f32 to f80.
9013 // FIXME: Avoid the extend by constructing the right constant pool?
9014 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9015 FudgePtr, MachinePointerInfo::getConstantPool(),
9016 MVT::f32, false, false, 4);
9017 // Extend everything to 80 bits to force it to be done on x87.
9018 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9019 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9022 std::pair<SDValue,SDValue>
9023 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9024 bool IsSigned, bool IsReplace) const {
9027 EVT DstTy = Op.getValueType();
9029 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9030 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9034 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9035 DstTy.getSimpleVT() >= MVT::i16 &&
9036 "Unknown FP_TO_INT to lower!");
9038 // These are really Legal.
9039 if (DstTy == MVT::i32 &&
9040 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9041 return std::make_pair(SDValue(), SDValue());
9042 if (Subtarget->is64Bit() &&
9043 DstTy == MVT::i64 &&
9044 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9045 return std::make_pair(SDValue(), SDValue());
9047 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9048 // stack slot, or into the FTOL runtime function.
9049 MachineFunction &MF = DAG.getMachineFunction();
9050 unsigned MemSize = DstTy.getSizeInBits()/8;
9051 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9052 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9055 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9056 Opc = X86ISD::WIN_FTOL;
9058 switch (DstTy.getSimpleVT().SimpleTy) {
9059 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9060 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9061 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9062 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9065 SDValue Chain = DAG.getEntryNode();
9066 SDValue Value = Op.getOperand(0);
9067 EVT TheVT = Op.getOperand(0).getValueType();
9068 // FIXME This causes a redundant load/store if the SSE-class value is already
9069 // in memory, such as if it is on the callstack.
9070 if (isScalarFPTypeInSSEReg(TheVT)) {
9071 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9072 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9073 MachinePointerInfo::getFixedStack(SSFI),
9075 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9077 Chain, StackSlot, DAG.getValueType(TheVT)
9080 MachineMemOperand *MMO =
9081 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9082 MachineMemOperand::MOLoad, MemSize, MemSize);
9083 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9084 array_lengthof(Ops), DstTy, MMO);
9085 Chain = Value.getValue(1);
9086 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9087 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9090 MachineMemOperand *MMO =
9091 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9092 MachineMemOperand::MOStore, MemSize, MemSize);
9094 if (Opc != X86ISD::WIN_FTOL) {
9095 // Build the FP_TO_INT*_IN_MEM
9096 SDValue Ops[] = { Chain, Value, StackSlot };
9097 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9098 Ops, array_lengthof(Ops), DstTy,
9100 return std::make_pair(FIST, StackSlot);
9102 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9103 DAG.getVTList(MVT::Other, MVT::Glue),
9105 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9106 MVT::i32, ftol.getValue(1));
9107 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9108 MVT::i32, eax.getValue(2));
9109 SDValue Ops[] = { eax, edx };
9110 SDValue pair = IsReplace
9111 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9112 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9113 return std::make_pair(pair, SDValue());
9117 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9118 const X86Subtarget *Subtarget) {
9119 MVT VT = Op->getSimpleValueType(0);
9120 SDValue In = Op->getOperand(0);
9121 MVT InVT = In.getSimpleValueType();
9124 // Optimize vectors in AVX mode:
9127 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9128 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9129 // Concat upper and lower parts.
9132 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9133 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9134 // Concat upper and lower parts.
9137 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9138 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9139 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9142 if (Subtarget->hasInt256())
9143 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9145 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9146 SDValue Undef = DAG.getUNDEF(InVT);
9147 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9148 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9149 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9151 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9152 VT.getVectorNumElements()/2);
9154 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9155 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9157 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9160 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9161 SelectionDAG &DAG) {
9162 MVT VT = Op->getSimpleValueType(0);
9163 SDValue In = Op->getOperand(0);
9164 MVT InVT = In.getSimpleValueType();
9166 unsigned int NumElts = VT.getVectorNumElements();
9167 if (NumElts != 8 && NumElts != 16)
9170 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9171 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9173 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9174 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9175 // Now we have only mask extension
9176 assert(InVT.getVectorElementType() == MVT::i1);
9177 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9178 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9179 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9180 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9181 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9182 MachinePointerInfo::getConstantPool(),
9183 false, false, false, Alignment);
9185 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9186 if (VT.is512BitVector())
9188 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9191 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9192 SelectionDAG &DAG) {
9193 if (Subtarget->hasFp256()) {
9194 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9202 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9203 SelectionDAG &DAG) {
9205 MVT VT = Op.getSimpleValueType();
9206 SDValue In = Op.getOperand(0);
9207 MVT SVT = In.getSimpleValueType();
9209 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9210 return LowerZERO_EXTEND_AVX512(Op, DAG);
9212 if (Subtarget->hasFp256()) {
9213 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9218 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9219 VT.getVectorNumElements() != SVT.getVectorNumElements());
9223 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9225 MVT VT = Op.getSimpleValueType();
9226 SDValue In = Op.getOperand(0);
9227 MVT InVT = In.getSimpleValueType();
9229 if (VT == MVT::i1) {
9230 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9231 "Invalid scalar TRUNCATE operation");
9232 if (InVT == MVT::i32)
9234 if (InVT.getSizeInBits() == 64)
9235 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9236 else if (InVT.getSizeInBits() < 32)
9237 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9238 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9240 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9241 "Invalid TRUNCATE operation");
9243 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9244 if (VT.getVectorElementType().getSizeInBits() >=8)
9245 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9247 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9248 unsigned NumElts = InVT.getVectorNumElements();
9249 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9250 if (InVT.getSizeInBits() < 512) {
9251 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9252 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9256 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9257 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9258 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9259 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9260 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9261 MachinePointerInfo::getConstantPool(),
9262 false, false, false, Alignment);
9263 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9264 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9265 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9268 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9269 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9270 if (Subtarget->hasInt256()) {
9271 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9272 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9273 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9275 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9276 DAG.getIntPtrConstant(0));
9279 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9280 DAG.getIntPtrConstant(0));
9281 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9282 DAG.getIntPtrConstant(2));
9283 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9284 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9285 static const int ShufMask[] = {0, 2, 4, 6};
9286 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9289 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9290 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9291 if (Subtarget->hasInt256()) {
9292 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9294 SmallVector<SDValue,32> pshufbMask;
9295 for (unsigned i = 0; i < 2; ++i) {
9296 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9297 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9298 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9299 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9300 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9301 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9302 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9303 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9304 for (unsigned j = 0; j < 8; ++j)
9305 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9307 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9308 &pshufbMask[0], 32);
9309 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9310 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9312 static const int ShufMask[] = {0, 2, -1, -1};
9313 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9315 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9316 DAG.getIntPtrConstant(0));
9317 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9320 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9321 DAG.getIntPtrConstant(0));
9323 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9324 DAG.getIntPtrConstant(4));
9326 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9327 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9330 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9331 -1, -1, -1, -1, -1, -1, -1, -1};
9333 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9334 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9335 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9337 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9338 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9340 // The MOVLHPS Mask:
9341 static const int ShufMask2[] = {0, 1, 4, 5};
9342 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9343 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9346 // Handle truncation of V256 to V128 using shuffles.
9347 if (!VT.is128BitVector() || !InVT.is256BitVector())
9350 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9352 unsigned NumElems = VT.getVectorNumElements();
9353 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9355 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9356 // Prepare truncation shuffle mask
9357 for (unsigned i = 0; i != NumElems; ++i)
9359 SDValue V = DAG.getVectorShuffle(NVT, DL,
9360 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9361 DAG.getUNDEF(NVT), &MaskVec[0]);
9362 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9363 DAG.getIntPtrConstant(0));
9366 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9367 SelectionDAG &DAG) const {
9368 assert(!Op.getSimpleValueType().isVector());
9370 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9371 /*IsSigned=*/ true, /*IsReplace=*/ false);
9372 SDValue FIST = Vals.first, StackSlot = Vals.second;
9373 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9374 if (FIST.getNode() == 0) return Op;
9376 if (StackSlot.getNode())
9378 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9379 FIST, StackSlot, MachinePointerInfo(),
9380 false, false, false, 0);
9382 // The node is the result.
9386 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9387 SelectionDAG &DAG) const {
9388 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9389 /*IsSigned=*/ false, /*IsReplace=*/ false);
9390 SDValue FIST = Vals.first, StackSlot = Vals.second;
9391 assert(FIST.getNode() && "Unexpected failure");
9393 if (StackSlot.getNode())
9395 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9396 FIST, StackSlot, MachinePointerInfo(),
9397 false, false, false, 0);
9399 // The node is the result.
9403 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9405 MVT VT = Op.getSimpleValueType();
9406 SDValue In = Op.getOperand(0);
9407 MVT SVT = In.getSimpleValueType();
9409 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9411 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9412 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9413 In, DAG.getUNDEF(SVT)));
9416 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9417 LLVMContext *Context = DAG.getContext();
9419 MVT VT = Op.getSimpleValueType();
9421 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9422 if (VT.isVector()) {
9423 EltVT = VT.getVectorElementType();
9424 NumElts = VT.getVectorNumElements();
9427 if (EltVT == MVT::f64)
9428 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9429 APInt(64, ~(1ULL << 63))));
9431 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9432 APInt(32, ~(1U << 31))));
9433 C = ConstantVector::getSplat(NumElts, C);
9434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9435 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9436 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9437 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9438 MachinePointerInfo::getConstantPool(),
9439 false, false, false, Alignment);
9440 if (VT.isVector()) {
9441 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9442 return DAG.getNode(ISD::BITCAST, dl, VT,
9443 DAG.getNode(ISD::AND, dl, ANDVT,
9444 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9446 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9448 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9451 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9452 LLVMContext *Context = DAG.getContext();
9454 MVT VT = Op.getSimpleValueType();
9456 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9457 if (VT.isVector()) {
9458 EltVT = VT.getVectorElementType();
9459 NumElts = VT.getVectorNumElements();
9462 if (EltVT == MVT::f64)
9463 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9464 APInt(64, 1ULL << 63)));
9466 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9467 APInt(32, 1U << 31)));
9468 C = ConstantVector::getSplat(NumElts, C);
9469 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9470 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9471 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9472 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9473 MachinePointerInfo::getConstantPool(),
9474 false, false, false, Alignment);
9475 if (VT.isVector()) {
9476 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9477 return DAG.getNode(ISD::BITCAST, dl, VT,
9478 DAG.getNode(ISD::XOR, dl, XORVT,
9479 DAG.getNode(ISD::BITCAST, dl, XORVT,
9481 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9484 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9487 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9488 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9489 LLVMContext *Context = DAG.getContext();
9490 SDValue Op0 = Op.getOperand(0);
9491 SDValue Op1 = Op.getOperand(1);
9493 MVT VT = Op.getSimpleValueType();
9494 MVT SrcVT = Op1.getSimpleValueType();
9496 // If second operand is smaller, extend it first.
9497 if (SrcVT.bitsLT(VT)) {
9498 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9501 // And if it is bigger, shrink it first.
9502 if (SrcVT.bitsGT(VT)) {
9503 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9507 // At this point the operands and the result should have the same
9508 // type, and that won't be f80 since that is not custom lowered.
9510 // First get the sign bit of second operand.
9511 SmallVector<Constant*,4> CV;
9512 if (SrcVT == MVT::f64) {
9513 const fltSemantics &Sem = APFloat::IEEEdouble;
9514 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9515 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9517 const fltSemantics &Sem = APFloat::IEEEsingle;
9518 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9519 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9520 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9521 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9523 Constant *C = ConstantVector::get(CV);
9524 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9525 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9526 MachinePointerInfo::getConstantPool(),
9527 false, false, false, 16);
9528 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9530 // Shift sign bit right or left if the two operands have different types.
9531 if (SrcVT.bitsGT(VT)) {
9532 // Op0 is MVT::f32, Op1 is MVT::f64.
9533 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9534 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9535 DAG.getConstant(32, MVT::i32));
9536 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9537 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9538 DAG.getIntPtrConstant(0));
9541 // Clear first operand sign bit.
9543 if (VT == MVT::f64) {
9544 const fltSemantics &Sem = APFloat::IEEEdouble;
9545 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9546 APInt(64, ~(1ULL << 63)))));
9547 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9549 const fltSemantics &Sem = APFloat::IEEEsingle;
9550 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9551 APInt(32, ~(1U << 31)))));
9552 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9553 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9554 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9556 C = ConstantVector::get(CV);
9557 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9558 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9559 MachinePointerInfo::getConstantPool(),
9560 false, false, false, 16);
9561 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9563 // Or the value with the sign bit.
9564 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9567 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9568 SDValue N0 = Op.getOperand(0);
9570 MVT VT = Op.getSimpleValueType();
9572 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9573 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9574 DAG.getConstant(1, VT));
9575 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9578 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9580 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9581 SelectionDAG &DAG) {
9582 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9584 if (!Subtarget->hasSSE41())
9587 if (!Op->hasOneUse())
9590 SDNode *N = Op.getNode();
9593 SmallVector<SDValue, 8> Opnds;
9594 DenseMap<SDValue, unsigned> VecInMap;
9595 SmallVector<SDValue, 8> VecIns;
9596 EVT VT = MVT::Other;
9598 // Recognize a special case where a vector is casted into wide integer to
9600 Opnds.push_back(N->getOperand(0));
9601 Opnds.push_back(N->getOperand(1));
9603 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9604 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9605 // BFS traverse all OR'd operands.
9606 if (I->getOpcode() == ISD::OR) {
9607 Opnds.push_back(I->getOperand(0));
9608 Opnds.push_back(I->getOperand(1));
9609 // Re-evaluate the number of nodes to be traversed.
9610 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9614 // Quit if a non-EXTRACT_VECTOR_ELT
9615 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9618 // Quit if without a constant index.
9619 SDValue Idx = I->getOperand(1);
9620 if (!isa<ConstantSDNode>(Idx))
9623 SDValue ExtractedFromVec = I->getOperand(0);
9624 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9625 if (M == VecInMap.end()) {
9626 VT = ExtractedFromVec.getValueType();
9627 // Quit if not 128/256-bit vector.
9628 if (!VT.is128BitVector() && !VT.is256BitVector())
9630 // Quit if not the same type.
9631 if (VecInMap.begin() != VecInMap.end() &&
9632 VT != VecInMap.begin()->first.getValueType())
9634 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9635 VecIns.push_back(ExtractedFromVec);
9637 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9640 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9641 "Not extracted from 128-/256-bit vector.");
9643 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9645 for (DenseMap<SDValue, unsigned>::const_iterator
9646 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9647 // Quit if not all elements are used.
9648 if (I->second != FullMask)
9652 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9654 // Cast all vectors into TestVT for PTEST.
9655 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9656 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9658 // If more than one full vectors are evaluated, OR them first before PTEST.
9659 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9660 // Each iteration will OR 2 nodes and append the result until there is only
9661 // 1 node left, i.e. the final OR'd value of all vectors.
9662 SDValue LHS = VecIns[Slot];
9663 SDValue RHS = VecIns[Slot + 1];
9664 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9667 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9668 VecIns.back(), VecIns.back());
9671 /// \brief return true if \c Op has a use that doesn't just read flags.
9672 static bool hasNonFlagsUse(SDValue Op) {
9673 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9676 unsigned UOpNo = UI.getOperandNo();
9677 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9678 // Look pass truncate.
9679 UOpNo = User->use_begin().getOperandNo();
9680 User = *User->use_begin();
9683 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9684 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9690 /// Emit nodes that will be selected as "test Op0,Op0", or something
9692 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9693 SelectionDAG &DAG) const {
9694 if (Op.getValueType() == MVT::i1)
9695 // KORTEST instruction should be selected
9696 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9697 DAG.getConstant(0, Op.getValueType()));
9699 // CF and OF aren't always set the way we want. Determine which
9700 // of these we need.
9701 bool NeedCF = false;
9702 bool NeedOF = false;
9705 case X86::COND_A: case X86::COND_AE:
9706 case X86::COND_B: case X86::COND_BE:
9709 case X86::COND_G: case X86::COND_GE:
9710 case X86::COND_L: case X86::COND_LE:
9711 case X86::COND_O: case X86::COND_NO:
9715 // See if we can use the EFLAGS value from the operand instead of
9716 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9717 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9718 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9719 // Emit a CMP with 0, which is the TEST pattern.
9720 //if (Op.getValueType() == MVT::i1)
9721 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9722 // DAG.getConstant(0, MVT::i1));
9723 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9724 DAG.getConstant(0, Op.getValueType()));
9726 unsigned Opcode = 0;
9727 unsigned NumOperands = 0;
9729 // Truncate operations may prevent the merge of the SETCC instruction
9730 // and the arithmetic instruction before it. Attempt to truncate the operands
9731 // of the arithmetic instruction and use a reduced bit-width instruction.
9732 bool NeedTruncation = false;
9733 SDValue ArithOp = Op;
9734 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9735 SDValue Arith = Op->getOperand(0);
9736 // Both the trunc and the arithmetic op need to have one user each.
9737 if (Arith->hasOneUse())
9738 switch (Arith.getOpcode()) {
9745 NeedTruncation = true;
9751 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9752 // which may be the result of a CAST. We use the variable 'Op', which is the
9753 // non-casted variable when we check for possible users.
9754 switch (ArithOp.getOpcode()) {
9756 // Due to an isel shortcoming, be conservative if this add is likely to be
9757 // selected as part of a load-modify-store instruction. When the root node
9758 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9759 // uses of other nodes in the match, such as the ADD in this case. This
9760 // leads to the ADD being left around and reselected, with the result being
9761 // two adds in the output. Alas, even if none our users are stores, that
9762 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9763 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9764 // climbing the DAG back to the root, and it doesn't seem to be worth the
9766 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9767 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9768 if (UI->getOpcode() != ISD::CopyToReg &&
9769 UI->getOpcode() != ISD::SETCC &&
9770 UI->getOpcode() != ISD::STORE)
9773 if (ConstantSDNode *C =
9774 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9775 // An add of one will be selected as an INC.
9776 if (C->getAPIntValue() == 1) {
9777 Opcode = X86ISD::INC;
9782 // An add of negative one (subtract of one) will be selected as a DEC.
9783 if (C->getAPIntValue().isAllOnesValue()) {
9784 Opcode = X86ISD::DEC;
9790 // Otherwise use a regular EFLAGS-setting add.
9791 Opcode = X86ISD::ADD;
9796 // If we have a constant logical shift that's only used in a comparison
9797 // against zero turn it into an equivalent AND. This allows turning it into
9798 // a TEST instruction later.
9799 if (isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9800 EVT VT = Op.getValueType();
9801 unsigned BitWidth = VT.getSizeInBits();
9802 unsigned ShAmt = Op->getConstantOperandVal(1);
9803 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9805 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9806 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9807 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9808 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9810 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9811 DAG.getConstant(Mask, VT));
9812 DAG.ReplaceAllUsesWith(Op, New);
9818 // If the primary and result isn't used, don't bother using X86ISD::AND,
9819 // because a TEST instruction will be better.
9820 if (!hasNonFlagsUse(Op))
9826 // Due to the ISEL shortcoming noted above, be conservative if this op is
9827 // likely to be selected as part of a load-modify-store instruction.
9828 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9829 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9830 if (UI->getOpcode() == ISD::STORE)
9833 // Otherwise use a regular EFLAGS-setting instruction.
9834 switch (ArithOp.getOpcode()) {
9835 default: llvm_unreachable("unexpected operator!");
9836 case ISD::SUB: Opcode = X86ISD::SUB; break;
9837 case ISD::XOR: Opcode = X86ISD::XOR; break;
9838 case ISD::AND: Opcode = X86ISD::AND; break;
9840 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9841 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9842 if (EFLAGS.getNode())
9845 Opcode = X86ISD::OR;
9859 return SDValue(Op.getNode(), 1);
9865 // If we found that truncation is beneficial, perform the truncation and
9867 if (NeedTruncation) {
9868 EVT VT = Op.getValueType();
9869 SDValue WideVal = Op->getOperand(0);
9870 EVT WideVT = WideVal.getValueType();
9871 unsigned ConvertedOp = 0;
9872 // Use a target machine opcode to prevent further DAGCombine
9873 // optimizations that may separate the arithmetic operations
9874 // from the setcc node.
9875 switch (WideVal.getOpcode()) {
9877 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9878 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9879 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9880 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9881 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9885 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9886 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9887 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9888 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9889 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9895 // Emit a CMP with 0, which is the TEST pattern.
9896 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9897 DAG.getConstant(0, Op.getValueType()));
9899 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9900 SmallVector<SDValue, 4> Ops;
9901 for (unsigned i = 0; i != NumOperands; ++i)
9902 Ops.push_back(Op.getOperand(i));
9904 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9905 DAG.ReplaceAllUsesWith(Op, New);
9906 return SDValue(New.getNode(), 1);
9909 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9911 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9912 SDLoc dl, SelectionDAG &DAG) const {
9913 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9914 if (C->getAPIntValue() == 0)
9915 return EmitTest(Op0, X86CC, dl, DAG);
9917 if (Op0.getValueType() == MVT::i1)
9918 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9921 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9922 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9923 // Do the comparison at i32 if it's smaller, besides the Atom case.
9924 // This avoids subregister aliasing issues. Keep the smaller reference
9925 // if we're optimizing for size, however, as that'll allow better folding
9926 // of memory operations.
9927 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9928 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9929 AttributeSet::FunctionIndex, Attribute::MinSize) &&
9930 !Subtarget->isAtom()) {
9932 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9933 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9934 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9936 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9937 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9938 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9940 return SDValue(Sub.getNode(), 1);
9942 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9945 /// Convert a comparison if required by the subtarget.
9946 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9947 SelectionDAG &DAG) const {
9948 // If the subtarget does not support the FUCOMI instruction, floating-point
9949 // comparisons have to be converted.
9950 if (Subtarget->hasCMov() ||
9951 Cmp.getOpcode() != X86ISD::CMP ||
9952 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9953 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9956 // The instruction selector will select an FUCOM instruction instead of
9957 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9958 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9959 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9961 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9962 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9963 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9964 DAG.getConstant(8, MVT::i8));
9965 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9966 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9969 static bool isAllOnes(SDValue V) {
9970 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9971 return C && C->isAllOnesValue();
9974 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9975 /// if it's possible.
9976 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9977 SDLoc dl, SelectionDAG &DAG) const {
9978 SDValue Op0 = And.getOperand(0);
9979 SDValue Op1 = And.getOperand(1);
9980 if (Op0.getOpcode() == ISD::TRUNCATE)
9981 Op0 = Op0.getOperand(0);
9982 if (Op1.getOpcode() == ISD::TRUNCATE)
9983 Op1 = Op1.getOperand(0);
9986 if (Op1.getOpcode() == ISD::SHL)
9987 std::swap(Op0, Op1);
9988 if (Op0.getOpcode() == ISD::SHL) {
9989 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9990 if (And00C->getZExtValue() == 1) {
9991 // If we looked past a truncate, check that it's only truncating away
9993 unsigned BitWidth = Op0.getValueSizeInBits();
9994 unsigned AndBitWidth = And.getValueSizeInBits();
9995 if (BitWidth > AndBitWidth) {
9997 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9998 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10002 RHS = Op0.getOperand(1);
10004 } else if (Op1.getOpcode() == ISD::Constant) {
10005 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10006 uint64_t AndRHSVal = AndRHS->getZExtValue();
10007 SDValue AndLHS = Op0;
10009 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10010 LHS = AndLHS.getOperand(0);
10011 RHS = AndLHS.getOperand(1);
10014 // Use BT if the immediate can't be encoded in a TEST instruction.
10015 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10017 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10021 if (LHS.getNode()) {
10022 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10023 // instruction. Since the shift amount is in-range-or-undefined, we know
10024 // that doing a bittest on the i32 value is ok. We extend to i32 because
10025 // the encoding for the i16 version is larger than the i32 version.
10026 // Also promote i16 to i32 for performance / code size reason.
10027 if (LHS.getValueType() == MVT::i8 ||
10028 LHS.getValueType() == MVT::i16)
10029 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10031 // If the operand types disagree, extend the shift amount to match. Since
10032 // BT ignores high bits (like shifts) we can use anyextend.
10033 if (LHS.getValueType() != RHS.getValueType())
10034 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10036 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10037 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10038 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10039 DAG.getConstant(Cond, MVT::i8), BT);
10045 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10047 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10052 // SSE Condition code mapping:
10061 switch (SetCCOpcode) {
10062 default: llvm_unreachable("Unexpected SETCC condition");
10064 case ISD::SETEQ: SSECC = 0; break;
10066 case ISD::SETGT: Swap = true; // Fallthrough
10068 case ISD::SETOLT: SSECC = 1; break;
10070 case ISD::SETGE: Swap = true; // Fallthrough
10072 case ISD::SETOLE: SSECC = 2; break;
10073 case ISD::SETUO: SSECC = 3; break;
10075 case ISD::SETNE: SSECC = 4; break;
10076 case ISD::SETULE: Swap = true; // Fallthrough
10077 case ISD::SETUGE: SSECC = 5; break;
10078 case ISD::SETULT: Swap = true; // Fallthrough
10079 case ISD::SETUGT: SSECC = 6; break;
10080 case ISD::SETO: SSECC = 7; break;
10082 case ISD::SETONE: SSECC = 8; break;
10085 std::swap(Op0, Op1);
10090 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10091 // ones, and then concatenate the result back.
10092 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10093 MVT VT = Op.getSimpleValueType();
10095 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10096 "Unsupported value type for operation");
10098 unsigned NumElems = VT.getVectorNumElements();
10100 SDValue CC = Op.getOperand(2);
10102 // Extract the LHS vectors
10103 SDValue LHS = Op.getOperand(0);
10104 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10105 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10107 // Extract the RHS vectors
10108 SDValue RHS = Op.getOperand(1);
10109 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10110 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10112 // Issue the operation on the smaller types and concatenate the result back
10113 MVT EltVT = VT.getVectorElementType();
10114 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10115 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10116 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10117 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10120 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10121 const X86Subtarget *Subtarget) {
10122 SDValue Op0 = Op.getOperand(0);
10123 SDValue Op1 = Op.getOperand(1);
10124 SDValue CC = Op.getOperand(2);
10125 MVT VT = Op.getSimpleValueType();
10128 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10129 Op.getValueType().getScalarType() == MVT::i1 &&
10130 "Cannot set masked compare for this operation");
10132 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10134 bool Unsigned = false;
10137 switch (SetCCOpcode) {
10138 default: llvm_unreachable("Unexpected SETCC condition");
10139 case ISD::SETNE: SSECC = 4; break;
10140 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10141 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10142 case ISD::SETLT: Swap = true; //fall-through
10143 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10144 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10145 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10146 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10147 case ISD::SETULE: Unsigned = true; //fall-through
10148 case ISD::SETLE: SSECC = 2; break;
10152 std::swap(Op0, Op1);
10154 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10155 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10156 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10157 DAG.getConstant(SSECC, MVT::i8));
10160 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10161 /// operand \p Op1. If non-trivial (for example because it's not constant)
10162 /// return an empty value.
10163 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10165 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10169 MVT VT = Op1.getSimpleValueType();
10170 MVT EVT = VT.getVectorElementType();
10171 unsigned n = VT.getVectorNumElements();
10172 SmallVector<SDValue, 8> ULTOp1;
10174 for (unsigned i = 0; i < n; ++i) {
10175 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10176 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10179 // Avoid underflow.
10180 APInt Val = Elt->getAPIntValue();
10184 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10187 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10190 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10191 SelectionDAG &DAG) {
10192 SDValue Op0 = Op.getOperand(0);
10193 SDValue Op1 = Op.getOperand(1);
10194 SDValue CC = Op.getOperand(2);
10195 MVT VT = Op.getSimpleValueType();
10196 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10197 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10202 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10203 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10206 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10207 unsigned Opc = X86ISD::CMPP;
10208 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10209 assert(VT.getVectorNumElements() <= 16);
10210 Opc = X86ISD::CMPM;
10212 // In the two special cases we can't handle, emit two comparisons.
10215 unsigned CombineOpc;
10216 if (SetCCOpcode == ISD::SETUEQ) {
10217 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10219 assert(SetCCOpcode == ISD::SETONE);
10220 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10223 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10224 DAG.getConstant(CC0, MVT::i8));
10225 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10226 DAG.getConstant(CC1, MVT::i8));
10227 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10229 // Handle all other FP comparisons here.
10230 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10231 DAG.getConstant(SSECC, MVT::i8));
10234 // Break 256-bit integer vector compare into smaller ones.
10235 if (VT.is256BitVector() && !Subtarget->hasInt256())
10236 return Lower256IntVSETCC(Op, DAG);
10238 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10239 EVT OpVT = Op1.getValueType();
10240 if (Subtarget->hasAVX512()) {
10241 if (Op1.getValueType().is512BitVector() ||
10242 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10243 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10245 // In AVX-512 architecture setcc returns mask with i1 elements,
10246 // But there is no compare instruction for i8 and i16 elements.
10247 // We are not talking about 512-bit operands in this case, these
10248 // types are illegal.
10250 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10251 OpVT.getVectorElementType().getSizeInBits() >= 8))
10252 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10253 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10256 // We are handling one of the integer comparisons here. Since SSE only has
10257 // GT and EQ comparisons for integer, swapping operands and multiple
10258 // operations may be required for some comparisons.
10260 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10261 bool Subus = false;
10263 switch (SetCCOpcode) {
10264 default: llvm_unreachable("Unexpected SETCC condition");
10265 case ISD::SETNE: Invert = true;
10266 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10267 case ISD::SETLT: Swap = true;
10268 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10269 case ISD::SETGE: Swap = true;
10270 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10271 Invert = true; break;
10272 case ISD::SETULT: Swap = true;
10273 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10274 FlipSigns = true; break;
10275 case ISD::SETUGE: Swap = true;
10276 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10277 FlipSigns = true; Invert = true; break;
10280 // Special case: Use min/max operations for SETULE/SETUGE
10281 MVT VET = VT.getVectorElementType();
10283 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10284 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10287 switch (SetCCOpcode) {
10289 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10290 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10293 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10296 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10297 if (!MinMax && hasSubus) {
10298 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10300 // t = psubus Op0, Op1
10301 // pcmpeq t, <0..0>
10302 switch (SetCCOpcode) {
10304 case ISD::SETULT: {
10305 // If the comparison is against a constant we can turn this into a
10306 // setule. With psubus, setule does not require a swap. This is
10307 // beneficial because the constant in the register is no longer
10308 // destructed as the destination so it can be hoisted out of a loop.
10309 // Only do this pre-AVX since vpcmp* is no longer destructive.
10310 if (Subtarget->hasAVX())
10312 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10313 if (ULEOp1.getNode()) {
10315 Subus = true; Invert = false; Swap = false;
10319 // Psubus is better than flip-sign because it requires no inversion.
10320 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10321 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10325 Opc = X86ISD::SUBUS;
10331 std::swap(Op0, Op1);
10333 // Check that the operation in question is available (most are plain SSE2,
10334 // but PCMPGTQ and PCMPEQQ have different requirements).
10335 if (VT == MVT::v2i64) {
10336 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10337 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10339 // First cast everything to the right type.
10340 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10341 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10343 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10344 // bits of the inputs before performing those operations. The lower
10345 // compare is always unsigned.
10348 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10350 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10351 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10352 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10353 Sign, Zero, Sign, Zero);
10355 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10356 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10358 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10359 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10360 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10362 // Create masks for only the low parts/high parts of the 64 bit integers.
10363 static const int MaskHi[] = { 1, 1, 3, 3 };
10364 static const int MaskLo[] = { 0, 0, 2, 2 };
10365 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10366 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10367 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10369 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10370 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10373 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10375 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10378 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10379 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10380 // pcmpeqd + pshufd + pand.
10381 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10383 // First cast everything to the right type.
10384 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10385 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10388 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10390 // Make sure the lower and upper halves are both all-ones.
10391 static const int Mask[] = { 1, 0, 3, 2 };
10392 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10393 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10396 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10398 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10402 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10403 // bits of the inputs before performing those operations.
10405 EVT EltVT = VT.getVectorElementType();
10406 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10407 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10408 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10411 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10413 // If the logical-not of the result is required, perform that now.
10415 Result = DAG.getNOT(dl, Result, VT);
10418 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10421 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10422 getZeroVector(VT, Subtarget, DAG, dl));
10427 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10429 MVT VT = Op.getSimpleValueType();
10431 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10433 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10434 && "SetCC type must be 8-bit or 1-bit integer");
10435 SDValue Op0 = Op.getOperand(0);
10436 SDValue Op1 = Op.getOperand(1);
10438 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10440 // Optimize to BT if possible.
10441 // Lower (X & (1 << N)) == 0 to BT(X, N).
10442 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10443 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10444 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10445 Op1.getOpcode() == ISD::Constant &&
10446 cast<ConstantSDNode>(Op1)->isNullValue() &&
10447 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10448 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10449 if (NewSetCC.getNode())
10453 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10455 if (Op1.getOpcode() == ISD::Constant &&
10456 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10457 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10458 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10460 // If the input is a setcc, then reuse the input setcc or use a new one with
10461 // the inverted condition.
10462 if (Op0.getOpcode() == X86ISD::SETCC) {
10463 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10464 bool Invert = (CC == ISD::SETNE) ^
10465 cast<ConstantSDNode>(Op1)->isNullValue();
10469 CCode = X86::GetOppositeBranchCondition(CCode);
10470 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10471 DAG.getConstant(CCode, MVT::i8),
10472 Op0.getOperand(1));
10474 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10478 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10479 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10480 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10482 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10483 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10486 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10487 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10488 if (X86CC == X86::COND_INVALID)
10491 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10492 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10493 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10494 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10496 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10500 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10501 static bool isX86LogicalCmp(SDValue Op) {
10502 unsigned Opc = Op.getNode()->getOpcode();
10503 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10504 Opc == X86ISD::SAHF)
10506 if (Op.getResNo() == 1 &&
10507 (Opc == X86ISD::ADD ||
10508 Opc == X86ISD::SUB ||
10509 Opc == X86ISD::ADC ||
10510 Opc == X86ISD::SBB ||
10511 Opc == X86ISD::SMUL ||
10512 Opc == X86ISD::UMUL ||
10513 Opc == X86ISD::INC ||
10514 Opc == X86ISD::DEC ||
10515 Opc == X86ISD::OR ||
10516 Opc == X86ISD::XOR ||
10517 Opc == X86ISD::AND))
10520 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10526 static bool isZero(SDValue V) {
10527 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10528 return C && C->isNullValue();
10531 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10532 if (V.getOpcode() != ISD::TRUNCATE)
10535 SDValue VOp0 = V.getOperand(0);
10536 unsigned InBits = VOp0.getValueSizeInBits();
10537 unsigned Bits = V.getValueSizeInBits();
10538 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10541 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10542 bool addTest = true;
10543 SDValue Cond = Op.getOperand(0);
10544 SDValue Op1 = Op.getOperand(1);
10545 SDValue Op2 = Op.getOperand(2);
10547 EVT VT = Op1.getValueType();
10550 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10551 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10552 // sequence later on.
10553 if (Cond.getOpcode() == ISD::SETCC &&
10554 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10555 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10556 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10557 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10558 int SSECC = translateX86FSETCC(
10559 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10562 if (Subtarget->hasAVX512()) {
10563 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10564 DAG.getConstant(SSECC, MVT::i8));
10565 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10567 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10568 DAG.getConstant(SSECC, MVT::i8));
10569 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10570 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10571 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10575 if (Cond.getOpcode() == ISD::SETCC) {
10576 SDValue NewCond = LowerSETCC(Cond, DAG);
10577 if (NewCond.getNode())
10581 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10582 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10583 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10584 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10585 if (Cond.getOpcode() == X86ISD::SETCC &&
10586 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10587 isZero(Cond.getOperand(1).getOperand(1))) {
10588 SDValue Cmp = Cond.getOperand(1);
10590 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10592 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10593 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10594 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10596 SDValue CmpOp0 = Cmp.getOperand(0);
10597 // Apply further optimizations for special cases
10598 // (select (x != 0), -1, 0) -> neg & sbb
10599 // (select (x == 0), 0, -1) -> neg & sbb
10600 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10601 if (YC->isNullValue() &&
10602 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10603 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10604 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10605 DAG.getConstant(0, CmpOp0.getValueType()),
10607 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10608 DAG.getConstant(X86::COND_B, MVT::i8),
10609 SDValue(Neg.getNode(), 1));
10613 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10614 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10615 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10617 SDValue Res = // Res = 0 or -1.
10618 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10619 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10621 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10622 Res = DAG.getNOT(DL, Res, Res.getValueType());
10624 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10625 if (N2C == 0 || !N2C->isNullValue())
10626 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10631 // Look past (and (setcc_carry (cmp ...)), 1).
10632 if (Cond.getOpcode() == ISD::AND &&
10633 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10634 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10635 if (C && C->getAPIntValue() == 1)
10636 Cond = Cond.getOperand(0);
10639 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10640 // setting operand in place of the X86ISD::SETCC.
10641 unsigned CondOpcode = Cond.getOpcode();
10642 if (CondOpcode == X86ISD::SETCC ||
10643 CondOpcode == X86ISD::SETCC_CARRY) {
10644 CC = Cond.getOperand(0);
10646 SDValue Cmp = Cond.getOperand(1);
10647 unsigned Opc = Cmp.getOpcode();
10648 MVT VT = Op.getSimpleValueType();
10650 bool IllegalFPCMov = false;
10651 if (VT.isFloatingPoint() && !VT.isVector() &&
10652 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10653 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10655 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10656 Opc == X86ISD::BT) { // FIXME
10660 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10661 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10662 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10663 Cond.getOperand(0).getValueType() != MVT::i8)) {
10664 SDValue LHS = Cond.getOperand(0);
10665 SDValue RHS = Cond.getOperand(1);
10666 unsigned X86Opcode;
10669 switch (CondOpcode) {
10670 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10671 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10672 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10673 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10674 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10675 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10676 default: llvm_unreachable("unexpected overflowing operator");
10678 if (CondOpcode == ISD::UMULO)
10679 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10682 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10684 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10686 if (CondOpcode == ISD::UMULO)
10687 Cond = X86Op.getValue(2);
10689 Cond = X86Op.getValue(1);
10691 CC = DAG.getConstant(X86Cond, MVT::i8);
10696 // Look pass the truncate if the high bits are known zero.
10697 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10698 Cond = Cond.getOperand(0);
10700 // We know the result of AND is compared against zero. Try to match
10702 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10703 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10704 if (NewSetCC.getNode()) {
10705 CC = NewSetCC.getOperand(0);
10706 Cond = NewSetCC.getOperand(1);
10713 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10714 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10717 // a < b ? -1 : 0 -> RES = ~setcc_carry
10718 // a < b ? 0 : -1 -> RES = setcc_carry
10719 // a >= b ? -1 : 0 -> RES = setcc_carry
10720 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10721 if (Cond.getOpcode() == X86ISD::SUB) {
10722 Cond = ConvertCmpIfNecessary(Cond, DAG);
10723 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10725 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10726 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10727 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10728 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10729 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10730 return DAG.getNOT(DL, Res, Res.getValueType());
10735 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10736 // widen the cmov and push the truncate through. This avoids introducing a new
10737 // branch during isel and doesn't add any extensions.
10738 if (Op.getValueType() == MVT::i8 &&
10739 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10740 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10741 if (T1.getValueType() == T2.getValueType() &&
10742 // Blacklist CopyFromReg to avoid partial register stalls.
10743 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10744 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10745 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10746 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10750 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10751 // condition is true.
10752 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10753 SDValue Ops[] = { Op2, Op1, CC, Cond };
10754 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10757 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10758 MVT VT = Op->getSimpleValueType(0);
10759 SDValue In = Op->getOperand(0);
10760 MVT InVT = In.getSimpleValueType();
10763 unsigned int NumElts = VT.getVectorNumElements();
10764 if (NumElts != 8 && NumElts != 16)
10767 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10768 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10771 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10773 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10774 Constant *C = ConstantInt::get(*DAG.getContext(),
10775 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10777 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10778 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10779 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10780 MachinePointerInfo::getConstantPool(),
10781 false, false, false, Alignment);
10782 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10783 if (VT.is512BitVector())
10785 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10788 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10789 SelectionDAG &DAG) {
10790 MVT VT = Op->getSimpleValueType(0);
10791 SDValue In = Op->getOperand(0);
10792 MVT InVT = In.getSimpleValueType();
10795 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10796 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10798 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10799 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10800 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10803 if (Subtarget->hasInt256())
10804 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10806 // Optimize vectors in AVX mode
10807 // Sign extend v8i16 to v8i32 and
10810 // Divide input vector into two parts
10811 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10812 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10813 // concat the vectors to original VT
10815 unsigned NumElems = InVT.getVectorNumElements();
10816 SDValue Undef = DAG.getUNDEF(InVT);
10818 SmallVector<int,8> ShufMask1(NumElems, -1);
10819 for (unsigned i = 0; i != NumElems/2; ++i)
10822 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10824 SmallVector<int,8> ShufMask2(NumElems, -1);
10825 for (unsigned i = 0; i != NumElems/2; ++i)
10826 ShufMask2[i] = i + NumElems/2;
10828 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10830 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10831 VT.getVectorNumElements()/2);
10833 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10834 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10836 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10839 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10840 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10841 // from the AND / OR.
10842 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10843 Opc = Op.getOpcode();
10844 if (Opc != ISD::OR && Opc != ISD::AND)
10846 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10847 Op.getOperand(0).hasOneUse() &&
10848 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10849 Op.getOperand(1).hasOneUse());
10852 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10853 // 1 and that the SETCC node has a single use.
10854 static bool isXor1OfSetCC(SDValue Op) {
10855 if (Op.getOpcode() != ISD::XOR)
10857 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10858 if (N1C && N1C->getAPIntValue() == 1) {
10859 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10860 Op.getOperand(0).hasOneUse();
10865 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10866 bool addTest = true;
10867 SDValue Chain = Op.getOperand(0);
10868 SDValue Cond = Op.getOperand(1);
10869 SDValue Dest = Op.getOperand(2);
10872 bool Inverted = false;
10874 if (Cond.getOpcode() == ISD::SETCC) {
10875 // Check for setcc([su]{add,sub,mul}o == 0).
10876 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10877 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10878 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10879 Cond.getOperand(0).getResNo() == 1 &&
10880 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10881 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10882 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10883 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10884 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10885 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10887 Cond = Cond.getOperand(0);
10889 SDValue NewCond = LowerSETCC(Cond, DAG);
10890 if (NewCond.getNode())
10895 // FIXME: LowerXALUO doesn't handle these!!
10896 else if (Cond.getOpcode() == X86ISD::ADD ||
10897 Cond.getOpcode() == X86ISD::SUB ||
10898 Cond.getOpcode() == X86ISD::SMUL ||
10899 Cond.getOpcode() == X86ISD::UMUL)
10900 Cond = LowerXALUO(Cond, DAG);
10903 // Look pass (and (setcc_carry (cmp ...)), 1).
10904 if (Cond.getOpcode() == ISD::AND &&
10905 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10906 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10907 if (C && C->getAPIntValue() == 1)
10908 Cond = Cond.getOperand(0);
10911 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10912 // setting operand in place of the X86ISD::SETCC.
10913 unsigned CondOpcode = Cond.getOpcode();
10914 if (CondOpcode == X86ISD::SETCC ||
10915 CondOpcode == X86ISD::SETCC_CARRY) {
10916 CC = Cond.getOperand(0);
10918 SDValue Cmp = Cond.getOperand(1);
10919 unsigned Opc = Cmp.getOpcode();
10920 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10921 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10925 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10929 // These can only come from an arithmetic instruction with overflow,
10930 // e.g. SADDO, UADDO.
10931 Cond = Cond.getNode()->getOperand(1);
10937 CondOpcode = Cond.getOpcode();
10938 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10939 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10940 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10941 Cond.getOperand(0).getValueType() != MVT::i8)) {
10942 SDValue LHS = Cond.getOperand(0);
10943 SDValue RHS = Cond.getOperand(1);
10944 unsigned X86Opcode;
10947 // Keep this in sync with LowerXALUO, otherwise we might create redundant
10948 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10950 switch (CondOpcode) {
10951 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10953 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10955 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10958 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10959 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10961 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10963 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10966 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10967 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10968 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10969 default: llvm_unreachable("unexpected overflowing operator");
10972 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10973 if (CondOpcode == ISD::UMULO)
10974 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10977 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10979 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10981 if (CondOpcode == ISD::UMULO)
10982 Cond = X86Op.getValue(2);
10984 Cond = X86Op.getValue(1);
10986 CC = DAG.getConstant(X86Cond, MVT::i8);
10990 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10991 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10992 if (CondOpc == ISD::OR) {
10993 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10994 // two branches instead of an explicit OR instruction with a
10996 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10997 isX86LogicalCmp(Cmp)) {
10998 CC = Cond.getOperand(0).getOperand(0);
10999 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11000 Chain, Dest, CC, Cmp);
11001 CC = Cond.getOperand(1).getOperand(0);
11005 } else { // ISD::AND
11006 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11007 // two branches instead of an explicit AND instruction with a
11008 // separate test. However, we only do this if this block doesn't
11009 // have a fall-through edge, because this requires an explicit
11010 // jmp when the condition is false.
11011 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11012 isX86LogicalCmp(Cmp) &&
11013 Op.getNode()->hasOneUse()) {
11014 X86::CondCode CCode =
11015 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11016 CCode = X86::GetOppositeBranchCondition(CCode);
11017 CC = DAG.getConstant(CCode, MVT::i8);
11018 SDNode *User = *Op.getNode()->use_begin();
11019 // Look for an unconditional branch following this conditional branch.
11020 // We need this because we need to reverse the successors in order
11021 // to implement FCMP_OEQ.
11022 if (User->getOpcode() == ISD::BR) {
11023 SDValue FalseBB = User->getOperand(1);
11025 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11026 assert(NewBR == User);
11030 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11031 Chain, Dest, CC, Cmp);
11032 X86::CondCode CCode =
11033 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11034 CCode = X86::GetOppositeBranchCondition(CCode);
11035 CC = DAG.getConstant(CCode, MVT::i8);
11041 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11042 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11043 // It should be transformed during dag combiner except when the condition
11044 // is set by a arithmetics with overflow node.
11045 X86::CondCode CCode =
11046 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11047 CCode = X86::GetOppositeBranchCondition(CCode);
11048 CC = DAG.getConstant(CCode, MVT::i8);
11049 Cond = Cond.getOperand(0).getOperand(1);
11051 } else if (Cond.getOpcode() == ISD::SETCC &&
11052 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11053 // For FCMP_OEQ, we can emit
11054 // two branches instead of an explicit AND instruction with a
11055 // separate test. However, we only do this if this block doesn't
11056 // have a fall-through edge, because this requires an explicit
11057 // jmp when the condition is false.
11058 if (Op.getNode()->hasOneUse()) {
11059 SDNode *User = *Op.getNode()->use_begin();
11060 // Look for an unconditional branch following this conditional branch.
11061 // We need this because we need to reverse the successors in order
11062 // to implement FCMP_OEQ.
11063 if (User->getOpcode() == ISD::BR) {
11064 SDValue FalseBB = User->getOperand(1);
11066 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11067 assert(NewBR == User);
11071 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11072 Cond.getOperand(0), Cond.getOperand(1));
11073 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11074 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11075 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11076 Chain, Dest, CC, Cmp);
11077 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11082 } else if (Cond.getOpcode() == ISD::SETCC &&
11083 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11084 // For FCMP_UNE, we can emit
11085 // two branches instead of an explicit AND instruction with a
11086 // separate test. However, we only do this if this block doesn't
11087 // have a fall-through edge, because this requires an explicit
11088 // jmp when the condition is false.
11089 if (Op.getNode()->hasOneUse()) {
11090 SDNode *User = *Op.getNode()->use_begin();
11091 // Look for an unconditional branch following this conditional branch.
11092 // We need this because we need to reverse the successors in order
11093 // to implement FCMP_UNE.
11094 if (User->getOpcode() == ISD::BR) {
11095 SDValue FalseBB = User->getOperand(1);
11097 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11098 assert(NewBR == User);
11101 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11102 Cond.getOperand(0), Cond.getOperand(1));
11103 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11104 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11105 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11106 Chain, Dest, CC, Cmp);
11107 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11117 // Look pass the truncate if the high bits are known zero.
11118 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11119 Cond = Cond.getOperand(0);
11121 // We know the result of AND is compared against zero. Try to match
11123 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11124 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11125 if (NewSetCC.getNode()) {
11126 CC = NewSetCC.getOperand(0);
11127 Cond = NewSetCC.getOperand(1);
11134 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11135 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11137 Cond = ConvertCmpIfNecessary(Cond, DAG);
11138 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11139 Chain, Dest, CC, Cond);
11142 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11143 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11144 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11145 // that the guard pages used by the OS virtual memory manager are allocated in
11146 // correct sequence.
11148 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11149 SelectionDAG &DAG) const {
11150 MachineFunction &MF = DAG.getMachineFunction();
11151 bool SplitStack = MF.shouldSplitStack();
11152 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11158 SDNode* Node = Op.getNode();
11160 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11161 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11162 " not tell us which reg is the stack pointer!");
11163 EVT VT = Node->getValueType(0);
11164 SDValue Tmp1 = SDValue(Node, 0);
11165 SDValue Tmp2 = SDValue(Node, 1);
11166 SDValue Tmp3 = Node->getOperand(2);
11167 SDValue Chain = Tmp1.getOperand(0);
11169 // Chain the dynamic stack allocation so that it doesn't modify the stack
11170 // pointer when other instructions are using the stack.
11171 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11174 SDValue Size = Tmp2.getOperand(1);
11175 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11176 Chain = SP.getValue(1);
11177 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11178 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11179 unsigned StackAlign = TFI.getStackAlignment();
11180 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11181 if (Align > StackAlign)
11182 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11183 DAG.getConstant(-(uint64_t)Align, VT));
11184 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11186 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11187 DAG.getIntPtrConstant(0, true), SDValue(),
11190 SDValue Ops[2] = { Tmp1, Tmp2 };
11191 return DAG.getMergeValues(Ops, 2, dl);
11195 SDValue Chain = Op.getOperand(0);
11196 SDValue Size = Op.getOperand(1);
11197 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11198 EVT VT = Op.getNode()->getValueType(0);
11200 bool Is64Bit = Subtarget->is64Bit();
11201 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11204 MachineRegisterInfo &MRI = MF.getRegInfo();
11207 // The 64 bit implementation of segmented stacks needs to clobber both r10
11208 // r11. This makes it impossible to use it along with nested parameters.
11209 const Function *F = MF.getFunction();
11211 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11213 if (I->hasNestAttr())
11214 report_fatal_error("Cannot use segmented stacks with functions that "
11215 "have nested arguments.");
11218 const TargetRegisterClass *AddrRegClass =
11219 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11220 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11221 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11222 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11223 DAG.getRegister(Vreg, SPTy));
11224 SDValue Ops1[2] = { Value, Chain };
11225 return DAG.getMergeValues(Ops1, 2, dl);
11228 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11230 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11231 Flag = Chain.getValue(1);
11232 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11234 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11236 const X86RegisterInfo *RegInfo =
11237 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11238 unsigned SPReg = RegInfo->getStackRegister();
11239 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11240 Chain = SP.getValue(1);
11243 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11244 DAG.getConstant(-(uint64_t)Align, VT));
11245 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11248 SDValue Ops1[2] = { SP, Chain };
11249 return DAG.getMergeValues(Ops1, 2, dl);
11253 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11254 MachineFunction &MF = DAG.getMachineFunction();
11255 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11257 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11260 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11261 // vastart just stores the address of the VarArgsFrameIndex slot into the
11262 // memory location argument.
11263 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11265 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11266 MachinePointerInfo(SV), false, false, 0);
11270 // gp_offset (0 - 6 * 8)
11271 // fp_offset (48 - 48 + 8 * 16)
11272 // overflow_arg_area (point to parameters coming in memory).
11274 SmallVector<SDValue, 8> MemOps;
11275 SDValue FIN = Op.getOperand(1);
11277 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11278 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11280 FIN, MachinePointerInfo(SV), false, false, 0);
11281 MemOps.push_back(Store);
11284 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11285 FIN, DAG.getIntPtrConstant(4));
11286 Store = DAG.getStore(Op.getOperand(0), DL,
11287 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11289 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11290 MemOps.push_back(Store);
11292 // Store ptr to overflow_arg_area
11293 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11294 FIN, DAG.getIntPtrConstant(4));
11295 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11297 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11298 MachinePointerInfo(SV, 8),
11300 MemOps.push_back(Store);
11302 // Store ptr to reg_save_area.
11303 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11304 FIN, DAG.getIntPtrConstant(8));
11305 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11307 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11308 MachinePointerInfo(SV, 16), false, false, 0);
11309 MemOps.push_back(Store);
11310 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11311 &MemOps[0], MemOps.size());
11314 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11315 assert(Subtarget->is64Bit() &&
11316 "LowerVAARG only handles 64-bit va_arg!");
11317 assert((Subtarget->isTargetLinux() ||
11318 Subtarget->isTargetDarwin()) &&
11319 "Unhandled target in LowerVAARG");
11320 assert(Op.getNode()->getNumOperands() == 4);
11321 SDValue Chain = Op.getOperand(0);
11322 SDValue SrcPtr = Op.getOperand(1);
11323 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11324 unsigned Align = Op.getConstantOperandVal(3);
11327 EVT ArgVT = Op.getNode()->getValueType(0);
11328 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11329 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11332 // Decide which area this value should be read from.
11333 // TODO: Implement the AMD64 ABI in its entirety. This simple
11334 // selection mechanism works only for the basic types.
11335 if (ArgVT == MVT::f80) {
11336 llvm_unreachable("va_arg for f80 not yet implemented");
11337 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11338 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11339 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11340 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11342 llvm_unreachable("Unhandled argument type in LowerVAARG");
11345 if (ArgMode == 2) {
11346 // Sanity Check: Make sure using fp_offset makes sense.
11347 assert(!getTargetMachine().Options.UseSoftFloat &&
11348 !(DAG.getMachineFunction()
11349 .getFunction()->getAttributes()
11350 .hasAttribute(AttributeSet::FunctionIndex,
11351 Attribute::NoImplicitFloat)) &&
11352 Subtarget->hasSSE1());
11355 // Insert VAARG_64 node into the DAG
11356 // VAARG_64 returns two values: Variable Argument Address, Chain
11357 SmallVector<SDValue, 11> InstOps;
11358 InstOps.push_back(Chain);
11359 InstOps.push_back(SrcPtr);
11360 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11361 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11362 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11363 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11364 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11365 VTs, &InstOps[0], InstOps.size(),
11367 MachinePointerInfo(SV),
11369 /*Volatile=*/false,
11371 /*WriteMem=*/true);
11372 Chain = VAARG.getValue(1);
11374 // Load the next argument and return it
11375 return DAG.getLoad(ArgVT, dl,
11378 MachinePointerInfo(),
11379 false, false, false, 0);
11382 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11383 SelectionDAG &DAG) {
11384 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11385 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11386 SDValue Chain = Op.getOperand(0);
11387 SDValue DstPtr = Op.getOperand(1);
11388 SDValue SrcPtr = Op.getOperand(2);
11389 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11390 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11393 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11394 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11396 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11399 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11400 // amount is a constant. Takes immediate version of shift as input.
11401 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11402 SDValue SrcOp, uint64_t ShiftAmt,
11403 SelectionDAG &DAG) {
11404 MVT ElementType = VT.getVectorElementType();
11406 // Check for ShiftAmt >= element width
11407 if (ShiftAmt >= ElementType.getSizeInBits()) {
11408 if (Opc == X86ISD::VSRAI)
11409 ShiftAmt = ElementType.getSizeInBits() - 1;
11411 return DAG.getConstant(0, VT);
11414 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11415 && "Unknown target vector shift-by-constant node");
11417 // Fold this packed vector shift into a build vector if SrcOp is a
11418 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11419 if (VT == SrcOp.getSimpleValueType() &&
11420 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11421 SmallVector<SDValue, 8> Elts;
11422 unsigned NumElts = SrcOp->getNumOperands();
11423 ConstantSDNode *ND;
11426 default: llvm_unreachable(0);
11427 case X86ISD::VSHLI:
11428 for (unsigned i=0; i!=NumElts; ++i) {
11429 SDValue CurrentOp = SrcOp->getOperand(i);
11430 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11431 Elts.push_back(CurrentOp);
11434 ND = cast<ConstantSDNode>(CurrentOp);
11435 const APInt &C = ND->getAPIntValue();
11436 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11439 case X86ISD::VSRLI:
11440 for (unsigned i=0; i!=NumElts; ++i) {
11441 SDValue CurrentOp = SrcOp->getOperand(i);
11442 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11443 Elts.push_back(CurrentOp);
11446 ND = cast<ConstantSDNode>(CurrentOp);
11447 const APInt &C = ND->getAPIntValue();
11448 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11451 case X86ISD::VSRAI:
11452 for (unsigned i=0; i!=NumElts; ++i) {
11453 SDValue CurrentOp = SrcOp->getOperand(i);
11454 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11455 Elts.push_back(CurrentOp);
11458 ND = cast<ConstantSDNode>(CurrentOp);
11459 const APInt &C = ND->getAPIntValue();
11460 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11465 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11468 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11471 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11472 // may or may not be a constant. Takes immediate version of shift as input.
11473 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11474 SDValue SrcOp, SDValue ShAmt,
11475 SelectionDAG &DAG) {
11476 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11478 // Catch shift-by-constant.
11479 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11480 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11481 CShAmt->getZExtValue(), DAG);
11483 // Change opcode to non-immediate version
11485 default: llvm_unreachable("Unknown target vector shift node");
11486 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11487 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11488 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11491 // Need to build a vector containing shift amount
11492 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11495 ShOps[1] = DAG.getConstant(0, MVT::i32);
11496 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11497 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11499 // The return type has to be a 128-bit type with the same element
11500 // type as the input type.
11501 MVT EltVT = VT.getVectorElementType();
11502 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11504 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11505 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11508 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11510 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11512 default: return SDValue(); // Don't custom lower most intrinsics.
11513 // Comparison intrinsics.
11514 case Intrinsic::x86_sse_comieq_ss:
11515 case Intrinsic::x86_sse_comilt_ss:
11516 case Intrinsic::x86_sse_comile_ss:
11517 case Intrinsic::x86_sse_comigt_ss:
11518 case Intrinsic::x86_sse_comige_ss:
11519 case Intrinsic::x86_sse_comineq_ss:
11520 case Intrinsic::x86_sse_ucomieq_ss:
11521 case Intrinsic::x86_sse_ucomilt_ss:
11522 case Intrinsic::x86_sse_ucomile_ss:
11523 case Intrinsic::x86_sse_ucomigt_ss:
11524 case Intrinsic::x86_sse_ucomige_ss:
11525 case Intrinsic::x86_sse_ucomineq_ss:
11526 case Intrinsic::x86_sse2_comieq_sd:
11527 case Intrinsic::x86_sse2_comilt_sd:
11528 case Intrinsic::x86_sse2_comile_sd:
11529 case Intrinsic::x86_sse2_comigt_sd:
11530 case Intrinsic::x86_sse2_comige_sd:
11531 case Intrinsic::x86_sse2_comineq_sd:
11532 case Intrinsic::x86_sse2_ucomieq_sd:
11533 case Intrinsic::x86_sse2_ucomilt_sd:
11534 case Intrinsic::x86_sse2_ucomile_sd:
11535 case Intrinsic::x86_sse2_ucomigt_sd:
11536 case Intrinsic::x86_sse2_ucomige_sd:
11537 case Intrinsic::x86_sse2_ucomineq_sd: {
11541 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11542 case Intrinsic::x86_sse_comieq_ss:
11543 case Intrinsic::x86_sse2_comieq_sd:
11544 Opc = X86ISD::COMI;
11547 case Intrinsic::x86_sse_comilt_ss:
11548 case Intrinsic::x86_sse2_comilt_sd:
11549 Opc = X86ISD::COMI;
11552 case Intrinsic::x86_sse_comile_ss:
11553 case Intrinsic::x86_sse2_comile_sd:
11554 Opc = X86ISD::COMI;
11557 case Intrinsic::x86_sse_comigt_ss:
11558 case Intrinsic::x86_sse2_comigt_sd:
11559 Opc = X86ISD::COMI;
11562 case Intrinsic::x86_sse_comige_ss:
11563 case Intrinsic::x86_sse2_comige_sd:
11564 Opc = X86ISD::COMI;
11567 case Intrinsic::x86_sse_comineq_ss:
11568 case Intrinsic::x86_sse2_comineq_sd:
11569 Opc = X86ISD::COMI;
11572 case Intrinsic::x86_sse_ucomieq_ss:
11573 case Intrinsic::x86_sse2_ucomieq_sd:
11574 Opc = X86ISD::UCOMI;
11577 case Intrinsic::x86_sse_ucomilt_ss:
11578 case Intrinsic::x86_sse2_ucomilt_sd:
11579 Opc = X86ISD::UCOMI;
11582 case Intrinsic::x86_sse_ucomile_ss:
11583 case Intrinsic::x86_sse2_ucomile_sd:
11584 Opc = X86ISD::UCOMI;
11587 case Intrinsic::x86_sse_ucomigt_ss:
11588 case Intrinsic::x86_sse2_ucomigt_sd:
11589 Opc = X86ISD::UCOMI;
11592 case Intrinsic::x86_sse_ucomige_ss:
11593 case Intrinsic::x86_sse2_ucomige_sd:
11594 Opc = X86ISD::UCOMI;
11597 case Intrinsic::x86_sse_ucomineq_ss:
11598 case Intrinsic::x86_sse2_ucomineq_sd:
11599 Opc = X86ISD::UCOMI;
11604 SDValue LHS = Op.getOperand(1);
11605 SDValue RHS = Op.getOperand(2);
11606 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11607 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11608 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11609 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11610 DAG.getConstant(X86CC, MVT::i8), Cond);
11611 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11614 // Arithmetic intrinsics.
11615 case Intrinsic::x86_sse2_pmulu_dq:
11616 case Intrinsic::x86_avx2_pmulu_dq:
11617 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11618 Op.getOperand(1), Op.getOperand(2));
11620 // SSE2/AVX2 sub with unsigned saturation intrinsics
11621 case Intrinsic::x86_sse2_psubus_b:
11622 case Intrinsic::x86_sse2_psubus_w:
11623 case Intrinsic::x86_avx2_psubus_b:
11624 case Intrinsic::x86_avx2_psubus_w:
11625 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11626 Op.getOperand(1), Op.getOperand(2));
11628 // SSE3/AVX horizontal add/sub intrinsics
11629 case Intrinsic::x86_sse3_hadd_ps:
11630 case Intrinsic::x86_sse3_hadd_pd:
11631 case Intrinsic::x86_avx_hadd_ps_256:
11632 case Intrinsic::x86_avx_hadd_pd_256:
11633 case Intrinsic::x86_sse3_hsub_ps:
11634 case Intrinsic::x86_sse3_hsub_pd:
11635 case Intrinsic::x86_avx_hsub_ps_256:
11636 case Intrinsic::x86_avx_hsub_pd_256:
11637 case Intrinsic::x86_ssse3_phadd_w_128:
11638 case Intrinsic::x86_ssse3_phadd_d_128:
11639 case Intrinsic::x86_avx2_phadd_w:
11640 case Intrinsic::x86_avx2_phadd_d:
11641 case Intrinsic::x86_ssse3_phsub_w_128:
11642 case Intrinsic::x86_ssse3_phsub_d_128:
11643 case Intrinsic::x86_avx2_phsub_w:
11644 case Intrinsic::x86_avx2_phsub_d: {
11647 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11648 case Intrinsic::x86_sse3_hadd_ps:
11649 case Intrinsic::x86_sse3_hadd_pd:
11650 case Intrinsic::x86_avx_hadd_ps_256:
11651 case Intrinsic::x86_avx_hadd_pd_256:
11652 Opcode = X86ISD::FHADD;
11654 case Intrinsic::x86_sse3_hsub_ps:
11655 case Intrinsic::x86_sse3_hsub_pd:
11656 case Intrinsic::x86_avx_hsub_ps_256:
11657 case Intrinsic::x86_avx_hsub_pd_256:
11658 Opcode = X86ISD::FHSUB;
11660 case Intrinsic::x86_ssse3_phadd_w_128:
11661 case Intrinsic::x86_ssse3_phadd_d_128:
11662 case Intrinsic::x86_avx2_phadd_w:
11663 case Intrinsic::x86_avx2_phadd_d:
11664 Opcode = X86ISD::HADD;
11666 case Intrinsic::x86_ssse3_phsub_w_128:
11667 case Intrinsic::x86_ssse3_phsub_d_128:
11668 case Intrinsic::x86_avx2_phsub_w:
11669 case Intrinsic::x86_avx2_phsub_d:
11670 Opcode = X86ISD::HSUB;
11673 return DAG.getNode(Opcode, dl, Op.getValueType(),
11674 Op.getOperand(1), Op.getOperand(2));
11677 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11678 case Intrinsic::x86_sse2_pmaxu_b:
11679 case Intrinsic::x86_sse41_pmaxuw:
11680 case Intrinsic::x86_sse41_pmaxud:
11681 case Intrinsic::x86_avx2_pmaxu_b:
11682 case Intrinsic::x86_avx2_pmaxu_w:
11683 case Intrinsic::x86_avx2_pmaxu_d:
11684 case Intrinsic::x86_sse2_pminu_b:
11685 case Intrinsic::x86_sse41_pminuw:
11686 case Intrinsic::x86_sse41_pminud:
11687 case Intrinsic::x86_avx2_pminu_b:
11688 case Intrinsic::x86_avx2_pminu_w:
11689 case Intrinsic::x86_avx2_pminu_d:
11690 case Intrinsic::x86_sse41_pmaxsb:
11691 case Intrinsic::x86_sse2_pmaxs_w:
11692 case Intrinsic::x86_sse41_pmaxsd:
11693 case Intrinsic::x86_avx2_pmaxs_b:
11694 case Intrinsic::x86_avx2_pmaxs_w:
11695 case Intrinsic::x86_avx2_pmaxs_d:
11696 case Intrinsic::x86_sse41_pminsb:
11697 case Intrinsic::x86_sse2_pmins_w:
11698 case Intrinsic::x86_sse41_pminsd:
11699 case Intrinsic::x86_avx2_pmins_b:
11700 case Intrinsic::x86_avx2_pmins_w:
11701 case Intrinsic::x86_avx2_pmins_d: {
11704 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11705 case Intrinsic::x86_sse2_pmaxu_b:
11706 case Intrinsic::x86_sse41_pmaxuw:
11707 case Intrinsic::x86_sse41_pmaxud:
11708 case Intrinsic::x86_avx2_pmaxu_b:
11709 case Intrinsic::x86_avx2_pmaxu_w:
11710 case Intrinsic::x86_avx2_pmaxu_d:
11711 Opcode = X86ISD::UMAX;
11713 case Intrinsic::x86_sse2_pminu_b:
11714 case Intrinsic::x86_sse41_pminuw:
11715 case Intrinsic::x86_sse41_pminud:
11716 case Intrinsic::x86_avx2_pminu_b:
11717 case Intrinsic::x86_avx2_pminu_w:
11718 case Intrinsic::x86_avx2_pminu_d:
11719 Opcode = X86ISD::UMIN;
11721 case Intrinsic::x86_sse41_pmaxsb:
11722 case Intrinsic::x86_sse2_pmaxs_w:
11723 case Intrinsic::x86_sse41_pmaxsd:
11724 case Intrinsic::x86_avx2_pmaxs_b:
11725 case Intrinsic::x86_avx2_pmaxs_w:
11726 case Intrinsic::x86_avx2_pmaxs_d:
11727 Opcode = X86ISD::SMAX;
11729 case Intrinsic::x86_sse41_pminsb:
11730 case Intrinsic::x86_sse2_pmins_w:
11731 case Intrinsic::x86_sse41_pminsd:
11732 case Intrinsic::x86_avx2_pmins_b:
11733 case Intrinsic::x86_avx2_pmins_w:
11734 case Intrinsic::x86_avx2_pmins_d:
11735 Opcode = X86ISD::SMIN;
11738 return DAG.getNode(Opcode, dl, Op.getValueType(),
11739 Op.getOperand(1), Op.getOperand(2));
11742 // SSE/SSE2/AVX floating point max/min intrinsics.
11743 case Intrinsic::x86_sse_max_ps:
11744 case Intrinsic::x86_sse2_max_pd:
11745 case Intrinsic::x86_avx_max_ps_256:
11746 case Intrinsic::x86_avx_max_pd_256:
11747 case Intrinsic::x86_sse_min_ps:
11748 case Intrinsic::x86_sse2_min_pd:
11749 case Intrinsic::x86_avx_min_ps_256:
11750 case Intrinsic::x86_avx_min_pd_256: {
11753 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11754 case Intrinsic::x86_sse_max_ps:
11755 case Intrinsic::x86_sse2_max_pd:
11756 case Intrinsic::x86_avx_max_ps_256:
11757 case Intrinsic::x86_avx_max_pd_256:
11758 Opcode = X86ISD::FMAX;
11760 case Intrinsic::x86_sse_min_ps:
11761 case Intrinsic::x86_sse2_min_pd:
11762 case Intrinsic::x86_avx_min_ps_256:
11763 case Intrinsic::x86_avx_min_pd_256:
11764 Opcode = X86ISD::FMIN;
11767 return DAG.getNode(Opcode, dl, Op.getValueType(),
11768 Op.getOperand(1), Op.getOperand(2));
11771 // AVX2 variable shift intrinsics
11772 case Intrinsic::x86_avx2_psllv_d:
11773 case Intrinsic::x86_avx2_psllv_q:
11774 case Intrinsic::x86_avx2_psllv_d_256:
11775 case Intrinsic::x86_avx2_psllv_q_256:
11776 case Intrinsic::x86_avx2_psrlv_d:
11777 case Intrinsic::x86_avx2_psrlv_q:
11778 case Intrinsic::x86_avx2_psrlv_d_256:
11779 case Intrinsic::x86_avx2_psrlv_q_256:
11780 case Intrinsic::x86_avx2_psrav_d:
11781 case Intrinsic::x86_avx2_psrav_d_256: {
11784 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11785 case Intrinsic::x86_avx2_psllv_d:
11786 case Intrinsic::x86_avx2_psllv_q:
11787 case Intrinsic::x86_avx2_psllv_d_256:
11788 case Intrinsic::x86_avx2_psllv_q_256:
11791 case Intrinsic::x86_avx2_psrlv_d:
11792 case Intrinsic::x86_avx2_psrlv_q:
11793 case Intrinsic::x86_avx2_psrlv_d_256:
11794 case Intrinsic::x86_avx2_psrlv_q_256:
11797 case Intrinsic::x86_avx2_psrav_d:
11798 case Intrinsic::x86_avx2_psrav_d_256:
11802 return DAG.getNode(Opcode, dl, Op.getValueType(),
11803 Op.getOperand(1), Op.getOperand(2));
11806 case Intrinsic::x86_ssse3_pshuf_b_128:
11807 case Intrinsic::x86_avx2_pshuf_b:
11808 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11809 Op.getOperand(1), Op.getOperand(2));
11811 case Intrinsic::x86_ssse3_psign_b_128:
11812 case Intrinsic::x86_ssse3_psign_w_128:
11813 case Intrinsic::x86_ssse3_psign_d_128:
11814 case Intrinsic::x86_avx2_psign_b:
11815 case Intrinsic::x86_avx2_psign_w:
11816 case Intrinsic::x86_avx2_psign_d:
11817 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11818 Op.getOperand(1), Op.getOperand(2));
11820 case Intrinsic::x86_sse41_insertps:
11821 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11822 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11824 case Intrinsic::x86_avx_vperm2f128_ps_256:
11825 case Intrinsic::x86_avx_vperm2f128_pd_256:
11826 case Intrinsic::x86_avx_vperm2f128_si_256:
11827 case Intrinsic::x86_avx2_vperm2i128:
11828 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11829 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11831 case Intrinsic::x86_avx2_permd:
11832 case Intrinsic::x86_avx2_permps:
11833 // Operands intentionally swapped. Mask is last operand to intrinsic,
11834 // but second operand for node/instruction.
11835 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11836 Op.getOperand(2), Op.getOperand(1));
11838 case Intrinsic::x86_sse_sqrt_ps:
11839 case Intrinsic::x86_sse2_sqrt_pd:
11840 case Intrinsic::x86_avx_sqrt_ps_256:
11841 case Intrinsic::x86_avx_sqrt_pd_256:
11842 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11844 // ptest and testp intrinsics. The intrinsic these come from are designed to
11845 // return an integer value, not just an instruction so lower it to the ptest
11846 // or testp pattern and a setcc for the result.
11847 case Intrinsic::x86_sse41_ptestz:
11848 case Intrinsic::x86_sse41_ptestc:
11849 case Intrinsic::x86_sse41_ptestnzc:
11850 case Intrinsic::x86_avx_ptestz_256:
11851 case Intrinsic::x86_avx_ptestc_256:
11852 case Intrinsic::x86_avx_ptestnzc_256:
11853 case Intrinsic::x86_avx_vtestz_ps:
11854 case Intrinsic::x86_avx_vtestc_ps:
11855 case Intrinsic::x86_avx_vtestnzc_ps:
11856 case Intrinsic::x86_avx_vtestz_pd:
11857 case Intrinsic::x86_avx_vtestc_pd:
11858 case Intrinsic::x86_avx_vtestnzc_pd:
11859 case Intrinsic::x86_avx_vtestz_ps_256:
11860 case Intrinsic::x86_avx_vtestc_ps_256:
11861 case Intrinsic::x86_avx_vtestnzc_ps_256:
11862 case Intrinsic::x86_avx_vtestz_pd_256:
11863 case Intrinsic::x86_avx_vtestc_pd_256:
11864 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11865 bool IsTestPacked = false;
11868 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11869 case Intrinsic::x86_avx_vtestz_ps:
11870 case Intrinsic::x86_avx_vtestz_pd:
11871 case Intrinsic::x86_avx_vtestz_ps_256:
11872 case Intrinsic::x86_avx_vtestz_pd_256:
11873 IsTestPacked = true; // Fallthrough
11874 case Intrinsic::x86_sse41_ptestz:
11875 case Intrinsic::x86_avx_ptestz_256:
11877 X86CC = X86::COND_E;
11879 case Intrinsic::x86_avx_vtestc_ps:
11880 case Intrinsic::x86_avx_vtestc_pd:
11881 case Intrinsic::x86_avx_vtestc_ps_256:
11882 case Intrinsic::x86_avx_vtestc_pd_256:
11883 IsTestPacked = true; // Fallthrough
11884 case Intrinsic::x86_sse41_ptestc:
11885 case Intrinsic::x86_avx_ptestc_256:
11887 X86CC = X86::COND_B;
11889 case Intrinsic::x86_avx_vtestnzc_ps:
11890 case Intrinsic::x86_avx_vtestnzc_pd:
11891 case Intrinsic::x86_avx_vtestnzc_ps_256:
11892 case Intrinsic::x86_avx_vtestnzc_pd_256:
11893 IsTestPacked = true; // Fallthrough
11894 case Intrinsic::x86_sse41_ptestnzc:
11895 case Intrinsic::x86_avx_ptestnzc_256:
11897 X86CC = X86::COND_A;
11901 SDValue LHS = Op.getOperand(1);
11902 SDValue RHS = Op.getOperand(2);
11903 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11904 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11905 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11906 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11907 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11909 case Intrinsic::x86_avx512_kortestz_w:
11910 case Intrinsic::x86_avx512_kortestc_w: {
11911 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11912 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11913 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11914 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11915 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11916 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11917 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11920 // SSE/AVX shift intrinsics
11921 case Intrinsic::x86_sse2_psll_w:
11922 case Intrinsic::x86_sse2_psll_d:
11923 case Intrinsic::x86_sse2_psll_q:
11924 case Intrinsic::x86_avx2_psll_w:
11925 case Intrinsic::x86_avx2_psll_d:
11926 case Intrinsic::x86_avx2_psll_q:
11927 case Intrinsic::x86_sse2_psrl_w:
11928 case Intrinsic::x86_sse2_psrl_d:
11929 case Intrinsic::x86_sse2_psrl_q:
11930 case Intrinsic::x86_avx2_psrl_w:
11931 case Intrinsic::x86_avx2_psrl_d:
11932 case Intrinsic::x86_avx2_psrl_q:
11933 case Intrinsic::x86_sse2_psra_w:
11934 case Intrinsic::x86_sse2_psra_d:
11935 case Intrinsic::x86_avx2_psra_w:
11936 case Intrinsic::x86_avx2_psra_d: {
11939 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11940 case Intrinsic::x86_sse2_psll_w:
11941 case Intrinsic::x86_sse2_psll_d:
11942 case Intrinsic::x86_sse2_psll_q:
11943 case Intrinsic::x86_avx2_psll_w:
11944 case Intrinsic::x86_avx2_psll_d:
11945 case Intrinsic::x86_avx2_psll_q:
11946 Opcode = X86ISD::VSHL;
11948 case Intrinsic::x86_sse2_psrl_w:
11949 case Intrinsic::x86_sse2_psrl_d:
11950 case Intrinsic::x86_sse2_psrl_q:
11951 case Intrinsic::x86_avx2_psrl_w:
11952 case Intrinsic::x86_avx2_psrl_d:
11953 case Intrinsic::x86_avx2_psrl_q:
11954 Opcode = X86ISD::VSRL;
11956 case Intrinsic::x86_sse2_psra_w:
11957 case Intrinsic::x86_sse2_psra_d:
11958 case Intrinsic::x86_avx2_psra_w:
11959 case Intrinsic::x86_avx2_psra_d:
11960 Opcode = X86ISD::VSRA;
11963 return DAG.getNode(Opcode, dl, Op.getValueType(),
11964 Op.getOperand(1), Op.getOperand(2));
11967 // SSE/AVX immediate shift intrinsics
11968 case Intrinsic::x86_sse2_pslli_w:
11969 case Intrinsic::x86_sse2_pslli_d:
11970 case Intrinsic::x86_sse2_pslli_q:
11971 case Intrinsic::x86_avx2_pslli_w:
11972 case Intrinsic::x86_avx2_pslli_d:
11973 case Intrinsic::x86_avx2_pslli_q:
11974 case Intrinsic::x86_sse2_psrli_w:
11975 case Intrinsic::x86_sse2_psrli_d:
11976 case Intrinsic::x86_sse2_psrli_q:
11977 case Intrinsic::x86_avx2_psrli_w:
11978 case Intrinsic::x86_avx2_psrli_d:
11979 case Intrinsic::x86_avx2_psrli_q:
11980 case Intrinsic::x86_sse2_psrai_w:
11981 case Intrinsic::x86_sse2_psrai_d:
11982 case Intrinsic::x86_avx2_psrai_w:
11983 case Intrinsic::x86_avx2_psrai_d: {
11986 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11987 case Intrinsic::x86_sse2_pslli_w:
11988 case Intrinsic::x86_sse2_pslli_d:
11989 case Intrinsic::x86_sse2_pslli_q:
11990 case Intrinsic::x86_avx2_pslli_w:
11991 case Intrinsic::x86_avx2_pslli_d:
11992 case Intrinsic::x86_avx2_pslli_q:
11993 Opcode = X86ISD::VSHLI;
11995 case Intrinsic::x86_sse2_psrli_w:
11996 case Intrinsic::x86_sse2_psrli_d:
11997 case Intrinsic::x86_sse2_psrli_q:
11998 case Intrinsic::x86_avx2_psrli_w:
11999 case Intrinsic::x86_avx2_psrli_d:
12000 case Intrinsic::x86_avx2_psrli_q:
12001 Opcode = X86ISD::VSRLI;
12003 case Intrinsic::x86_sse2_psrai_w:
12004 case Intrinsic::x86_sse2_psrai_d:
12005 case Intrinsic::x86_avx2_psrai_w:
12006 case Intrinsic::x86_avx2_psrai_d:
12007 Opcode = X86ISD::VSRAI;
12010 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12011 Op.getOperand(1), Op.getOperand(2), DAG);
12014 case Intrinsic::x86_sse42_pcmpistria128:
12015 case Intrinsic::x86_sse42_pcmpestria128:
12016 case Intrinsic::x86_sse42_pcmpistric128:
12017 case Intrinsic::x86_sse42_pcmpestric128:
12018 case Intrinsic::x86_sse42_pcmpistrio128:
12019 case Intrinsic::x86_sse42_pcmpestrio128:
12020 case Intrinsic::x86_sse42_pcmpistris128:
12021 case Intrinsic::x86_sse42_pcmpestris128:
12022 case Intrinsic::x86_sse42_pcmpistriz128:
12023 case Intrinsic::x86_sse42_pcmpestriz128: {
12027 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12028 case Intrinsic::x86_sse42_pcmpistria128:
12029 Opcode = X86ISD::PCMPISTRI;
12030 X86CC = X86::COND_A;
12032 case Intrinsic::x86_sse42_pcmpestria128:
12033 Opcode = X86ISD::PCMPESTRI;
12034 X86CC = X86::COND_A;
12036 case Intrinsic::x86_sse42_pcmpistric128:
12037 Opcode = X86ISD::PCMPISTRI;
12038 X86CC = X86::COND_B;
12040 case Intrinsic::x86_sse42_pcmpestric128:
12041 Opcode = X86ISD::PCMPESTRI;
12042 X86CC = X86::COND_B;
12044 case Intrinsic::x86_sse42_pcmpistrio128:
12045 Opcode = X86ISD::PCMPISTRI;
12046 X86CC = X86::COND_O;
12048 case Intrinsic::x86_sse42_pcmpestrio128:
12049 Opcode = X86ISD::PCMPESTRI;
12050 X86CC = X86::COND_O;
12052 case Intrinsic::x86_sse42_pcmpistris128:
12053 Opcode = X86ISD::PCMPISTRI;
12054 X86CC = X86::COND_S;
12056 case Intrinsic::x86_sse42_pcmpestris128:
12057 Opcode = X86ISD::PCMPESTRI;
12058 X86CC = X86::COND_S;
12060 case Intrinsic::x86_sse42_pcmpistriz128:
12061 Opcode = X86ISD::PCMPISTRI;
12062 X86CC = X86::COND_E;
12064 case Intrinsic::x86_sse42_pcmpestriz128:
12065 Opcode = X86ISD::PCMPESTRI;
12066 X86CC = X86::COND_E;
12069 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12070 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12071 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12072 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12073 DAG.getConstant(X86CC, MVT::i8),
12074 SDValue(PCMP.getNode(), 1));
12075 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12078 case Intrinsic::x86_sse42_pcmpistri128:
12079 case Intrinsic::x86_sse42_pcmpestri128: {
12081 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12082 Opcode = X86ISD::PCMPISTRI;
12084 Opcode = X86ISD::PCMPESTRI;
12086 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12087 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12088 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12090 case Intrinsic::x86_fma_vfmadd_ps:
12091 case Intrinsic::x86_fma_vfmadd_pd:
12092 case Intrinsic::x86_fma_vfmsub_ps:
12093 case Intrinsic::x86_fma_vfmsub_pd:
12094 case Intrinsic::x86_fma_vfnmadd_ps:
12095 case Intrinsic::x86_fma_vfnmadd_pd:
12096 case Intrinsic::x86_fma_vfnmsub_ps:
12097 case Intrinsic::x86_fma_vfnmsub_pd:
12098 case Intrinsic::x86_fma_vfmaddsub_ps:
12099 case Intrinsic::x86_fma_vfmaddsub_pd:
12100 case Intrinsic::x86_fma_vfmsubadd_ps:
12101 case Intrinsic::x86_fma_vfmsubadd_pd:
12102 case Intrinsic::x86_fma_vfmadd_ps_256:
12103 case Intrinsic::x86_fma_vfmadd_pd_256:
12104 case Intrinsic::x86_fma_vfmsub_ps_256:
12105 case Intrinsic::x86_fma_vfmsub_pd_256:
12106 case Intrinsic::x86_fma_vfnmadd_ps_256:
12107 case Intrinsic::x86_fma_vfnmadd_pd_256:
12108 case Intrinsic::x86_fma_vfnmsub_ps_256:
12109 case Intrinsic::x86_fma_vfnmsub_pd_256:
12110 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12111 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12112 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12113 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12114 case Intrinsic::x86_fma_vfmadd_ps_512:
12115 case Intrinsic::x86_fma_vfmadd_pd_512:
12116 case Intrinsic::x86_fma_vfmsub_ps_512:
12117 case Intrinsic::x86_fma_vfmsub_pd_512:
12118 case Intrinsic::x86_fma_vfnmadd_ps_512:
12119 case Intrinsic::x86_fma_vfnmadd_pd_512:
12120 case Intrinsic::x86_fma_vfnmsub_ps_512:
12121 case Intrinsic::x86_fma_vfnmsub_pd_512:
12122 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12123 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12124 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12125 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12128 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12129 case Intrinsic::x86_fma_vfmadd_ps:
12130 case Intrinsic::x86_fma_vfmadd_pd:
12131 case Intrinsic::x86_fma_vfmadd_ps_256:
12132 case Intrinsic::x86_fma_vfmadd_pd_256:
12133 case Intrinsic::x86_fma_vfmadd_ps_512:
12134 case Intrinsic::x86_fma_vfmadd_pd_512:
12135 Opc = X86ISD::FMADD;
12137 case Intrinsic::x86_fma_vfmsub_ps:
12138 case Intrinsic::x86_fma_vfmsub_pd:
12139 case Intrinsic::x86_fma_vfmsub_ps_256:
12140 case Intrinsic::x86_fma_vfmsub_pd_256:
12141 case Intrinsic::x86_fma_vfmsub_ps_512:
12142 case Intrinsic::x86_fma_vfmsub_pd_512:
12143 Opc = X86ISD::FMSUB;
12145 case Intrinsic::x86_fma_vfnmadd_ps:
12146 case Intrinsic::x86_fma_vfnmadd_pd:
12147 case Intrinsic::x86_fma_vfnmadd_ps_256:
12148 case Intrinsic::x86_fma_vfnmadd_pd_256:
12149 case Intrinsic::x86_fma_vfnmadd_ps_512:
12150 case Intrinsic::x86_fma_vfnmadd_pd_512:
12151 Opc = X86ISD::FNMADD;
12153 case Intrinsic::x86_fma_vfnmsub_ps:
12154 case Intrinsic::x86_fma_vfnmsub_pd:
12155 case Intrinsic::x86_fma_vfnmsub_ps_256:
12156 case Intrinsic::x86_fma_vfnmsub_pd_256:
12157 case Intrinsic::x86_fma_vfnmsub_ps_512:
12158 case Intrinsic::x86_fma_vfnmsub_pd_512:
12159 Opc = X86ISD::FNMSUB;
12161 case Intrinsic::x86_fma_vfmaddsub_ps:
12162 case Intrinsic::x86_fma_vfmaddsub_pd:
12163 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12164 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12165 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12166 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12167 Opc = X86ISD::FMADDSUB;
12169 case Intrinsic::x86_fma_vfmsubadd_ps:
12170 case Intrinsic::x86_fma_vfmsubadd_pd:
12171 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12172 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12173 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12174 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12175 Opc = X86ISD::FMSUBADD;
12179 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12180 Op.getOperand(2), Op.getOperand(3));
12185 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12186 SDValue Base, SDValue Index,
12187 SDValue ScaleOp, SDValue Chain,
12188 const X86Subtarget * Subtarget) {
12190 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12191 assert(C && "Invalid scale type");
12192 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12193 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12194 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12195 Index.getSimpleValueType().getVectorNumElements());
12196 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12197 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12198 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12199 SDValue Segment = DAG.getRegister(0, MVT::i32);
12200 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12201 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12202 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12203 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12206 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12207 SDValue Src, SDValue Mask, SDValue Base,
12208 SDValue Index, SDValue ScaleOp, SDValue Chain,
12209 const X86Subtarget * Subtarget) {
12211 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12212 assert(C && "Invalid scale type");
12213 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12214 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12215 Index.getSimpleValueType().getVectorNumElements());
12216 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12217 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12218 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12219 SDValue Segment = DAG.getRegister(0, MVT::i32);
12220 if (Src.getOpcode() == ISD::UNDEF)
12221 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12222 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12223 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12224 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12225 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12228 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12229 SDValue Src, SDValue Base, SDValue Index,
12230 SDValue ScaleOp, SDValue Chain) {
12232 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12233 assert(C && "Invalid scale type");
12234 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12235 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12236 SDValue Segment = DAG.getRegister(0, MVT::i32);
12237 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12238 Index.getSimpleValueType().getVectorNumElements());
12239 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12240 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12241 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12242 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12243 return SDValue(Res, 1);
12246 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12247 SDValue Src, SDValue Mask, SDValue Base,
12248 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12250 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12251 assert(C && "Invalid scale type");
12252 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12253 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12254 SDValue Segment = DAG.getRegister(0, MVT::i32);
12255 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12256 Index.getSimpleValueType().getVectorNumElements());
12257 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12258 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12259 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12260 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12261 return SDValue(Res, 1);
12264 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12265 SelectionDAG &DAG) {
12267 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12269 default: return SDValue(); // Don't custom lower most intrinsics.
12271 // RDRAND/RDSEED intrinsics.
12272 case Intrinsic::x86_rdrand_16:
12273 case Intrinsic::x86_rdrand_32:
12274 case Intrinsic::x86_rdrand_64:
12275 case Intrinsic::x86_rdseed_16:
12276 case Intrinsic::x86_rdseed_32:
12277 case Intrinsic::x86_rdseed_64: {
12278 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12279 IntNo == Intrinsic::x86_rdseed_32 ||
12280 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12282 // Emit the node with the right value type.
12283 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12284 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12286 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12287 // Otherwise return the value from Rand, which is always 0, casted to i32.
12288 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12289 DAG.getConstant(1, Op->getValueType(1)),
12290 DAG.getConstant(X86::COND_B, MVT::i32),
12291 SDValue(Result.getNode(), 1) };
12292 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12293 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12294 Ops, array_lengthof(Ops));
12296 // Return { result, isValid, chain }.
12297 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12298 SDValue(Result.getNode(), 2));
12300 //int_gather(index, base, scale);
12301 case Intrinsic::x86_avx512_gather_qpd_512:
12302 case Intrinsic::x86_avx512_gather_qps_512:
12303 case Intrinsic::x86_avx512_gather_dpd_512:
12304 case Intrinsic::x86_avx512_gather_qpi_512:
12305 case Intrinsic::x86_avx512_gather_qpq_512:
12306 case Intrinsic::x86_avx512_gather_dpq_512:
12307 case Intrinsic::x86_avx512_gather_dps_512:
12308 case Intrinsic::x86_avx512_gather_dpi_512: {
12311 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12312 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12313 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12314 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12315 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12316 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12317 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12318 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12319 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12321 SDValue Chain = Op.getOperand(0);
12322 SDValue Index = Op.getOperand(2);
12323 SDValue Base = Op.getOperand(3);
12324 SDValue Scale = Op.getOperand(4);
12325 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12327 //int_gather_mask(v1, mask, index, base, scale);
12328 case Intrinsic::x86_avx512_gather_qps_mask_512:
12329 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12330 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12331 case Intrinsic::x86_avx512_gather_dps_mask_512:
12332 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12333 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12334 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12335 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12338 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12339 case Intrinsic::x86_avx512_gather_qps_mask_512:
12340 Opc = X86::VGATHERQPSZrm; break;
12341 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12342 Opc = X86::VGATHERQPDZrm; break;
12343 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12344 Opc = X86::VGATHERDPDZrm; break;
12345 case Intrinsic::x86_avx512_gather_dps_mask_512:
12346 Opc = X86::VGATHERDPSZrm; break;
12347 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12348 Opc = X86::VPGATHERQDZrm; break;
12349 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12350 Opc = X86::VPGATHERQQZrm; break;
12351 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12352 Opc = X86::VPGATHERDDZrm; break;
12353 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12354 Opc = X86::VPGATHERDQZrm; break;
12356 SDValue Chain = Op.getOperand(0);
12357 SDValue Src = Op.getOperand(2);
12358 SDValue Mask = Op.getOperand(3);
12359 SDValue Index = Op.getOperand(4);
12360 SDValue Base = Op.getOperand(5);
12361 SDValue Scale = Op.getOperand(6);
12362 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12365 //int_scatter(base, index, v1, scale);
12366 case Intrinsic::x86_avx512_scatter_qpd_512:
12367 case Intrinsic::x86_avx512_scatter_qps_512:
12368 case Intrinsic::x86_avx512_scatter_dpd_512:
12369 case Intrinsic::x86_avx512_scatter_qpi_512:
12370 case Intrinsic::x86_avx512_scatter_qpq_512:
12371 case Intrinsic::x86_avx512_scatter_dpq_512:
12372 case Intrinsic::x86_avx512_scatter_dps_512:
12373 case Intrinsic::x86_avx512_scatter_dpi_512: {
12376 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12377 case Intrinsic::x86_avx512_scatter_qpd_512:
12378 Opc = X86::VSCATTERQPDZmr; break;
12379 case Intrinsic::x86_avx512_scatter_qps_512:
12380 Opc = X86::VSCATTERQPSZmr; break;
12381 case Intrinsic::x86_avx512_scatter_dpd_512:
12382 Opc = X86::VSCATTERDPDZmr; break;
12383 case Intrinsic::x86_avx512_scatter_dps_512:
12384 Opc = X86::VSCATTERDPSZmr; break;
12385 case Intrinsic::x86_avx512_scatter_qpi_512:
12386 Opc = X86::VPSCATTERQDZmr; break;
12387 case Intrinsic::x86_avx512_scatter_qpq_512:
12388 Opc = X86::VPSCATTERQQZmr; break;
12389 case Intrinsic::x86_avx512_scatter_dpq_512:
12390 Opc = X86::VPSCATTERDQZmr; break;
12391 case Intrinsic::x86_avx512_scatter_dpi_512:
12392 Opc = X86::VPSCATTERDDZmr; break;
12394 SDValue Chain = Op.getOperand(0);
12395 SDValue Base = Op.getOperand(2);
12396 SDValue Index = Op.getOperand(3);
12397 SDValue Src = Op.getOperand(4);
12398 SDValue Scale = Op.getOperand(5);
12399 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12401 //int_scatter_mask(base, mask, index, v1, scale);
12402 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12403 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12404 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12405 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12406 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12407 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12408 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12409 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12412 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12413 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12414 Opc = X86::VSCATTERQPDZmr; break;
12415 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12416 Opc = X86::VSCATTERQPSZmr; break;
12417 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12418 Opc = X86::VSCATTERDPDZmr; break;
12419 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12420 Opc = X86::VSCATTERDPSZmr; break;
12421 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12422 Opc = X86::VPSCATTERQDZmr; break;
12423 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12424 Opc = X86::VPSCATTERQQZmr; break;
12425 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12426 Opc = X86::VPSCATTERDQZmr; break;
12427 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12428 Opc = X86::VPSCATTERDDZmr; break;
12430 SDValue Chain = Op.getOperand(0);
12431 SDValue Base = Op.getOperand(2);
12432 SDValue Mask = Op.getOperand(3);
12433 SDValue Index = Op.getOperand(4);
12434 SDValue Src = Op.getOperand(5);
12435 SDValue Scale = Op.getOperand(6);
12436 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12438 // XTEST intrinsics.
12439 case Intrinsic::x86_xtest: {
12440 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12441 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12442 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12443 DAG.getConstant(X86::COND_NE, MVT::i8),
12445 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12446 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12447 Ret, SDValue(InTrans.getNode(), 1));
12452 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12453 SelectionDAG &DAG) const {
12454 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12455 MFI->setReturnAddressIsTaken(true);
12457 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12460 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12462 EVT PtrVT = getPointerTy();
12465 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12466 const X86RegisterInfo *RegInfo =
12467 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12468 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12469 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12470 DAG.getNode(ISD::ADD, dl, PtrVT,
12471 FrameAddr, Offset),
12472 MachinePointerInfo(), false, false, false, 0);
12475 // Just load the return address.
12476 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12477 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12478 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12481 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12482 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12483 MFI->setFrameAddressIsTaken(true);
12485 EVT VT = Op.getValueType();
12486 SDLoc dl(Op); // FIXME probably not meaningful
12487 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12488 const X86RegisterInfo *RegInfo =
12489 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12490 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12491 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12492 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12493 "Invalid Frame Register!");
12494 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12496 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12497 MachinePointerInfo(),
12498 false, false, false, 0);
12502 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12503 SelectionDAG &DAG) const {
12504 const X86RegisterInfo *RegInfo =
12505 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12506 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12509 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12510 SDValue Chain = Op.getOperand(0);
12511 SDValue Offset = Op.getOperand(1);
12512 SDValue Handler = Op.getOperand(2);
12515 EVT PtrVT = getPointerTy();
12516 const X86RegisterInfo *RegInfo =
12517 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12518 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12519 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12520 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12521 "Invalid Frame Register!");
12522 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12523 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12525 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12526 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12527 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12528 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12530 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12532 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12533 DAG.getRegister(StoreAddrReg, PtrVT));
12536 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12537 SelectionDAG &DAG) const {
12539 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12540 DAG.getVTList(MVT::i32, MVT::Other),
12541 Op.getOperand(0), Op.getOperand(1));
12544 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12545 SelectionDAG &DAG) const {
12547 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12548 Op.getOperand(0), Op.getOperand(1));
12551 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12552 return Op.getOperand(0);
12555 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12556 SelectionDAG &DAG) const {
12557 SDValue Root = Op.getOperand(0);
12558 SDValue Trmp = Op.getOperand(1); // trampoline
12559 SDValue FPtr = Op.getOperand(2); // nested function
12560 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12563 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12564 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12566 if (Subtarget->is64Bit()) {
12567 SDValue OutChains[6];
12569 // Large code-model.
12570 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12571 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12573 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12574 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12576 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12578 // Load the pointer to the nested function into R11.
12579 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12580 SDValue Addr = Trmp;
12581 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12582 Addr, MachinePointerInfo(TrmpAddr),
12585 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12586 DAG.getConstant(2, MVT::i64));
12587 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12588 MachinePointerInfo(TrmpAddr, 2),
12591 // Load the 'nest' parameter value into R10.
12592 // R10 is specified in X86CallingConv.td
12593 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12594 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12595 DAG.getConstant(10, MVT::i64));
12596 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12597 Addr, MachinePointerInfo(TrmpAddr, 10),
12600 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12601 DAG.getConstant(12, MVT::i64));
12602 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12603 MachinePointerInfo(TrmpAddr, 12),
12606 // Jump to the nested function.
12607 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12608 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12609 DAG.getConstant(20, MVT::i64));
12610 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12611 Addr, MachinePointerInfo(TrmpAddr, 20),
12614 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12615 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12616 DAG.getConstant(22, MVT::i64));
12617 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12618 MachinePointerInfo(TrmpAddr, 22),
12621 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12623 const Function *Func =
12624 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12625 CallingConv::ID CC = Func->getCallingConv();
12630 llvm_unreachable("Unsupported calling convention");
12631 case CallingConv::C:
12632 case CallingConv::X86_StdCall: {
12633 // Pass 'nest' parameter in ECX.
12634 // Must be kept in sync with X86CallingConv.td
12635 NestReg = X86::ECX;
12637 // Check that ECX wasn't needed by an 'inreg' parameter.
12638 FunctionType *FTy = Func->getFunctionType();
12639 const AttributeSet &Attrs = Func->getAttributes();
12641 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12642 unsigned InRegCount = 0;
12645 for (FunctionType::param_iterator I = FTy->param_begin(),
12646 E = FTy->param_end(); I != E; ++I, ++Idx)
12647 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12648 // FIXME: should only count parameters that are lowered to integers.
12649 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12651 if (InRegCount > 2) {
12652 report_fatal_error("Nest register in use - reduce number of inreg"
12658 case CallingConv::X86_FastCall:
12659 case CallingConv::X86_ThisCall:
12660 case CallingConv::Fast:
12661 // Pass 'nest' parameter in EAX.
12662 // Must be kept in sync with X86CallingConv.td
12663 NestReg = X86::EAX;
12667 SDValue OutChains[4];
12668 SDValue Addr, Disp;
12670 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12671 DAG.getConstant(10, MVT::i32));
12672 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12674 // This is storing the opcode for MOV32ri.
12675 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12676 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12677 OutChains[0] = DAG.getStore(Root, dl,
12678 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12679 Trmp, MachinePointerInfo(TrmpAddr),
12682 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12683 DAG.getConstant(1, MVT::i32));
12684 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12685 MachinePointerInfo(TrmpAddr, 1),
12688 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12689 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12690 DAG.getConstant(5, MVT::i32));
12691 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12692 MachinePointerInfo(TrmpAddr, 5),
12695 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12696 DAG.getConstant(6, MVT::i32));
12697 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12698 MachinePointerInfo(TrmpAddr, 6),
12701 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12705 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12706 SelectionDAG &DAG) const {
12708 The rounding mode is in bits 11:10 of FPSR, and has the following
12710 00 Round to nearest
12715 FLT_ROUNDS, on the other hand, expects the following:
12722 To perform the conversion, we do:
12723 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12726 MachineFunction &MF = DAG.getMachineFunction();
12727 const TargetMachine &TM = MF.getTarget();
12728 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12729 unsigned StackAlignment = TFI.getStackAlignment();
12730 MVT VT = Op.getSimpleValueType();
12733 // Save FP Control Word to stack slot
12734 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12735 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12737 MachineMemOperand *MMO =
12738 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12739 MachineMemOperand::MOStore, 2, 2);
12741 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12742 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12743 DAG.getVTList(MVT::Other),
12744 Ops, array_lengthof(Ops), MVT::i16,
12747 // Load FP Control Word from stack slot
12748 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12749 MachinePointerInfo(), false, false, false, 0);
12751 // Transform as necessary
12753 DAG.getNode(ISD::SRL, DL, MVT::i16,
12754 DAG.getNode(ISD::AND, DL, MVT::i16,
12755 CWD, DAG.getConstant(0x800, MVT::i16)),
12756 DAG.getConstant(11, MVT::i8));
12758 DAG.getNode(ISD::SRL, DL, MVT::i16,
12759 DAG.getNode(ISD::AND, DL, MVT::i16,
12760 CWD, DAG.getConstant(0x400, MVT::i16)),
12761 DAG.getConstant(9, MVT::i8));
12764 DAG.getNode(ISD::AND, DL, MVT::i16,
12765 DAG.getNode(ISD::ADD, DL, MVT::i16,
12766 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12767 DAG.getConstant(1, MVT::i16)),
12768 DAG.getConstant(3, MVT::i16));
12770 return DAG.getNode((VT.getSizeInBits() < 16 ?
12771 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12774 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12775 MVT VT = Op.getSimpleValueType();
12777 unsigned NumBits = VT.getSizeInBits();
12780 Op = Op.getOperand(0);
12781 if (VT == MVT::i8) {
12782 // Zero extend to i32 since there is not an i8 bsr.
12784 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12787 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12788 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12789 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12791 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12794 DAG.getConstant(NumBits+NumBits-1, OpVT),
12795 DAG.getConstant(X86::COND_E, MVT::i8),
12798 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12800 // Finally xor with NumBits-1.
12801 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12804 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12808 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12809 MVT VT = Op.getSimpleValueType();
12811 unsigned NumBits = VT.getSizeInBits();
12814 Op = Op.getOperand(0);
12815 if (VT == MVT::i8) {
12816 // Zero extend to i32 since there is not an i8 bsr.
12818 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12821 // Issue a bsr (scan bits in reverse).
12822 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12823 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12825 // And xor with NumBits-1.
12826 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12829 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12833 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12834 MVT VT = Op.getSimpleValueType();
12835 unsigned NumBits = VT.getSizeInBits();
12837 Op = Op.getOperand(0);
12839 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12840 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12841 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12843 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12846 DAG.getConstant(NumBits, VT),
12847 DAG.getConstant(X86::COND_E, MVT::i8),
12850 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12853 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12854 // ones, and then concatenate the result back.
12855 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12856 MVT VT = Op.getSimpleValueType();
12858 assert(VT.is256BitVector() && VT.isInteger() &&
12859 "Unsupported value type for operation");
12861 unsigned NumElems = VT.getVectorNumElements();
12864 // Extract the LHS vectors
12865 SDValue LHS = Op.getOperand(0);
12866 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12867 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12869 // Extract the RHS vectors
12870 SDValue RHS = Op.getOperand(1);
12871 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12872 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12874 MVT EltVT = VT.getVectorElementType();
12875 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12877 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12878 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12879 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12882 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12883 assert(Op.getSimpleValueType().is256BitVector() &&
12884 Op.getSimpleValueType().isInteger() &&
12885 "Only handle AVX 256-bit vector integer operation");
12886 return Lower256IntArith(Op, DAG);
12889 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12890 assert(Op.getSimpleValueType().is256BitVector() &&
12891 Op.getSimpleValueType().isInteger() &&
12892 "Only handle AVX 256-bit vector integer operation");
12893 return Lower256IntArith(Op, DAG);
12896 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12897 SelectionDAG &DAG) {
12899 MVT VT = Op.getSimpleValueType();
12901 // Decompose 256-bit ops into smaller 128-bit ops.
12902 if (VT.is256BitVector() && !Subtarget->hasInt256())
12903 return Lower256IntArith(Op, DAG);
12905 SDValue A = Op.getOperand(0);
12906 SDValue B = Op.getOperand(1);
12908 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12909 if (VT == MVT::v4i32) {
12910 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12911 "Should not custom lower when pmuldq is available!");
12913 // Extract the odd parts.
12914 static const int UnpackMask[] = { 1, -1, 3, -1 };
12915 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12916 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12918 // Multiply the even parts.
12919 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12920 // Now multiply odd parts.
12921 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12923 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12924 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12926 // Merge the two vectors back together with a shuffle. This expands into 2
12928 static const int ShufMask[] = { 0, 4, 2, 6 };
12929 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12932 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12933 "Only know how to lower V2I64/V4I64/V8I64 multiply");
12935 // Ahi = psrlqi(a, 32);
12936 // Bhi = psrlqi(b, 32);
12938 // AloBlo = pmuludq(a, b);
12939 // AloBhi = pmuludq(a, Bhi);
12940 // AhiBlo = pmuludq(Ahi, b);
12942 // AloBhi = psllqi(AloBhi, 32);
12943 // AhiBlo = psllqi(AhiBlo, 32);
12944 // return AloBlo + AloBhi + AhiBlo;
12946 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12947 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12949 // Bit cast to 32-bit vectors for MULUDQ
12950 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12951 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12952 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12953 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12954 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12955 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12957 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12958 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12959 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12961 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12962 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12964 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12965 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12968 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12969 MVT VT = Op.getSimpleValueType();
12970 MVT EltTy = VT.getVectorElementType();
12971 unsigned NumElts = VT.getVectorNumElements();
12972 SDValue N0 = Op.getOperand(0);
12975 // Lower sdiv X, pow2-const.
12976 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12980 APInt SplatValue, SplatUndef;
12981 unsigned SplatBitSize;
12983 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12985 EltTy.getSizeInBits() < SplatBitSize)
12988 if ((SplatValue != 0) &&
12989 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12990 unsigned Lg2 = SplatValue.countTrailingZeros();
12991 // Splat the sign bit.
12992 SmallVector<SDValue, 16> Sz(NumElts,
12993 DAG.getConstant(EltTy.getSizeInBits() - 1,
12995 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12996 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12998 // Add (N0 < 0) ? abs2 - 1 : 0;
12999 SmallVector<SDValue, 16> Amt(NumElts,
13000 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
13002 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
13003 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
13005 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
13006 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
13007 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
13008 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
13011 // If we're dividing by a positive value, we're done. Otherwise, we must
13012 // negate the result.
13013 if (SplatValue.isNonNegative())
13016 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
13017 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
13018 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
13023 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13024 const X86Subtarget *Subtarget) {
13025 MVT VT = Op.getSimpleValueType();
13027 SDValue R = Op.getOperand(0);
13028 SDValue Amt = Op.getOperand(1);
13030 // Optimize shl/srl/sra with constant shift amount.
13031 if (isSplatVector(Amt.getNode())) {
13032 SDValue SclrAmt = Amt->getOperand(0);
13033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13034 uint64_t ShiftAmt = C->getZExtValue();
13036 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13037 (Subtarget->hasInt256() &&
13038 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13039 (Subtarget->hasAVX512() &&
13040 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13041 if (Op.getOpcode() == ISD::SHL)
13042 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13044 if (Op.getOpcode() == ISD::SRL)
13045 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13047 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13048 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13052 if (VT == MVT::v16i8) {
13053 if (Op.getOpcode() == ISD::SHL) {
13054 // Make a large shift.
13055 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13056 MVT::v8i16, R, ShiftAmt,
13058 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13059 // Zero out the rightmost bits.
13060 SmallVector<SDValue, 16> V(16,
13061 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13063 return DAG.getNode(ISD::AND, dl, VT, SHL,
13064 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13066 if (Op.getOpcode() == ISD::SRL) {
13067 // Make a large shift.
13068 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13069 MVT::v8i16, R, ShiftAmt,
13071 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13072 // Zero out the leftmost bits.
13073 SmallVector<SDValue, 16> V(16,
13074 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13076 return DAG.getNode(ISD::AND, dl, VT, SRL,
13077 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13079 if (Op.getOpcode() == ISD::SRA) {
13080 if (ShiftAmt == 7) {
13081 // R s>> 7 === R s< 0
13082 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13083 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13086 // R s>> a === ((R u>> a) ^ m) - m
13087 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13088 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13090 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13091 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13092 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13095 llvm_unreachable("Unknown shift opcode.");
13098 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13099 if (Op.getOpcode() == ISD::SHL) {
13100 // Make a large shift.
13101 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13102 MVT::v16i16, R, ShiftAmt,
13104 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13105 // Zero out the rightmost bits.
13106 SmallVector<SDValue, 32> V(32,
13107 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13109 return DAG.getNode(ISD::AND, dl, VT, SHL,
13110 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13112 if (Op.getOpcode() == ISD::SRL) {
13113 // Make a large shift.
13114 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13115 MVT::v16i16, R, ShiftAmt,
13117 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13118 // Zero out the leftmost bits.
13119 SmallVector<SDValue, 32> V(32,
13120 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13122 return DAG.getNode(ISD::AND, dl, VT, SRL,
13123 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13125 if (Op.getOpcode() == ISD::SRA) {
13126 if (ShiftAmt == 7) {
13127 // R s>> 7 === R s< 0
13128 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13129 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13132 // R s>> a === ((R u>> a) ^ m) - m
13133 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13134 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13136 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13137 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13138 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13141 llvm_unreachable("Unknown shift opcode.");
13146 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13147 if (!Subtarget->is64Bit() &&
13148 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13149 Amt.getOpcode() == ISD::BITCAST &&
13150 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13151 Amt = Amt.getOperand(0);
13152 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13153 VT.getVectorNumElements();
13154 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13155 uint64_t ShiftAmt = 0;
13156 for (unsigned i = 0; i != Ratio; ++i) {
13157 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13161 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13163 // Check remaining shift amounts.
13164 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13165 uint64_t ShAmt = 0;
13166 for (unsigned j = 0; j != Ratio; ++j) {
13167 ConstantSDNode *C =
13168 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13172 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13174 if (ShAmt != ShiftAmt)
13177 switch (Op.getOpcode()) {
13179 llvm_unreachable("Unknown shift opcode!");
13181 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13184 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13187 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13195 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13196 const X86Subtarget* Subtarget) {
13197 MVT VT = Op.getSimpleValueType();
13199 SDValue R = Op.getOperand(0);
13200 SDValue Amt = Op.getOperand(1);
13202 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13203 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13204 (Subtarget->hasInt256() &&
13205 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13206 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13207 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13209 EVT EltVT = VT.getVectorElementType();
13211 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13212 unsigned NumElts = VT.getVectorNumElements();
13214 for (i = 0; i != NumElts; ++i) {
13215 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13219 for (j = i; j != NumElts; ++j) {
13220 SDValue Arg = Amt.getOperand(j);
13221 if (Arg.getOpcode() == ISD::UNDEF) continue;
13222 if (Arg != Amt.getOperand(i))
13225 if (i != NumElts && j == NumElts)
13226 BaseShAmt = Amt.getOperand(i);
13228 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13229 Amt = Amt.getOperand(0);
13230 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13231 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13232 SDValue InVec = Amt.getOperand(0);
13233 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13234 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13236 for (; i != NumElts; ++i) {
13237 SDValue Arg = InVec.getOperand(i);
13238 if (Arg.getOpcode() == ISD::UNDEF) continue;
13242 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13243 if (ConstantSDNode *C =
13244 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13245 unsigned SplatIdx =
13246 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13247 if (C->getZExtValue() == SplatIdx)
13248 BaseShAmt = InVec.getOperand(1);
13251 if (BaseShAmt.getNode() == 0)
13252 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13253 DAG.getIntPtrConstant(0));
13257 if (BaseShAmt.getNode()) {
13258 if (EltVT.bitsGT(MVT::i32))
13259 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13260 else if (EltVT.bitsLT(MVT::i32))
13261 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13263 switch (Op.getOpcode()) {
13265 llvm_unreachable("Unknown shift opcode!");
13267 switch (VT.SimpleTy) {
13268 default: return SDValue();
13277 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13280 switch (VT.SimpleTy) {
13281 default: return SDValue();
13288 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13291 switch (VT.SimpleTy) {
13292 default: return SDValue();
13301 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13307 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13308 if (!Subtarget->is64Bit() &&
13309 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13310 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
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 std::vector<SDValue> Vals(Ratio);
13317 for (unsigned i = 0; i != Ratio; ++i)
13318 Vals[i] = Amt.getOperand(i);
13319 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13320 for (unsigned j = 0; j != Ratio; ++j)
13321 if (Vals[j] != Amt.getOperand(i + j))
13324 switch (Op.getOpcode()) {
13326 llvm_unreachable("Unknown shift opcode!");
13328 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13330 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13332 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13339 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13340 SelectionDAG &DAG) {
13342 MVT VT = Op.getSimpleValueType();
13344 SDValue R = Op.getOperand(0);
13345 SDValue Amt = Op.getOperand(1);
13348 if (!Subtarget->hasSSE2())
13351 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13355 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13359 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13361 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13362 if (Subtarget->hasInt256()) {
13363 if (Op.getOpcode() == ISD::SRL &&
13364 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13365 VT == MVT::v4i64 || VT == MVT::v8i32))
13367 if (Op.getOpcode() == ISD::SHL &&
13368 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13369 VT == MVT::v4i64 || VT == MVT::v8i32))
13371 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13375 // If possible, lower this packed shift into a vector multiply instead of
13376 // expanding it into a sequence of scalar shifts.
13377 // Do this only if the vector shift count is a constant build_vector.
13378 if (Op.getOpcode() == ISD::SHL &&
13379 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13380 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13381 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13382 SmallVector<SDValue, 8> Elts;
13383 EVT SVT = VT.getScalarType();
13384 unsigned SVTBits = SVT.getSizeInBits();
13385 const APInt &One = APInt(SVTBits, 1);
13386 unsigned NumElems = VT.getVectorNumElements();
13388 for (unsigned i=0; i !=NumElems; ++i) {
13389 SDValue Op = Amt->getOperand(i);
13390 if (Op->getOpcode() == ISD::UNDEF) {
13391 Elts.push_back(Op);
13395 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13396 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13397 uint64_t ShAmt = C.getZExtValue();
13398 if (ShAmt >= SVTBits) {
13399 Elts.push_back(DAG.getUNDEF(SVT));
13402 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13404 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13405 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13408 // Lower SHL with variable shift amount.
13409 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13410 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13412 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13413 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13414 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13415 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13418 // If possible, lower this shift as a sequence of two shifts by
13419 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13421 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13423 // Could be rewritten as:
13424 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13426 // The advantage is that the two shifts from the example would be
13427 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13428 // the vector shift into four scalar shifts plus four pairs of vector
13430 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13431 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13432 unsigned TargetOpcode = X86ISD::MOVSS;
13433 bool CanBeSimplified;
13434 // The splat value for the first packed shift (the 'X' from the example).
13435 SDValue Amt1 = Amt->getOperand(0);
13436 // The splat value for the second packed shift (the 'Y' from the example).
13437 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13438 Amt->getOperand(2);
13440 // See if it is possible to replace this node with a sequence of
13441 // two shifts followed by a MOVSS/MOVSD
13442 if (VT == MVT::v4i32) {
13443 // Check if it is legal to use a MOVSS.
13444 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13445 Amt2 == Amt->getOperand(3);
13446 if (!CanBeSimplified) {
13447 // Otherwise, check if we can still simplify this node using a MOVSD.
13448 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13449 Amt->getOperand(2) == Amt->getOperand(3);
13450 TargetOpcode = X86ISD::MOVSD;
13451 Amt2 = Amt->getOperand(2);
13454 // Do similar checks for the case where the machine value type
13456 CanBeSimplified = Amt1 == Amt->getOperand(1);
13457 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13458 CanBeSimplified = Amt2 == Amt->getOperand(i);
13460 if (!CanBeSimplified) {
13461 TargetOpcode = X86ISD::MOVSD;
13462 CanBeSimplified = true;
13463 Amt2 = Amt->getOperand(4);
13464 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13465 CanBeSimplified = Amt1 == Amt->getOperand(i);
13466 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13467 CanBeSimplified = Amt2 == Amt->getOperand(j);
13471 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13472 isa<ConstantSDNode>(Amt2)) {
13473 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13474 EVT CastVT = MVT::v4i32;
13476 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13477 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13479 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13480 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13481 if (TargetOpcode == X86ISD::MOVSD)
13482 CastVT = MVT::v2i64;
13483 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13484 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13485 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13487 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13491 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13492 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13495 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13496 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13498 // Turn 'a' into a mask suitable for VSELECT
13499 SDValue VSelM = DAG.getConstant(0x80, VT);
13500 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13501 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13503 SDValue CM1 = DAG.getConstant(0x0f, VT);
13504 SDValue CM2 = DAG.getConstant(0x3f, VT);
13506 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13507 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13508 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13509 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13510 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13513 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13514 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13515 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13517 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13518 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13519 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13520 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13521 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13524 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13525 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13526 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13528 // return VSELECT(r, r+r, a);
13529 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13530 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13534 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13535 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13536 // solution better.
13537 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13538 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13540 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13541 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13542 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13543 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13544 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13547 // Decompose 256-bit shifts into smaller 128-bit shifts.
13548 if (VT.is256BitVector()) {
13549 unsigned NumElems = VT.getVectorNumElements();
13550 MVT EltVT = VT.getVectorElementType();
13551 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13553 // Extract the two vectors
13554 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13555 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13557 // Recreate the shift amount vectors
13558 SDValue Amt1, Amt2;
13559 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13560 // Constant shift amount
13561 SmallVector<SDValue, 4> Amt1Csts;
13562 SmallVector<SDValue, 4> Amt2Csts;
13563 for (unsigned i = 0; i != NumElems/2; ++i)
13564 Amt1Csts.push_back(Amt->getOperand(i));
13565 for (unsigned i = NumElems/2; i != NumElems; ++i)
13566 Amt2Csts.push_back(Amt->getOperand(i));
13568 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13569 &Amt1Csts[0], NumElems/2);
13570 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13571 &Amt2Csts[0], NumElems/2);
13573 // Variable shift amount
13574 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13575 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13578 // Issue new vector shifts for the smaller types
13579 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13580 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13582 // Concatenate the result back
13583 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13589 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13590 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13591 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13592 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13593 // has only one use.
13594 SDNode *N = Op.getNode();
13595 SDValue LHS = N->getOperand(0);
13596 SDValue RHS = N->getOperand(1);
13597 unsigned BaseOp = 0;
13600 switch (Op.getOpcode()) {
13601 default: llvm_unreachable("Unknown ovf instruction!");
13603 // A subtract of one will be selected as a INC. Note that INC doesn't
13604 // set CF, so we can't do this for UADDO.
13605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13607 BaseOp = X86ISD::INC;
13608 Cond = X86::COND_O;
13611 BaseOp = X86ISD::ADD;
13612 Cond = X86::COND_O;
13615 BaseOp = X86ISD::ADD;
13616 Cond = X86::COND_B;
13619 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13620 // set CF, so we can't do this for USUBO.
13621 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13623 BaseOp = X86ISD::DEC;
13624 Cond = X86::COND_O;
13627 BaseOp = X86ISD::SUB;
13628 Cond = X86::COND_O;
13631 BaseOp = X86ISD::SUB;
13632 Cond = X86::COND_B;
13635 BaseOp = X86ISD::SMUL;
13636 Cond = X86::COND_O;
13638 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13639 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13641 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13644 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13645 DAG.getConstant(X86::COND_O, MVT::i32),
13646 SDValue(Sum.getNode(), 2));
13648 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13652 // Also sets EFLAGS.
13653 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13654 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13657 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13658 DAG.getConstant(Cond, MVT::i32),
13659 SDValue(Sum.getNode(), 1));
13661 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13664 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13665 SelectionDAG &DAG) const {
13667 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13668 MVT VT = Op.getSimpleValueType();
13670 if (!Subtarget->hasSSE2() || !VT.isVector())
13673 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13674 ExtraVT.getScalarType().getSizeInBits();
13676 switch (VT.SimpleTy) {
13677 default: return SDValue();
13680 if (!Subtarget->hasFp256())
13682 if (!Subtarget->hasInt256()) {
13683 // needs to be split
13684 unsigned NumElems = VT.getVectorNumElements();
13686 // Extract the LHS vectors
13687 SDValue LHS = Op.getOperand(0);
13688 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13689 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13691 MVT EltVT = VT.getVectorElementType();
13692 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13694 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13695 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13696 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13698 SDValue Extra = DAG.getValueType(ExtraVT);
13700 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13701 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13703 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13708 SDValue Op0 = Op.getOperand(0);
13709 SDValue Op00 = Op0.getOperand(0);
13711 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13712 if (Op0.getOpcode() == ISD::BITCAST &&
13713 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13714 // (sext (vzext x)) -> (vsext x)
13715 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13716 if (Tmp1.getNode()) {
13717 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13718 // This folding is only valid when the in-reg type is a vector of i8,
13720 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13721 ExtraEltVT == MVT::i32) {
13722 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13723 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13724 "This optimization is invalid without a VZEXT.");
13725 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13731 // If the above didn't work, then just use Shift-Left + Shift-Right.
13732 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13734 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13740 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13741 SelectionDAG &DAG) {
13743 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13744 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13745 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13746 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13748 // The only fence that needs an instruction is a sequentially-consistent
13749 // cross-thread fence.
13750 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13751 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13752 // no-sse2). There isn't any reason to disable it if the target processor
13754 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13755 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13757 SDValue Chain = Op.getOperand(0);
13758 SDValue Zero = DAG.getConstant(0, MVT::i32);
13760 DAG.getRegister(X86::ESP, MVT::i32), // Base
13761 DAG.getTargetConstant(1, MVT::i8), // Scale
13762 DAG.getRegister(0, MVT::i32), // Index
13763 DAG.getTargetConstant(0, MVT::i32), // Disp
13764 DAG.getRegister(0, MVT::i32), // Segment.
13768 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13769 return SDValue(Res, 0);
13772 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13773 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13776 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13777 SelectionDAG &DAG) {
13778 MVT T = Op.getSimpleValueType();
13782 switch(T.SimpleTy) {
13783 default: llvm_unreachable("Invalid value type!");
13784 case MVT::i8: Reg = X86::AL; size = 1; break;
13785 case MVT::i16: Reg = X86::AX; size = 2; break;
13786 case MVT::i32: Reg = X86::EAX; size = 4; break;
13788 assert(Subtarget->is64Bit() && "Node not type legal!");
13789 Reg = X86::RAX; size = 8;
13792 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13793 Op.getOperand(2), SDValue());
13794 SDValue Ops[] = { cpIn.getValue(0),
13797 DAG.getTargetConstant(size, MVT::i8),
13798 cpIn.getValue(1) };
13799 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13800 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13801 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13802 Ops, array_lengthof(Ops), T, MMO);
13804 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13808 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13809 SelectionDAG &DAG) {
13810 assert(Subtarget->is64Bit() && "Result not type legalized?");
13811 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13812 SDValue TheChain = Op.getOperand(0);
13814 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13815 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13816 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13818 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13819 DAG.getConstant(32, MVT::i8));
13821 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13824 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13827 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13828 SelectionDAG &DAG) {
13829 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13830 MVT DstVT = Op.getSimpleValueType();
13831 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13832 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13833 assert((DstVT == MVT::i64 ||
13834 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13835 "Unexpected custom BITCAST");
13836 // i64 <=> MMX conversions are Legal.
13837 if (SrcVT==MVT::i64 && DstVT.isVector())
13839 if (DstVT==MVT::i64 && SrcVT.isVector())
13841 // MMX <=> MMX conversions are Legal.
13842 if (SrcVT.isVector() && DstVT.isVector())
13844 // All other conversions need to be expanded.
13848 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13849 SDNode *Node = Op.getNode();
13851 EVT T = Node->getValueType(0);
13852 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13853 DAG.getConstant(0, T), Node->getOperand(2));
13854 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13855 cast<AtomicSDNode>(Node)->getMemoryVT(),
13856 Node->getOperand(0),
13857 Node->getOperand(1), negOp,
13858 cast<AtomicSDNode>(Node)->getMemOperand(),
13859 cast<AtomicSDNode>(Node)->getOrdering(),
13860 cast<AtomicSDNode>(Node)->getSynchScope());
13863 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13864 SDNode *Node = Op.getNode();
13866 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13868 // Convert seq_cst store -> xchg
13869 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13870 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13871 // (The only way to get a 16-byte store is cmpxchg16b)
13872 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13873 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13874 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13875 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13876 cast<AtomicSDNode>(Node)->getMemoryVT(),
13877 Node->getOperand(0),
13878 Node->getOperand(1), Node->getOperand(2),
13879 cast<AtomicSDNode>(Node)->getMemOperand(),
13880 cast<AtomicSDNode>(Node)->getOrdering(),
13881 cast<AtomicSDNode>(Node)->getSynchScope());
13882 return Swap.getValue(1);
13884 // Other atomic stores have a simple pattern.
13888 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13889 EVT VT = Op.getNode()->getSimpleValueType(0);
13891 // Let legalize expand this if it isn't a legal type yet.
13892 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13895 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13898 bool ExtraOp = false;
13899 switch (Op.getOpcode()) {
13900 default: llvm_unreachable("Invalid code");
13901 case ISD::ADDC: Opc = X86ISD::ADD; break;
13902 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13903 case ISD::SUBC: Opc = X86ISD::SUB; break;
13904 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13908 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13910 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13911 Op.getOperand(1), Op.getOperand(2));
13914 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13915 SelectionDAG &DAG) {
13916 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13918 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13919 // which returns the values as { float, float } (in XMM0) or
13920 // { double, double } (which is returned in XMM0, XMM1).
13922 SDValue Arg = Op.getOperand(0);
13923 EVT ArgVT = Arg.getValueType();
13924 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13926 TargetLowering::ArgListTy Args;
13927 TargetLowering::ArgListEntry Entry;
13931 Entry.isSExt = false;
13932 Entry.isZExt = false;
13933 Args.push_back(Entry);
13935 bool isF64 = ArgVT == MVT::f64;
13936 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13937 // the small struct {f32, f32} is returned in (eax, edx). For f64,
13938 // the results are returned via SRet in memory.
13939 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
13940 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13941 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13943 Type *RetTy = isF64
13944 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13945 : (Type*)VectorType::get(ArgTy, 4);
13947 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13948 false, false, false, false, 0,
13949 CallingConv::C, /*isTaillCall=*/false,
13950 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13951 Callee, Args, DAG, dl);
13952 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13955 // Returned in xmm0 and xmm1.
13956 return CallResult.first;
13958 // Returned in bits 0:31 and 32:64 xmm0.
13959 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13960 CallResult.first, DAG.getIntPtrConstant(0));
13961 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13962 CallResult.first, DAG.getIntPtrConstant(1));
13963 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13964 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13967 /// LowerOperation - Provide custom lowering hooks for some operations.
13969 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13970 switch (Op.getOpcode()) {
13971 default: llvm_unreachable("Should not custom lower this!");
13972 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
13973 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13974 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
13975 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
13976 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
13977 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13978 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
13979 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13980 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13981 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13982 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13983 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13984 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13985 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13986 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13987 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13988 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
13989 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13990 case ISD::SHL_PARTS:
13991 case ISD::SRA_PARTS:
13992 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
13993 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
13994 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
13995 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13996 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
13997 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13998 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
13999 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14000 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14001 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14002 case ISD::FABS: return LowerFABS(Op, DAG);
14003 case ISD::FNEG: return LowerFNEG(Op, DAG);
14004 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14005 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14006 case ISD::SETCC: return LowerSETCC(Op, DAG);
14007 case ISD::SELECT: return LowerSELECT(Op, DAG);
14008 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14009 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14010 case ISD::VASTART: return LowerVASTART(Op, DAG);
14011 case ISD::VAARG: return LowerVAARG(Op, DAG);
14012 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14013 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14014 case ISD::INTRINSIC_VOID:
14015 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14016 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14017 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14018 case ISD::FRAME_TO_ARGS_OFFSET:
14019 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14020 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14021 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14022 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14023 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14024 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14025 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14026 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14027 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14028 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14029 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14030 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14033 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14039 case ISD::UMULO: return LowerXALUO(Op, DAG);
14040 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14041 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14045 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14046 case ISD::ADD: return LowerADD(Op, DAG);
14047 case ISD::SUB: return LowerSUB(Op, DAG);
14048 case ISD::SDIV: return LowerSDIV(Op, DAG);
14049 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14053 static void ReplaceATOMIC_LOAD(SDNode *Node,
14054 SmallVectorImpl<SDValue> &Results,
14055 SelectionDAG &DAG) {
14057 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14059 // Convert wide load -> cmpxchg8b/cmpxchg16b
14060 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14061 // (The only way to get a 16-byte load is cmpxchg16b)
14062 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14063 SDValue Zero = DAG.getConstant(0, VT);
14064 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14065 Node->getOperand(0),
14066 Node->getOperand(1), Zero, Zero,
14067 cast<AtomicSDNode>(Node)->getMemOperand(),
14068 cast<AtomicSDNode>(Node)->getOrdering(),
14069 cast<AtomicSDNode>(Node)->getOrdering(),
14070 cast<AtomicSDNode>(Node)->getSynchScope());
14071 Results.push_back(Swap.getValue(0));
14072 Results.push_back(Swap.getValue(1));
14076 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14077 SelectionDAG &DAG, unsigned NewOp) {
14079 assert (Node->getValueType(0) == MVT::i64 &&
14080 "Only know how to expand i64 atomics");
14082 SDValue Chain = Node->getOperand(0);
14083 SDValue In1 = Node->getOperand(1);
14084 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14085 Node->getOperand(2), DAG.getIntPtrConstant(0));
14086 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14087 Node->getOperand(2), DAG.getIntPtrConstant(1));
14088 SDValue Ops[] = { Chain, In1, In2L, In2H };
14089 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14091 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14092 cast<MemSDNode>(Node)->getMemOperand());
14093 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14094 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14095 Results.push_back(Result.getValue(2));
14098 /// ReplaceNodeResults - Replace a node with an illegal result type
14099 /// with a new node built out of custom code.
14100 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14101 SmallVectorImpl<SDValue>&Results,
14102 SelectionDAG &DAG) const {
14104 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14105 switch (N->getOpcode()) {
14107 llvm_unreachable("Do not know how to custom type legalize this operation!");
14108 case ISD::SIGN_EXTEND_INREG:
14113 // We don't want to expand or promote these.
14115 case ISD::FP_TO_SINT:
14116 case ISD::FP_TO_UINT: {
14117 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14119 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14122 std::pair<SDValue,SDValue> Vals =
14123 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14124 SDValue FIST = Vals.first, StackSlot = Vals.second;
14125 if (FIST.getNode() != 0) {
14126 EVT VT = N->getValueType(0);
14127 // Return a load from the stack slot.
14128 if (StackSlot.getNode() != 0)
14129 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14130 MachinePointerInfo(),
14131 false, false, false, 0));
14133 Results.push_back(FIST);
14137 case ISD::UINT_TO_FP: {
14138 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14139 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14140 N->getValueType(0) != MVT::v2f32)
14142 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14144 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14146 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14147 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14148 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14149 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14150 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14151 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14154 case ISD::FP_ROUND: {
14155 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14157 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14158 Results.push_back(V);
14161 case ISD::READCYCLECOUNTER: {
14162 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14163 SDValue TheChain = N->getOperand(0);
14164 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
14165 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
14167 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
14169 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14170 SDValue Ops[] = { eax, edx };
14171 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
14172 array_lengthof(Ops)));
14173 Results.push_back(edx.getValue(1));
14176 case ISD::ATOMIC_CMP_SWAP: {
14177 EVT T = N->getValueType(0);
14178 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14179 bool Regs64bit = T == MVT::i128;
14180 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14181 SDValue cpInL, cpInH;
14182 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14183 DAG.getConstant(0, HalfT));
14184 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14185 DAG.getConstant(1, HalfT));
14186 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14187 Regs64bit ? X86::RAX : X86::EAX,
14189 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14190 Regs64bit ? X86::RDX : X86::EDX,
14191 cpInH, cpInL.getValue(1));
14192 SDValue swapInL, swapInH;
14193 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14194 DAG.getConstant(0, HalfT));
14195 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14196 DAG.getConstant(1, HalfT));
14197 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14198 Regs64bit ? X86::RBX : X86::EBX,
14199 swapInL, cpInH.getValue(1));
14200 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14201 Regs64bit ? X86::RCX : X86::ECX,
14202 swapInH, swapInL.getValue(1));
14203 SDValue Ops[] = { swapInH.getValue(0),
14205 swapInH.getValue(1) };
14206 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14207 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14208 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14209 X86ISD::LCMPXCHG8_DAG;
14210 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14211 Ops, array_lengthof(Ops), T, MMO);
14212 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14213 Regs64bit ? X86::RAX : X86::EAX,
14214 HalfT, Result.getValue(1));
14215 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14216 Regs64bit ? X86::RDX : X86::EDX,
14217 HalfT, cpOutL.getValue(2));
14218 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14219 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14220 Results.push_back(cpOutH.getValue(1));
14223 case ISD::ATOMIC_LOAD_ADD:
14224 case ISD::ATOMIC_LOAD_AND:
14225 case ISD::ATOMIC_LOAD_NAND:
14226 case ISD::ATOMIC_LOAD_OR:
14227 case ISD::ATOMIC_LOAD_SUB:
14228 case ISD::ATOMIC_LOAD_XOR:
14229 case ISD::ATOMIC_LOAD_MAX:
14230 case ISD::ATOMIC_LOAD_MIN:
14231 case ISD::ATOMIC_LOAD_UMAX:
14232 case ISD::ATOMIC_LOAD_UMIN:
14233 case ISD::ATOMIC_SWAP: {
14235 switch (N->getOpcode()) {
14236 default: llvm_unreachable("Unexpected opcode");
14237 case ISD::ATOMIC_LOAD_ADD:
14238 Opc = X86ISD::ATOMADD64_DAG;
14240 case ISD::ATOMIC_LOAD_AND:
14241 Opc = X86ISD::ATOMAND64_DAG;
14243 case ISD::ATOMIC_LOAD_NAND:
14244 Opc = X86ISD::ATOMNAND64_DAG;
14246 case ISD::ATOMIC_LOAD_OR:
14247 Opc = X86ISD::ATOMOR64_DAG;
14249 case ISD::ATOMIC_LOAD_SUB:
14250 Opc = X86ISD::ATOMSUB64_DAG;
14252 case ISD::ATOMIC_LOAD_XOR:
14253 Opc = X86ISD::ATOMXOR64_DAG;
14255 case ISD::ATOMIC_LOAD_MAX:
14256 Opc = X86ISD::ATOMMAX64_DAG;
14258 case ISD::ATOMIC_LOAD_MIN:
14259 Opc = X86ISD::ATOMMIN64_DAG;
14261 case ISD::ATOMIC_LOAD_UMAX:
14262 Opc = X86ISD::ATOMUMAX64_DAG;
14264 case ISD::ATOMIC_LOAD_UMIN:
14265 Opc = X86ISD::ATOMUMIN64_DAG;
14267 case ISD::ATOMIC_SWAP:
14268 Opc = X86ISD::ATOMSWAP64_DAG;
14271 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14274 case ISD::ATOMIC_LOAD:
14275 ReplaceATOMIC_LOAD(N, Results, DAG);
14279 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14281 default: return NULL;
14282 case X86ISD::BSF: return "X86ISD::BSF";
14283 case X86ISD::BSR: return "X86ISD::BSR";
14284 case X86ISD::SHLD: return "X86ISD::SHLD";
14285 case X86ISD::SHRD: return "X86ISD::SHRD";
14286 case X86ISD::FAND: return "X86ISD::FAND";
14287 case X86ISD::FANDN: return "X86ISD::FANDN";
14288 case X86ISD::FOR: return "X86ISD::FOR";
14289 case X86ISD::FXOR: return "X86ISD::FXOR";
14290 case X86ISD::FSRL: return "X86ISD::FSRL";
14291 case X86ISD::FILD: return "X86ISD::FILD";
14292 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14293 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14294 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14295 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14296 case X86ISD::FLD: return "X86ISD::FLD";
14297 case X86ISD::FST: return "X86ISD::FST";
14298 case X86ISD::CALL: return "X86ISD::CALL";
14299 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14300 case X86ISD::BT: return "X86ISD::BT";
14301 case X86ISD::CMP: return "X86ISD::CMP";
14302 case X86ISD::COMI: return "X86ISD::COMI";
14303 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14304 case X86ISD::CMPM: return "X86ISD::CMPM";
14305 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14306 case X86ISD::SETCC: return "X86ISD::SETCC";
14307 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14308 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14309 case X86ISD::CMOV: return "X86ISD::CMOV";
14310 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14311 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14312 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14313 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14314 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14315 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14316 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14317 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14318 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14319 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14320 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14321 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14322 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14323 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14324 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14325 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14326 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14327 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14328 case X86ISD::HADD: return "X86ISD::HADD";
14329 case X86ISD::HSUB: return "X86ISD::HSUB";
14330 case X86ISD::FHADD: return "X86ISD::FHADD";
14331 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14332 case X86ISD::UMAX: return "X86ISD::UMAX";
14333 case X86ISD::UMIN: return "X86ISD::UMIN";
14334 case X86ISD::SMAX: return "X86ISD::SMAX";
14335 case X86ISD::SMIN: return "X86ISD::SMIN";
14336 case X86ISD::FMAX: return "X86ISD::FMAX";
14337 case X86ISD::FMIN: return "X86ISD::FMIN";
14338 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14339 case X86ISD::FMINC: return "X86ISD::FMINC";
14340 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14341 case X86ISD::FRCP: return "X86ISD::FRCP";
14342 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14343 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14344 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14345 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14346 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14347 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14348 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14349 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14350 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14351 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14352 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14353 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14354 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14355 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14356 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14357 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14358 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14359 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14360 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14361 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14362 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14363 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14364 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14365 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14366 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14367 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14368 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14369 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14370 case X86ISD::VSHL: return "X86ISD::VSHL";
14371 case X86ISD::VSRL: return "X86ISD::VSRL";
14372 case X86ISD::VSRA: return "X86ISD::VSRA";
14373 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14374 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14375 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14376 case X86ISD::CMPP: return "X86ISD::CMPP";
14377 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14378 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14379 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14380 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14381 case X86ISD::ADD: return "X86ISD::ADD";
14382 case X86ISD::SUB: return "X86ISD::SUB";
14383 case X86ISD::ADC: return "X86ISD::ADC";
14384 case X86ISD::SBB: return "X86ISD::SBB";
14385 case X86ISD::SMUL: return "X86ISD::SMUL";
14386 case X86ISD::UMUL: return "X86ISD::UMUL";
14387 case X86ISD::INC: return "X86ISD::INC";
14388 case X86ISD::DEC: return "X86ISD::DEC";
14389 case X86ISD::OR: return "X86ISD::OR";
14390 case X86ISD::XOR: return "X86ISD::XOR";
14391 case X86ISD::AND: return "X86ISD::AND";
14392 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14393 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14394 case X86ISD::PTEST: return "X86ISD::PTEST";
14395 case X86ISD::TESTP: return "X86ISD::TESTP";
14396 case X86ISD::TESTM: return "X86ISD::TESTM";
14397 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14398 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14399 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14400 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14401 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14402 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14403 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14404 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14405 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14406 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14407 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14408 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14409 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14410 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14411 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14412 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14413 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14414 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14415 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14416 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14417 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14418 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14419 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14420 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14421 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14422 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14423 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14424 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14425 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14426 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14427 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14428 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14429 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14430 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14431 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14432 case X86ISD::SAHF: return "X86ISD::SAHF";
14433 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14434 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14435 case X86ISD::FMADD: return "X86ISD::FMADD";
14436 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14437 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14438 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14439 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14440 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14441 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14442 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14443 case X86ISD::XTEST: return "X86ISD::XTEST";
14447 // isLegalAddressingMode - Return true if the addressing mode represented
14448 // by AM is legal for this target, for a load/store of the specified type.
14449 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14451 // X86 supports extremely general addressing modes.
14452 CodeModel::Model M = getTargetMachine().getCodeModel();
14453 Reloc::Model R = getTargetMachine().getRelocationModel();
14455 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14456 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14461 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14463 // If a reference to this global requires an extra load, we can't fold it.
14464 if (isGlobalStubReference(GVFlags))
14467 // If BaseGV requires a register for the PIC base, we cannot also have a
14468 // BaseReg specified.
14469 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14472 // If lower 4G is not available, then we must use rip-relative addressing.
14473 if ((M != CodeModel::Small || R != Reloc::Static) &&
14474 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14478 switch (AM.Scale) {
14484 // These scales always work.
14489 // These scales are formed with basereg+scalereg. Only accept if there is
14494 default: // Other stuff never works.
14501 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14502 unsigned Bits = Ty->getScalarSizeInBits();
14504 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14505 // particularly cheaper than those without.
14509 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14510 // variable shifts just as cheap as scalar ones.
14511 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14514 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14515 // fully general vector.
14519 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14520 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14522 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14523 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14524 return NumBits1 > NumBits2;
14527 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14528 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14531 if (!isTypeLegal(EVT::getEVT(Ty1)))
14534 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14536 // Assuming the caller doesn't have a zeroext or signext return parameter,
14537 // truncation all the way down to i1 is valid.
14541 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14542 return isInt<32>(Imm);
14545 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14546 // Can also use sub to handle negated immediates.
14547 return isInt<32>(Imm);
14550 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14551 if (!VT1.isInteger() || !VT2.isInteger())
14553 unsigned NumBits1 = VT1.getSizeInBits();
14554 unsigned NumBits2 = VT2.getSizeInBits();
14555 return NumBits1 > NumBits2;
14558 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14559 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14560 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14563 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14564 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14565 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14568 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14569 EVT VT1 = Val.getValueType();
14570 if (isZExtFree(VT1, VT2))
14573 if (Val.getOpcode() != ISD::LOAD)
14576 if (!VT1.isSimple() || !VT1.isInteger() ||
14577 !VT2.isSimple() || !VT2.isInteger())
14580 switch (VT1.getSimpleVT().SimpleTy) {
14585 // X86 has 8, 16, and 32-bit zero-extending loads.
14593 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14594 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14597 VT = VT.getScalarType();
14599 if (!VT.isSimple())
14602 switch (VT.getSimpleVT().SimpleTy) {
14613 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14614 // i16 instructions are longer (0x66 prefix) and potentially slower.
14615 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14618 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14619 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14620 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14621 /// are assumed to be legal.
14623 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14625 if (!VT.isSimple())
14628 MVT SVT = VT.getSimpleVT();
14630 // Very little shuffling can be done for 64-bit vectors right now.
14631 if (VT.getSizeInBits() == 64)
14634 // FIXME: pshufb, blends, shifts.
14635 return (SVT.getVectorNumElements() == 2 ||
14636 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14637 isMOVLMask(M, SVT) ||
14638 isSHUFPMask(M, SVT) ||
14639 isPSHUFDMask(M, SVT) ||
14640 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14641 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14642 isPALIGNRMask(M, SVT, Subtarget) ||
14643 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14644 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14645 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14646 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14650 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14652 if (!VT.isSimple())
14655 MVT SVT = VT.getSimpleVT();
14656 unsigned NumElts = SVT.getVectorNumElements();
14657 // FIXME: This collection of masks seems suspect.
14660 if (NumElts == 4 && SVT.is128BitVector()) {
14661 return (isMOVLMask(Mask, SVT) ||
14662 isCommutedMOVLMask(Mask, SVT, true) ||
14663 isSHUFPMask(Mask, SVT) ||
14664 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14669 //===----------------------------------------------------------------------===//
14670 // X86 Scheduler Hooks
14671 //===----------------------------------------------------------------------===//
14673 /// Utility function to emit xbegin specifying the start of an RTM region.
14674 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14675 const TargetInstrInfo *TII) {
14676 DebugLoc DL = MI->getDebugLoc();
14678 const BasicBlock *BB = MBB->getBasicBlock();
14679 MachineFunction::iterator I = MBB;
14682 // For the v = xbegin(), we generate
14693 MachineBasicBlock *thisMBB = MBB;
14694 MachineFunction *MF = MBB->getParent();
14695 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14696 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14697 MF->insert(I, mainMBB);
14698 MF->insert(I, sinkMBB);
14700 // Transfer the remainder of BB and its successor edges to sinkMBB.
14701 sinkMBB->splice(sinkMBB->begin(), MBB,
14702 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14703 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14707 // # fallthrough to mainMBB
14708 // # abortion to sinkMBB
14709 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14710 thisMBB->addSuccessor(mainMBB);
14711 thisMBB->addSuccessor(sinkMBB);
14715 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14716 mainMBB->addSuccessor(sinkMBB);
14719 // EAX is live into the sinkMBB
14720 sinkMBB->addLiveIn(X86::EAX);
14721 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14722 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14725 MI->eraseFromParent();
14729 // Get CMPXCHG opcode for the specified data type.
14730 static unsigned getCmpXChgOpcode(EVT VT) {
14731 switch (VT.getSimpleVT().SimpleTy) {
14732 case MVT::i8: return X86::LCMPXCHG8;
14733 case MVT::i16: return X86::LCMPXCHG16;
14734 case MVT::i32: return X86::LCMPXCHG32;
14735 case MVT::i64: return X86::LCMPXCHG64;
14739 llvm_unreachable("Invalid operand size!");
14742 // Get LOAD opcode for the specified data type.
14743 static unsigned getLoadOpcode(EVT VT) {
14744 switch (VT.getSimpleVT().SimpleTy) {
14745 case MVT::i8: return X86::MOV8rm;
14746 case MVT::i16: return X86::MOV16rm;
14747 case MVT::i32: return X86::MOV32rm;
14748 case MVT::i64: return X86::MOV64rm;
14752 llvm_unreachable("Invalid operand size!");
14755 // Get opcode of the non-atomic one from the specified atomic instruction.
14756 static unsigned getNonAtomicOpcode(unsigned Opc) {
14758 case X86::ATOMAND8: return X86::AND8rr;
14759 case X86::ATOMAND16: return X86::AND16rr;
14760 case X86::ATOMAND32: return X86::AND32rr;
14761 case X86::ATOMAND64: return X86::AND64rr;
14762 case X86::ATOMOR8: return X86::OR8rr;
14763 case X86::ATOMOR16: return X86::OR16rr;
14764 case X86::ATOMOR32: return X86::OR32rr;
14765 case X86::ATOMOR64: return X86::OR64rr;
14766 case X86::ATOMXOR8: return X86::XOR8rr;
14767 case X86::ATOMXOR16: return X86::XOR16rr;
14768 case X86::ATOMXOR32: return X86::XOR32rr;
14769 case X86::ATOMXOR64: return X86::XOR64rr;
14771 llvm_unreachable("Unhandled atomic-load-op opcode!");
14774 // Get opcode of the non-atomic one from the specified atomic instruction with
14776 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14777 unsigned &ExtraOpc) {
14779 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14780 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14781 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14782 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14783 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14784 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14785 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14786 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14787 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14788 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14789 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14790 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14791 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14792 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14793 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14794 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14795 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14796 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14797 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14798 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14800 llvm_unreachable("Unhandled atomic-load-op opcode!");
14803 // Get opcode of the non-atomic one from the specified atomic instruction for
14804 // 64-bit data type on 32-bit target.
14805 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14807 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14808 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14809 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14810 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14811 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14812 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14813 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14814 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14815 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14816 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14818 llvm_unreachable("Unhandled atomic-load-op opcode!");
14821 // Get opcode of the non-atomic one from the specified atomic instruction for
14822 // 64-bit data type on 32-bit target with extra opcode.
14823 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14825 unsigned &ExtraOpc) {
14827 case X86::ATOMNAND6432:
14828 ExtraOpc = X86::NOT32r;
14829 HiOpc = X86::AND32rr;
14830 return X86::AND32rr;
14832 llvm_unreachable("Unhandled atomic-load-op opcode!");
14835 // Get pseudo CMOV opcode from the specified data type.
14836 static unsigned getPseudoCMOVOpc(EVT VT) {
14837 switch (VT.getSimpleVT().SimpleTy) {
14838 case MVT::i8: return X86::CMOV_GR8;
14839 case MVT::i16: return X86::CMOV_GR16;
14840 case MVT::i32: return X86::CMOV_GR32;
14844 llvm_unreachable("Unknown CMOV opcode!");
14847 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14848 // They will be translated into a spin-loop or compare-exchange loop from
14851 // dst = atomic-fetch-op MI.addr, MI.val
14857 // t1 = LOAD MI.addr
14859 // t4 = phi(t1, t3 / loop)
14860 // t2 = OP MI.val, t4
14862 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14868 MachineBasicBlock *
14869 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14870 MachineBasicBlock *MBB) const {
14871 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14872 DebugLoc DL = MI->getDebugLoc();
14874 MachineFunction *MF = MBB->getParent();
14875 MachineRegisterInfo &MRI = MF->getRegInfo();
14877 const BasicBlock *BB = MBB->getBasicBlock();
14878 MachineFunction::iterator I = MBB;
14881 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14882 "Unexpected number of operands");
14884 assert(MI->hasOneMemOperand() &&
14885 "Expected atomic-load-op to have one memoperand");
14887 // Memory Reference
14888 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14889 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14891 unsigned DstReg, SrcReg;
14892 unsigned MemOpndSlot;
14894 unsigned CurOp = 0;
14896 DstReg = MI->getOperand(CurOp++).getReg();
14897 MemOpndSlot = CurOp;
14898 CurOp += X86::AddrNumOperands;
14899 SrcReg = MI->getOperand(CurOp++).getReg();
14901 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14902 MVT::SimpleValueType VT = *RC->vt_begin();
14903 unsigned t1 = MRI.createVirtualRegister(RC);
14904 unsigned t2 = MRI.createVirtualRegister(RC);
14905 unsigned t3 = MRI.createVirtualRegister(RC);
14906 unsigned t4 = MRI.createVirtualRegister(RC);
14907 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14909 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14910 unsigned LOADOpc = getLoadOpcode(VT);
14912 // For the atomic load-arith operator, we generate
14915 // t1 = LOAD [MI.addr]
14917 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14918 // t1 = OP MI.val, EAX
14920 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14926 MachineBasicBlock *thisMBB = MBB;
14927 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14928 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14929 MF->insert(I, mainMBB);
14930 MF->insert(I, sinkMBB);
14932 MachineInstrBuilder MIB;
14934 // Transfer the remainder of BB and its successor edges to sinkMBB.
14935 sinkMBB->splice(sinkMBB->begin(), MBB,
14936 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14937 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14940 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14941 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14942 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14944 NewMO.setIsKill(false);
14945 MIB.addOperand(NewMO);
14947 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14948 unsigned flags = (*MMOI)->getFlags();
14949 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14950 MachineMemOperand *MMO =
14951 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14952 (*MMOI)->getSize(),
14953 (*MMOI)->getBaseAlignment(),
14954 (*MMOI)->getTBAAInfo(),
14955 (*MMOI)->getRanges());
14956 MIB.addMemOperand(MMO);
14959 thisMBB->addSuccessor(mainMBB);
14962 MachineBasicBlock *origMainMBB = mainMBB;
14965 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14966 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14968 unsigned Opc = MI->getOpcode();
14971 llvm_unreachable("Unhandled atomic-load-op opcode!");
14972 case X86::ATOMAND8:
14973 case X86::ATOMAND16:
14974 case X86::ATOMAND32:
14975 case X86::ATOMAND64:
14977 case X86::ATOMOR16:
14978 case X86::ATOMOR32:
14979 case X86::ATOMOR64:
14980 case X86::ATOMXOR8:
14981 case X86::ATOMXOR16:
14982 case X86::ATOMXOR32:
14983 case X86::ATOMXOR64: {
14984 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14985 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14989 case X86::ATOMNAND8:
14990 case X86::ATOMNAND16:
14991 case X86::ATOMNAND32:
14992 case X86::ATOMNAND64: {
14993 unsigned Tmp = MRI.createVirtualRegister(RC);
14995 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14996 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14998 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15001 case X86::ATOMMAX8:
15002 case X86::ATOMMAX16:
15003 case X86::ATOMMAX32:
15004 case X86::ATOMMAX64:
15005 case X86::ATOMMIN8:
15006 case X86::ATOMMIN16:
15007 case X86::ATOMMIN32:
15008 case X86::ATOMMIN64:
15009 case X86::ATOMUMAX8:
15010 case X86::ATOMUMAX16:
15011 case X86::ATOMUMAX32:
15012 case X86::ATOMUMAX64:
15013 case X86::ATOMUMIN8:
15014 case X86::ATOMUMIN16:
15015 case X86::ATOMUMIN32:
15016 case X86::ATOMUMIN64: {
15018 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15020 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15024 if (Subtarget->hasCMov()) {
15025 if (VT != MVT::i8) {
15027 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15031 // Promote i8 to i32 to use CMOV32
15032 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15033 const TargetRegisterClass *RC32 =
15034 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15035 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15036 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15037 unsigned Tmp = MRI.createVirtualRegister(RC32);
15039 unsigned Undef = MRI.createVirtualRegister(RC32);
15040 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15042 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15045 .addImm(X86::sub_8bit);
15046 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15049 .addImm(X86::sub_8bit);
15051 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15055 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15056 .addReg(Tmp, 0, X86::sub_8bit);
15059 // Use pseudo select and lower them.
15060 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15061 "Invalid atomic-load-op transformation!");
15062 unsigned SelOpc = getPseudoCMOVOpc(VT);
15063 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15064 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15065 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15066 .addReg(SrcReg).addReg(t4)
15068 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15069 // Replace the original PHI node as mainMBB is changed after CMOV
15071 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15072 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15073 Phi->eraseFromParent();
15079 // Copy PhyReg back from virtual register.
15080 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15083 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15084 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15085 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15087 NewMO.setIsKill(false);
15088 MIB.addOperand(NewMO);
15091 MIB.setMemRefs(MMOBegin, MMOEnd);
15093 // Copy PhyReg back to virtual register.
15094 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15097 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15099 mainMBB->addSuccessor(origMainMBB);
15100 mainMBB->addSuccessor(sinkMBB);
15103 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15104 TII->get(TargetOpcode::COPY), DstReg)
15107 MI->eraseFromParent();
15111 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15112 // instructions. They will be translated into a spin-loop or compare-exchange
15116 // dst = atomic-fetch-op MI.addr, MI.val
15122 // t1L = LOAD [MI.addr + 0]
15123 // t1H = LOAD [MI.addr + 4]
15125 // t4L = phi(t1L, t3L / loop)
15126 // t4H = phi(t1H, t3H / loop)
15127 // t2L = OP MI.val.lo, t4L
15128 // t2H = OP MI.val.hi, t4H
15133 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15141 MachineBasicBlock *
15142 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15143 MachineBasicBlock *MBB) const {
15144 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15145 DebugLoc DL = MI->getDebugLoc();
15147 MachineFunction *MF = MBB->getParent();
15148 MachineRegisterInfo &MRI = MF->getRegInfo();
15150 const BasicBlock *BB = MBB->getBasicBlock();
15151 MachineFunction::iterator I = MBB;
15154 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15155 "Unexpected number of operands");
15157 assert(MI->hasOneMemOperand() &&
15158 "Expected atomic-load-op32 to have one memoperand");
15160 // Memory Reference
15161 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15162 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15164 unsigned DstLoReg, DstHiReg;
15165 unsigned SrcLoReg, SrcHiReg;
15166 unsigned MemOpndSlot;
15168 unsigned CurOp = 0;
15170 DstLoReg = MI->getOperand(CurOp++).getReg();
15171 DstHiReg = MI->getOperand(CurOp++).getReg();
15172 MemOpndSlot = CurOp;
15173 CurOp += X86::AddrNumOperands;
15174 SrcLoReg = MI->getOperand(CurOp++).getReg();
15175 SrcHiReg = MI->getOperand(CurOp++).getReg();
15177 const TargetRegisterClass *RC = &X86::GR32RegClass;
15178 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15180 unsigned t1L = MRI.createVirtualRegister(RC);
15181 unsigned t1H = MRI.createVirtualRegister(RC);
15182 unsigned t2L = MRI.createVirtualRegister(RC);
15183 unsigned t2H = MRI.createVirtualRegister(RC);
15184 unsigned t3L = MRI.createVirtualRegister(RC);
15185 unsigned t3H = MRI.createVirtualRegister(RC);
15186 unsigned t4L = MRI.createVirtualRegister(RC);
15187 unsigned t4H = MRI.createVirtualRegister(RC);
15189 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15190 unsigned LOADOpc = X86::MOV32rm;
15192 // For the atomic load-arith operator, we generate
15195 // t1L = LOAD [MI.addr + 0]
15196 // t1H = LOAD [MI.addr + 4]
15198 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15199 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15200 // t2L = OP MI.val.lo, t4L
15201 // t2H = OP MI.val.hi, t4H
15204 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15212 MachineBasicBlock *thisMBB = MBB;
15213 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15214 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15215 MF->insert(I, mainMBB);
15216 MF->insert(I, sinkMBB);
15218 MachineInstrBuilder MIB;
15220 // Transfer the remainder of BB and its successor edges to sinkMBB.
15221 sinkMBB->splice(sinkMBB->begin(), MBB,
15222 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15223 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15227 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15228 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15229 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15231 NewMO.setIsKill(false);
15232 MIB.addOperand(NewMO);
15234 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15235 unsigned flags = (*MMOI)->getFlags();
15236 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15237 MachineMemOperand *MMO =
15238 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15239 (*MMOI)->getSize(),
15240 (*MMOI)->getBaseAlignment(),
15241 (*MMOI)->getTBAAInfo(),
15242 (*MMOI)->getRanges());
15243 MIB.addMemOperand(MMO);
15245 MachineInstr *LowMI = MIB;
15248 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15249 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15250 if (i == X86::AddrDisp) {
15251 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15253 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15255 NewMO.setIsKill(false);
15256 MIB.addOperand(NewMO);
15259 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15261 thisMBB->addSuccessor(mainMBB);
15264 MachineBasicBlock *origMainMBB = mainMBB;
15267 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15268 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15269 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15270 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15272 unsigned Opc = MI->getOpcode();
15275 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15276 case X86::ATOMAND6432:
15277 case X86::ATOMOR6432:
15278 case X86::ATOMXOR6432:
15279 case X86::ATOMADD6432:
15280 case X86::ATOMSUB6432: {
15282 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15283 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15285 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15289 case X86::ATOMNAND6432: {
15290 unsigned HiOpc, NOTOpc;
15291 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15292 unsigned TmpL = MRI.createVirtualRegister(RC);
15293 unsigned TmpH = MRI.createVirtualRegister(RC);
15294 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15296 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15298 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15299 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15302 case X86::ATOMMAX6432:
15303 case X86::ATOMMIN6432:
15304 case X86::ATOMUMAX6432:
15305 case X86::ATOMUMIN6432: {
15307 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15308 unsigned cL = MRI.createVirtualRegister(RC8);
15309 unsigned cH = MRI.createVirtualRegister(RC8);
15310 unsigned cL32 = MRI.createVirtualRegister(RC);
15311 unsigned cH32 = MRI.createVirtualRegister(RC);
15312 unsigned cc = MRI.createVirtualRegister(RC);
15313 // cl := cmp src_lo, lo
15314 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15315 .addReg(SrcLoReg).addReg(t4L);
15316 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15317 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15318 // ch := cmp src_hi, hi
15319 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15320 .addReg(SrcHiReg).addReg(t4H);
15321 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15322 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15323 // cc := if (src_hi == hi) ? cl : ch;
15324 if (Subtarget->hasCMov()) {
15325 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15326 .addReg(cH32).addReg(cL32);
15328 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15329 .addReg(cH32).addReg(cL32)
15330 .addImm(X86::COND_E);
15331 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15333 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15334 if (Subtarget->hasCMov()) {
15335 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15336 .addReg(SrcLoReg).addReg(t4L);
15337 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15338 .addReg(SrcHiReg).addReg(t4H);
15340 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15341 .addReg(SrcLoReg).addReg(t4L)
15342 .addImm(X86::COND_NE);
15343 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15344 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15345 // 2nd CMOV lowering.
15346 mainMBB->addLiveIn(X86::EFLAGS);
15347 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15348 .addReg(SrcHiReg).addReg(t4H)
15349 .addImm(X86::COND_NE);
15350 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15351 // Replace the original PHI node as mainMBB is changed after CMOV
15353 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15354 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15355 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15356 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15357 PhiL->eraseFromParent();
15358 PhiH->eraseFromParent();
15362 case X86::ATOMSWAP6432: {
15364 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15365 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15366 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15371 // Copy EDX:EAX back from HiReg:LoReg
15372 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15373 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15374 // Copy ECX:EBX from t1H:t1L
15375 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15376 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15378 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15379 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15380 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15382 NewMO.setIsKill(false);
15383 MIB.addOperand(NewMO);
15385 MIB.setMemRefs(MMOBegin, MMOEnd);
15387 // Copy EDX:EAX back to t3H:t3L
15388 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15389 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15391 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15393 mainMBB->addSuccessor(origMainMBB);
15394 mainMBB->addSuccessor(sinkMBB);
15397 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15398 TII->get(TargetOpcode::COPY), DstLoReg)
15400 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15401 TII->get(TargetOpcode::COPY), DstHiReg)
15404 MI->eraseFromParent();
15408 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15409 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15410 // in the .td file.
15411 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15412 const TargetInstrInfo *TII) {
15414 switch (MI->getOpcode()) {
15415 default: llvm_unreachable("illegal opcode!");
15416 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15417 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15418 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15419 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15420 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15421 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15422 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15423 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15426 DebugLoc dl = MI->getDebugLoc();
15427 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15429 unsigned NumArgs = MI->getNumOperands();
15430 for (unsigned i = 1; i < NumArgs; ++i) {
15431 MachineOperand &Op = MI->getOperand(i);
15432 if (!(Op.isReg() && Op.isImplicit()))
15433 MIB.addOperand(Op);
15435 if (MI->hasOneMemOperand())
15436 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15438 BuildMI(*BB, MI, dl,
15439 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15440 .addReg(X86::XMM0);
15442 MI->eraseFromParent();
15446 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15447 // defs in an instruction pattern
15448 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15449 const TargetInstrInfo *TII) {
15451 switch (MI->getOpcode()) {
15452 default: llvm_unreachable("illegal opcode!");
15453 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15454 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15455 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15456 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15457 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15458 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15459 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15460 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15463 DebugLoc dl = MI->getDebugLoc();
15464 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15466 unsigned NumArgs = MI->getNumOperands(); // remove the results
15467 for (unsigned i = 1; i < NumArgs; ++i) {
15468 MachineOperand &Op = MI->getOperand(i);
15469 if (!(Op.isReg() && Op.isImplicit()))
15470 MIB.addOperand(Op);
15472 if (MI->hasOneMemOperand())
15473 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15475 BuildMI(*BB, MI, dl,
15476 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15479 MI->eraseFromParent();
15483 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15484 const TargetInstrInfo *TII,
15485 const X86Subtarget* Subtarget) {
15486 DebugLoc dl = MI->getDebugLoc();
15488 // Address into RAX/EAX, other two args into ECX, EDX.
15489 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15490 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15491 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15492 for (int i = 0; i < X86::AddrNumOperands; ++i)
15493 MIB.addOperand(MI->getOperand(i));
15495 unsigned ValOps = X86::AddrNumOperands;
15496 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15497 .addReg(MI->getOperand(ValOps).getReg());
15498 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15499 .addReg(MI->getOperand(ValOps+1).getReg());
15501 // The instruction doesn't actually take any operands though.
15502 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15504 MI->eraseFromParent(); // The pseudo is gone now.
15508 MachineBasicBlock *
15509 X86TargetLowering::EmitVAARG64WithCustomInserter(
15511 MachineBasicBlock *MBB) const {
15512 // Emit va_arg instruction on X86-64.
15514 // Operands to this pseudo-instruction:
15515 // 0 ) Output : destination address (reg)
15516 // 1-5) Input : va_list address (addr, i64mem)
15517 // 6 ) ArgSize : Size (in bytes) of vararg type
15518 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15519 // 8 ) Align : Alignment of type
15520 // 9 ) EFLAGS (implicit-def)
15522 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15523 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15525 unsigned DestReg = MI->getOperand(0).getReg();
15526 MachineOperand &Base = MI->getOperand(1);
15527 MachineOperand &Scale = MI->getOperand(2);
15528 MachineOperand &Index = MI->getOperand(3);
15529 MachineOperand &Disp = MI->getOperand(4);
15530 MachineOperand &Segment = MI->getOperand(5);
15531 unsigned ArgSize = MI->getOperand(6).getImm();
15532 unsigned ArgMode = MI->getOperand(7).getImm();
15533 unsigned Align = MI->getOperand(8).getImm();
15535 // Memory Reference
15536 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15537 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15538 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15540 // Machine Information
15541 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15542 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15543 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15544 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15545 DebugLoc DL = MI->getDebugLoc();
15547 // struct va_list {
15550 // i64 overflow_area (address)
15551 // i64 reg_save_area (address)
15553 // sizeof(va_list) = 24
15554 // alignment(va_list) = 8
15556 unsigned TotalNumIntRegs = 6;
15557 unsigned TotalNumXMMRegs = 8;
15558 bool UseGPOffset = (ArgMode == 1);
15559 bool UseFPOffset = (ArgMode == 2);
15560 unsigned MaxOffset = TotalNumIntRegs * 8 +
15561 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15563 /* Align ArgSize to a multiple of 8 */
15564 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15565 bool NeedsAlign = (Align > 8);
15567 MachineBasicBlock *thisMBB = MBB;
15568 MachineBasicBlock *overflowMBB;
15569 MachineBasicBlock *offsetMBB;
15570 MachineBasicBlock *endMBB;
15572 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15573 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15574 unsigned OffsetReg = 0;
15576 if (!UseGPOffset && !UseFPOffset) {
15577 // If we only pull from the overflow region, we don't create a branch.
15578 // We don't need to alter control flow.
15579 OffsetDestReg = 0; // unused
15580 OverflowDestReg = DestReg;
15583 overflowMBB = thisMBB;
15586 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15587 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15588 // If not, pull from overflow_area. (branch to overflowMBB)
15593 // offsetMBB overflowMBB
15598 // Registers for the PHI in endMBB
15599 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15600 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15602 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15603 MachineFunction *MF = MBB->getParent();
15604 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15605 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15606 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15608 MachineFunction::iterator MBBIter = MBB;
15611 // Insert the new basic blocks
15612 MF->insert(MBBIter, offsetMBB);
15613 MF->insert(MBBIter, overflowMBB);
15614 MF->insert(MBBIter, endMBB);
15616 // Transfer the remainder of MBB and its successor edges to endMBB.
15617 endMBB->splice(endMBB->begin(), thisMBB,
15618 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15619 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15621 // Make offsetMBB and overflowMBB successors of thisMBB
15622 thisMBB->addSuccessor(offsetMBB);
15623 thisMBB->addSuccessor(overflowMBB);
15625 // endMBB is a successor of both offsetMBB and overflowMBB
15626 offsetMBB->addSuccessor(endMBB);
15627 overflowMBB->addSuccessor(endMBB);
15629 // Load the offset value into a register
15630 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15631 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15635 .addDisp(Disp, UseFPOffset ? 4 : 0)
15636 .addOperand(Segment)
15637 .setMemRefs(MMOBegin, MMOEnd);
15639 // Check if there is enough room left to pull this argument.
15640 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15642 .addImm(MaxOffset + 8 - ArgSizeA8);
15644 // Branch to "overflowMBB" if offset >= max
15645 // Fall through to "offsetMBB" otherwise
15646 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15647 .addMBB(overflowMBB);
15650 // In offsetMBB, emit code to use the reg_save_area.
15652 assert(OffsetReg != 0);
15654 // Read the reg_save_area address.
15655 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15656 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15661 .addOperand(Segment)
15662 .setMemRefs(MMOBegin, MMOEnd);
15664 // Zero-extend the offset
15665 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15666 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15669 .addImm(X86::sub_32bit);
15671 // Add the offset to the reg_save_area to get the final address.
15672 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15673 .addReg(OffsetReg64)
15674 .addReg(RegSaveReg);
15676 // Compute the offset for the next argument
15677 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15678 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15680 .addImm(UseFPOffset ? 16 : 8);
15682 // Store it back into the va_list.
15683 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15687 .addDisp(Disp, UseFPOffset ? 4 : 0)
15688 .addOperand(Segment)
15689 .addReg(NextOffsetReg)
15690 .setMemRefs(MMOBegin, MMOEnd);
15693 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15698 // Emit code to use overflow area
15701 // Load the overflow_area address into a register.
15702 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15703 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15708 .addOperand(Segment)
15709 .setMemRefs(MMOBegin, MMOEnd);
15711 // If we need to align it, do so. Otherwise, just copy the address
15712 // to OverflowDestReg.
15714 // Align the overflow address
15715 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15716 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15718 // aligned_addr = (addr + (align-1)) & ~(align-1)
15719 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15720 .addReg(OverflowAddrReg)
15723 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15725 .addImm(~(uint64_t)(Align-1));
15727 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15728 .addReg(OverflowAddrReg);
15731 // Compute the next overflow address after this argument.
15732 // (the overflow address should be kept 8-byte aligned)
15733 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15734 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15735 .addReg(OverflowDestReg)
15736 .addImm(ArgSizeA8);
15738 // Store the new overflow address.
15739 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15744 .addOperand(Segment)
15745 .addReg(NextAddrReg)
15746 .setMemRefs(MMOBegin, MMOEnd);
15748 // If we branched, emit the PHI to the front of endMBB.
15750 BuildMI(*endMBB, endMBB->begin(), DL,
15751 TII->get(X86::PHI), DestReg)
15752 .addReg(OffsetDestReg).addMBB(offsetMBB)
15753 .addReg(OverflowDestReg).addMBB(overflowMBB);
15756 // Erase the pseudo instruction
15757 MI->eraseFromParent();
15762 MachineBasicBlock *
15763 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15765 MachineBasicBlock *MBB) const {
15766 // Emit code to save XMM registers to the stack. The ABI says that the
15767 // number of registers to save is given in %al, so it's theoretically
15768 // possible to do an indirect jump trick to avoid saving all of them,
15769 // however this code takes a simpler approach and just executes all
15770 // of the stores if %al is non-zero. It's less code, and it's probably
15771 // easier on the hardware branch predictor, and stores aren't all that
15772 // expensive anyway.
15774 // Create the new basic blocks. One block contains all the XMM stores,
15775 // and one block is the final destination regardless of whether any
15776 // stores were performed.
15777 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15778 MachineFunction *F = MBB->getParent();
15779 MachineFunction::iterator MBBIter = MBB;
15781 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15782 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15783 F->insert(MBBIter, XMMSaveMBB);
15784 F->insert(MBBIter, EndMBB);
15786 // Transfer the remainder of MBB and its successor edges to EndMBB.
15787 EndMBB->splice(EndMBB->begin(), MBB,
15788 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15789 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15791 // The original block will now fall through to the XMM save block.
15792 MBB->addSuccessor(XMMSaveMBB);
15793 // The XMMSaveMBB will fall through to the end block.
15794 XMMSaveMBB->addSuccessor(EndMBB);
15796 // Now add the instructions.
15797 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15798 DebugLoc DL = MI->getDebugLoc();
15800 unsigned CountReg = MI->getOperand(0).getReg();
15801 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15802 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15804 if (!Subtarget->isTargetWin64()) {
15805 // If %al is 0, branch around the XMM save block.
15806 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15807 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15808 MBB->addSuccessor(EndMBB);
15811 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15812 // that was just emitted, but clearly shouldn't be "saved".
15813 assert((MI->getNumOperands() <= 3 ||
15814 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15815 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15816 && "Expected last argument to be EFLAGS");
15817 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15818 // In the XMM save block, save all the XMM argument registers.
15819 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15820 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15821 MachineMemOperand *MMO =
15822 F->getMachineMemOperand(
15823 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15824 MachineMemOperand::MOStore,
15825 /*Size=*/16, /*Align=*/16);
15826 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15827 .addFrameIndex(RegSaveFrameIndex)
15828 .addImm(/*Scale=*/1)
15829 .addReg(/*IndexReg=*/0)
15830 .addImm(/*Disp=*/Offset)
15831 .addReg(/*Segment=*/0)
15832 .addReg(MI->getOperand(i).getReg())
15833 .addMemOperand(MMO);
15836 MI->eraseFromParent(); // The pseudo instruction is gone now.
15841 // The EFLAGS operand of SelectItr might be missing a kill marker
15842 // because there were multiple uses of EFLAGS, and ISel didn't know
15843 // which to mark. Figure out whether SelectItr should have had a
15844 // kill marker, and set it if it should. Returns the correct kill
15846 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15847 MachineBasicBlock* BB,
15848 const TargetRegisterInfo* TRI) {
15849 // Scan forward through BB for a use/def of EFLAGS.
15850 MachineBasicBlock::iterator miI(std::next(SelectItr));
15851 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15852 const MachineInstr& mi = *miI;
15853 if (mi.readsRegister(X86::EFLAGS))
15855 if (mi.definesRegister(X86::EFLAGS))
15856 break; // Should have kill-flag - update below.
15859 // If we hit the end of the block, check whether EFLAGS is live into a
15861 if (miI == BB->end()) {
15862 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15863 sEnd = BB->succ_end();
15864 sItr != sEnd; ++sItr) {
15865 MachineBasicBlock* succ = *sItr;
15866 if (succ->isLiveIn(X86::EFLAGS))
15871 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15872 // out. SelectMI should have a kill flag on EFLAGS.
15873 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15877 MachineBasicBlock *
15878 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15879 MachineBasicBlock *BB) const {
15880 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15881 DebugLoc DL = MI->getDebugLoc();
15883 // To "insert" a SELECT_CC instruction, we actually have to insert the
15884 // diamond control-flow pattern. The incoming instruction knows the
15885 // destination vreg to set, the condition code register to branch on, the
15886 // true/false values to select between, and a branch opcode to use.
15887 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15888 MachineFunction::iterator It = BB;
15894 // cmpTY ccX, r1, r2
15896 // fallthrough --> copy0MBB
15897 MachineBasicBlock *thisMBB = BB;
15898 MachineFunction *F = BB->getParent();
15899 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15900 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15901 F->insert(It, copy0MBB);
15902 F->insert(It, sinkMBB);
15904 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15905 // live into the sink and copy blocks.
15906 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15907 if (!MI->killsRegister(X86::EFLAGS) &&
15908 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15909 copy0MBB->addLiveIn(X86::EFLAGS);
15910 sinkMBB->addLiveIn(X86::EFLAGS);
15913 // Transfer the remainder of BB and its successor edges to sinkMBB.
15914 sinkMBB->splice(sinkMBB->begin(), BB,
15915 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15916 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15918 // Add the true and fallthrough blocks as its successors.
15919 BB->addSuccessor(copy0MBB);
15920 BB->addSuccessor(sinkMBB);
15922 // Create the conditional branch instruction.
15924 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15925 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15928 // %FalseValue = ...
15929 // # fallthrough to sinkMBB
15930 copy0MBB->addSuccessor(sinkMBB);
15933 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15935 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15936 TII->get(X86::PHI), MI->getOperand(0).getReg())
15937 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15938 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15940 MI->eraseFromParent(); // The pseudo instruction is gone now.
15944 MachineBasicBlock *
15945 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15946 bool Is64Bit) const {
15947 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15948 DebugLoc DL = MI->getDebugLoc();
15949 MachineFunction *MF = BB->getParent();
15950 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15952 assert(MF->shouldSplitStack());
15954 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15955 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15958 // ... [Till the alloca]
15959 // If stacklet is not large enough, jump to mallocMBB
15962 // Allocate by subtracting from RSP
15963 // Jump to continueMBB
15966 // Allocate by call to runtime
15970 // [rest of original BB]
15973 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15974 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15975 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15977 MachineRegisterInfo &MRI = MF->getRegInfo();
15978 const TargetRegisterClass *AddrRegClass =
15979 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15981 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15982 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15983 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15984 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15985 sizeVReg = MI->getOperand(1).getReg(),
15986 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15988 MachineFunction::iterator MBBIter = BB;
15991 MF->insert(MBBIter, bumpMBB);
15992 MF->insert(MBBIter, mallocMBB);
15993 MF->insert(MBBIter, continueMBB);
15995 continueMBB->splice(continueMBB->begin(), BB,
15996 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15997 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15999 // Add code to the main basic block to check if the stack limit has been hit,
16000 // and if so, jump to mallocMBB otherwise to bumpMBB.
16001 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16002 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16003 .addReg(tmpSPVReg).addReg(sizeVReg);
16004 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16005 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16006 .addReg(SPLimitVReg);
16007 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16009 // bumpMBB simply decreases the stack pointer, since we know the current
16010 // stacklet has enough space.
16011 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16012 .addReg(SPLimitVReg);
16013 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16014 .addReg(SPLimitVReg);
16015 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16017 // Calls into a routine in libgcc to allocate more space from the heap.
16018 const uint32_t *RegMask =
16019 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16021 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16023 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16024 .addExternalSymbol("__morestack_allocate_stack_space")
16025 .addRegMask(RegMask)
16026 .addReg(X86::RDI, RegState::Implicit)
16027 .addReg(X86::RAX, RegState::ImplicitDefine);
16029 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16031 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16032 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16033 .addExternalSymbol("__morestack_allocate_stack_space")
16034 .addRegMask(RegMask)
16035 .addReg(X86::EAX, RegState::ImplicitDefine);
16039 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16042 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16043 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16044 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16046 // Set up the CFG correctly.
16047 BB->addSuccessor(bumpMBB);
16048 BB->addSuccessor(mallocMBB);
16049 mallocMBB->addSuccessor(continueMBB);
16050 bumpMBB->addSuccessor(continueMBB);
16052 // Take care of the PHI nodes.
16053 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16054 MI->getOperand(0).getReg())
16055 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16056 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16058 // Delete the original pseudo instruction.
16059 MI->eraseFromParent();
16062 return continueMBB;
16065 MachineBasicBlock *
16066 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16067 MachineBasicBlock *BB) const {
16068 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16069 DebugLoc DL = MI->getDebugLoc();
16071 assert(!Subtarget->isTargetMacho());
16073 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16074 // non-trivial part is impdef of ESP.
16076 if (Subtarget->isTargetWin64()) {
16077 if (Subtarget->isTargetCygMing()) {
16078 // ___chkstk(Mingw64):
16079 // Clobbers R10, R11, RAX and EFLAGS.
16081 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16082 .addExternalSymbol("___chkstk")
16083 .addReg(X86::RAX, RegState::Implicit)
16084 .addReg(X86::RSP, RegState::Implicit)
16085 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16086 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16087 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16089 // __chkstk(MSVCRT): does not update stack pointer.
16090 // Clobbers R10, R11 and EFLAGS.
16091 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16092 .addExternalSymbol("__chkstk")
16093 .addReg(X86::RAX, RegState::Implicit)
16094 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16095 // RAX has the offset to be subtracted from RSP.
16096 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16101 const char *StackProbeSymbol =
16102 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16104 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16105 .addExternalSymbol(StackProbeSymbol)
16106 .addReg(X86::EAX, RegState::Implicit)
16107 .addReg(X86::ESP, RegState::Implicit)
16108 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16109 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16110 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16113 MI->eraseFromParent(); // The pseudo instruction is gone now.
16117 MachineBasicBlock *
16118 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16119 MachineBasicBlock *BB) const {
16120 // This is pretty easy. We're taking the value that we received from
16121 // our load from the relocation, sticking it in either RDI (x86-64)
16122 // or EAX and doing an indirect call. The return value will then
16123 // be in the normal return register.
16124 const X86InstrInfo *TII
16125 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16126 DebugLoc DL = MI->getDebugLoc();
16127 MachineFunction *F = BB->getParent();
16129 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16130 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16132 // Get a register mask for the lowered call.
16133 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16134 // proper register mask.
16135 const uint32_t *RegMask =
16136 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16137 if (Subtarget->is64Bit()) {
16138 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16139 TII->get(X86::MOV64rm), X86::RDI)
16141 .addImm(0).addReg(0)
16142 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16143 MI->getOperand(3).getTargetFlags())
16145 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16146 addDirectMem(MIB, X86::RDI);
16147 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16148 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16149 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16150 TII->get(X86::MOV32rm), X86::EAX)
16152 .addImm(0).addReg(0)
16153 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16154 MI->getOperand(3).getTargetFlags())
16156 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16157 addDirectMem(MIB, X86::EAX);
16158 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16160 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16161 TII->get(X86::MOV32rm), X86::EAX)
16162 .addReg(TII->getGlobalBaseReg(F))
16163 .addImm(0).addReg(0)
16164 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16165 MI->getOperand(3).getTargetFlags())
16167 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16168 addDirectMem(MIB, X86::EAX);
16169 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16172 MI->eraseFromParent(); // The pseudo instruction is gone now.
16176 MachineBasicBlock *
16177 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16178 MachineBasicBlock *MBB) const {
16179 DebugLoc DL = MI->getDebugLoc();
16180 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16182 MachineFunction *MF = MBB->getParent();
16183 MachineRegisterInfo &MRI = MF->getRegInfo();
16185 const BasicBlock *BB = MBB->getBasicBlock();
16186 MachineFunction::iterator I = MBB;
16189 // Memory Reference
16190 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16191 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16194 unsigned MemOpndSlot = 0;
16196 unsigned CurOp = 0;
16198 DstReg = MI->getOperand(CurOp++).getReg();
16199 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16200 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16201 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16202 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16204 MemOpndSlot = CurOp;
16206 MVT PVT = getPointerTy();
16207 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16208 "Invalid Pointer Size!");
16210 // For v = setjmp(buf), we generate
16213 // buf[LabelOffset] = restoreMBB
16214 // SjLjSetup restoreMBB
16220 // v = phi(main, restore)
16225 MachineBasicBlock *thisMBB = MBB;
16226 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16227 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16228 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16229 MF->insert(I, mainMBB);
16230 MF->insert(I, sinkMBB);
16231 MF->push_back(restoreMBB);
16233 MachineInstrBuilder MIB;
16235 // Transfer the remainder of BB and its successor edges to sinkMBB.
16236 sinkMBB->splice(sinkMBB->begin(), MBB,
16237 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16238 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16241 unsigned PtrStoreOpc = 0;
16242 unsigned LabelReg = 0;
16243 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16244 Reloc::Model RM = getTargetMachine().getRelocationModel();
16245 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16246 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16248 // Prepare IP either in reg or imm.
16249 if (!UseImmLabel) {
16250 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16251 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16252 LabelReg = MRI.createVirtualRegister(PtrRC);
16253 if (Subtarget->is64Bit()) {
16254 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16258 .addMBB(restoreMBB)
16261 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16262 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16263 .addReg(XII->getGlobalBaseReg(MF))
16266 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16270 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16272 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16273 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16274 if (i == X86::AddrDisp)
16275 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16277 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16280 MIB.addReg(LabelReg);
16282 MIB.addMBB(restoreMBB);
16283 MIB.setMemRefs(MMOBegin, MMOEnd);
16285 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16286 .addMBB(restoreMBB);
16288 const X86RegisterInfo *RegInfo =
16289 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16290 MIB.addRegMask(RegInfo->getNoPreservedMask());
16291 thisMBB->addSuccessor(mainMBB);
16292 thisMBB->addSuccessor(restoreMBB);
16296 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16297 mainMBB->addSuccessor(sinkMBB);
16300 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16301 TII->get(X86::PHI), DstReg)
16302 .addReg(mainDstReg).addMBB(mainMBB)
16303 .addReg(restoreDstReg).addMBB(restoreMBB);
16306 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16307 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16308 restoreMBB->addSuccessor(sinkMBB);
16310 MI->eraseFromParent();
16314 MachineBasicBlock *
16315 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16316 MachineBasicBlock *MBB) const {
16317 DebugLoc DL = MI->getDebugLoc();
16318 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16320 MachineFunction *MF = MBB->getParent();
16321 MachineRegisterInfo &MRI = MF->getRegInfo();
16323 // Memory Reference
16324 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16325 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16327 MVT PVT = getPointerTy();
16328 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16329 "Invalid Pointer Size!");
16331 const TargetRegisterClass *RC =
16332 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16333 unsigned Tmp = MRI.createVirtualRegister(RC);
16334 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16335 const X86RegisterInfo *RegInfo =
16336 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16337 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16338 unsigned SP = RegInfo->getStackRegister();
16340 MachineInstrBuilder MIB;
16342 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16343 const int64_t SPOffset = 2 * PVT.getStoreSize();
16345 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16346 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16349 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16350 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16351 MIB.addOperand(MI->getOperand(i));
16352 MIB.setMemRefs(MMOBegin, MMOEnd);
16354 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16355 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16356 if (i == X86::AddrDisp)
16357 MIB.addDisp(MI->getOperand(i), LabelOffset);
16359 MIB.addOperand(MI->getOperand(i));
16361 MIB.setMemRefs(MMOBegin, MMOEnd);
16363 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16364 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16365 if (i == X86::AddrDisp)
16366 MIB.addDisp(MI->getOperand(i), SPOffset);
16368 MIB.addOperand(MI->getOperand(i));
16370 MIB.setMemRefs(MMOBegin, MMOEnd);
16372 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16374 MI->eraseFromParent();
16378 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16379 // accumulator loops. Writing back to the accumulator allows the coalescer
16380 // to remove extra copies in the loop.
16381 MachineBasicBlock *
16382 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16383 MachineBasicBlock *MBB) const {
16384 MachineOperand &AddendOp = MI->getOperand(3);
16386 // Bail out early if the addend isn't a register - we can't switch these.
16387 if (!AddendOp.isReg())
16390 MachineFunction &MF = *MBB->getParent();
16391 MachineRegisterInfo &MRI = MF.getRegInfo();
16393 // Check whether the addend is defined by a PHI:
16394 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16395 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16396 if (!AddendDef.isPHI())
16399 // Look for the following pattern:
16401 // %addend = phi [%entry, 0], [%loop, %result]
16403 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16407 // %addend = phi [%entry, 0], [%loop, %result]
16409 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16411 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16412 assert(AddendDef.getOperand(i).isReg());
16413 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16414 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16415 if (&PHISrcInst == MI) {
16416 // Found a matching instruction.
16417 unsigned NewFMAOpc = 0;
16418 switch (MI->getOpcode()) {
16419 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16420 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16421 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16422 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16423 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16424 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16425 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16426 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16427 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16428 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16429 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16430 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16431 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16432 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16433 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16434 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16435 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16436 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16437 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16438 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16439 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16440 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16441 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16442 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16443 default: llvm_unreachable("Unrecognized FMA variant.");
16446 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16447 MachineInstrBuilder MIB =
16448 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16449 .addOperand(MI->getOperand(0))
16450 .addOperand(MI->getOperand(3))
16451 .addOperand(MI->getOperand(2))
16452 .addOperand(MI->getOperand(1));
16453 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16454 MI->eraseFromParent();
16461 MachineBasicBlock *
16462 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16463 MachineBasicBlock *BB) const {
16464 switch (MI->getOpcode()) {
16465 default: llvm_unreachable("Unexpected instr type to insert");
16466 case X86::TAILJMPd64:
16467 case X86::TAILJMPr64:
16468 case X86::TAILJMPm64:
16469 llvm_unreachable("TAILJMP64 would not be touched here.");
16470 case X86::TCRETURNdi64:
16471 case X86::TCRETURNri64:
16472 case X86::TCRETURNmi64:
16474 case X86::WIN_ALLOCA:
16475 return EmitLoweredWinAlloca(MI, BB);
16476 case X86::SEG_ALLOCA_32:
16477 return EmitLoweredSegAlloca(MI, BB, false);
16478 case X86::SEG_ALLOCA_64:
16479 return EmitLoweredSegAlloca(MI, BB, true);
16480 case X86::TLSCall_32:
16481 case X86::TLSCall_64:
16482 return EmitLoweredTLSCall(MI, BB);
16483 case X86::CMOV_GR8:
16484 case X86::CMOV_FR32:
16485 case X86::CMOV_FR64:
16486 case X86::CMOV_V4F32:
16487 case X86::CMOV_V2F64:
16488 case X86::CMOV_V2I64:
16489 case X86::CMOV_V8F32:
16490 case X86::CMOV_V4F64:
16491 case X86::CMOV_V4I64:
16492 case X86::CMOV_V16F32:
16493 case X86::CMOV_V8F64:
16494 case X86::CMOV_V8I64:
16495 case X86::CMOV_GR16:
16496 case X86::CMOV_GR32:
16497 case X86::CMOV_RFP32:
16498 case X86::CMOV_RFP64:
16499 case X86::CMOV_RFP80:
16500 return EmitLoweredSelect(MI, BB);
16502 case X86::FP32_TO_INT16_IN_MEM:
16503 case X86::FP32_TO_INT32_IN_MEM:
16504 case X86::FP32_TO_INT64_IN_MEM:
16505 case X86::FP64_TO_INT16_IN_MEM:
16506 case X86::FP64_TO_INT32_IN_MEM:
16507 case X86::FP64_TO_INT64_IN_MEM:
16508 case X86::FP80_TO_INT16_IN_MEM:
16509 case X86::FP80_TO_INT32_IN_MEM:
16510 case X86::FP80_TO_INT64_IN_MEM: {
16511 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16512 DebugLoc DL = MI->getDebugLoc();
16514 // Change the floating point control register to use "round towards zero"
16515 // mode when truncating to an integer value.
16516 MachineFunction *F = BB->getParent();
16517 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16518 addFrameReference(BuildMI(*BB, MI, DL,
16519 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16521 // Load the old value of the high byte of the control word...
16523 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16524 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16527 // Set the high part to be round to zero...
16528 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16531 // Reload the modified control word now...
16532 addFrameReference(BuildMI(*BB, MI, DL,
16533 TII->get(X86::FLDCW16m)), CWFrameIdx);
16535 // Restore the memory image of control word to original value
16536 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16539 // Get the X86 opcode to use.
16541 switch (MI->getOpcode()) {
16542 default: llvm_unreachable("illegal opcode!");
16543 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16544 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16545 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16546 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16547 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16548 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16549 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16550 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16551 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16555 MachineOperand &Op = MI->getOperand(0);
16557 AM.BaseType = X86AddressMode::RegBase;
16558 AM.Base.Reg = Op.getReg();
16560 AM.BaseType = X86AddressMode::FrameIndexBase;
16561 AM.Base.FrameIndex = Op.getIndex();
16563 Op = MI->getOperand(1);
16565 AM.Scale = Op.getImm();
16566 Op = MI->getOperand(2);
16568 AM.IndexReg = Op.getImm();
16569 Op = MI->getOperand(3);
16570 if (Op.isGlobal()) {
16571 AM.GV = Op.getGlobal();
16573 AM.Disp = Op.getImm();
16575 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16576 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16578 // Reload the original control word now.
16579 addFrameReference(BuildMI(*BB, MI, DL,
16580 TII->get(X86::FLDCW16m)), CWFrameIdx);
16582 MI->eraseFromParent(); // The pseudo instruction is gone now.
16585 // String/text processing lowering.
16586 case X86::PCMPISTRM128REG:
16587 case X86::VPCMPISTRM128REG:
16588 case X86::PCMPISTRM128MEM:
16589 case X86::VPCMPISTRM128MEM:
16590 case X86::PCMPESTRM128REG:
16591 case X86::VPCMPESTRM128REG:
16592 case X86::PCMPESTRM128MEM:
16593 case X86::VPCMPESTRM128MEM:
16594 assert(Subtarget->hasSSE42() &&
16595 "Target must have SSE4.2 or AVX features enabled");
16596 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16598 // String/text processing lowering.
16599 case X86::PCMPISTRIREG:
16600 case X86::VPCMPISTRIREG:
16601 case X86::PCMPISTRIMEM:
16602 case X86::VPCMPISTRIMEM:
16603 case X86::PCMPESTRIREG:
16604 case X86::VPCMPESTRIREG:
16605 case X86::PCMPESTRIMEM:
16606 case X86::VPCMPESTRIMEM:
16607 assert(Subtarget->hasSSE42() &&
16608 "Target must have SSE4.2 or AVX features enabled");
16609 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16611 // Thread synchronization.
16613 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16617 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16619 // Atomic Lowering.
16620 case X86::ATOMAND8:
16621 case X86::ATOMAND16:
16622 case X86::ATOMAND32:
16623 case X86::ATOMAND64:
16626 case X86::ATOMOR16:
16627 case X86::ATOMOR32:
16628 case X86::ATOMOR64:
16630 case X86::ATOMXOR16:
16631 case X86::ATOMXOR8:
16632 case X86::ATOMXOR32:
16633 case X86::ATOMXOR64:
16635 case X86::ATOMNAND8:
16636 case X86::ATOMNAND16:
16637 case X86::ATOMNAND32:
16638 case X86::ATOMNAND64:
16640 case X86::ATOMMAX8:
16641 case X86::ATOMMAX16:
16642 case X86::ATOMMAX32:
16643 case X86::ATOMMAX64:
16645 case X86::ATOMMIN8:
16646 case X86::ATOMMIN16:
16647 case X86::ATOMMIN32:
16648 case X86::ATOMMIN64:
16650 case X86::ATOMUMAX8:
16651 case X86::ATOMUMAX16:
16652 case X86::ATOMUMAX32:
16653 case X86::ATOMUMAX64:
16655 case X86::ATOMUMIN8:
16656 case X86::ATOMUMIN16:
16657 case X86::ATOMUMIN32:
16658 case X86::ATOMUMIN64:
16659 return EmitAtomicLoadArith(MI, BB);
16661 // This group does 64-bit operations on a 32-bit host.
16662 case X86::ATOMAND6432:
16663 case X86::ATOMOR6432:
16664 case X86::ATOMXOR6432:
16665 case X86::ATOMNAND6432:
16666 case X86::ATOMADD6432:
16667 case X86::ATOMSUB6432:
16668 case X86::ATOMMAX6432:
16669 case X86::ATOMMIN6432:
16670 case X86::ATOMUMAX6432:
16671 case X86::ATOMUMIN6432:
16672 case X86::ATOMSWAP6432:
16673 return EmitAtomicLoadArith6432(MI, BB);
16675 case X86::VASTART_SAVE_XMM_REGS:
16676 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16678 case X86::VAARG_64:
16679 return EmitVAARG64WithCustomInserter(MI, BB);
16681 case X86::EH_SjLj_SetJmp32:
16682 case X86::EH_SjLj_SetJmp64:
16683 return emitEHSjLjSetJmp(MI, BB);
16685 case X86::EH_SjLj_LongJmp32:
16686 case X86::EH_SjLj_LongJmp64:
16687 return emitEHSjLjLongJmp(MI, BB);
16689 case TargetOpcode::STACKMAP:
16690 case TargetOpcode::PATCHPOINT:
16691 return emitPatchPoint(MI, BB);
16693 case X86::VFMADDPDr213r:
16694 case X86::VFMADDPSr213r:
16695 case X86::VFMADDSDr213r:
16696 case X86::VFMADDSSr213r:
16697 case X86::VFMSUBPDr213r:
16698 case X86::VFMSUBPSr213r:
16699 case X86::VFMSUBSDr213r:
16700 case X86::VFMSUBSSr213r:
16701 case X86::VFNMADDPDr213r:
16702 case X86::VFNMADDPSr213r:
16703 case X86::VFNMADDSDr213r:
16704 case X86::VFNMADDSSr213r:
16705 case X86::VFNMSUBPDr213r:
16706 case X86::VFNMSUBPSr213r:
16707 case X86::VFNMSUBSDr213r:
16708 case X86::VFNMSUBSSr213r:
16709 case X86::VFMADDPDr213rY:
16710 case X86::VFMADDPSr213rY:
16711 case X86::VFMSUBPDr213rY:
16712 case X86::VFMSUBPSr213rY:
16713 case X86::VFNMADDPDr213rY:
16714 case X86::VFNMADDPSr213rY:
16715 case X86::VFNMSUBPDr213rY:
16716 case X86::VFNMSUBPSr213rY:
16717 return emitFMA3Instr(MI, BB);
16721 //===----------------------------------------------------------------------===//
16722 // X86 Optimization Hooks
16723 //===----------------------------------------------------------------------===//
16725 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16728 const SelectionDAG &DAG,
16729 unsigned Depth) const {
16730 unsigned BitWidth = KnownZero.getBitWidth();
16731 unsigned Opc = Op.getOpcode();
16732 assert((Opc >= ISD::BUILTIN_OP_END ||
16733 Opc == ISD::INTRINSIC_WO_CHAIN ||
16734 Opc == ISD::INTRINSIC_W_CHAIN ||
16735 Opc == ISD::INTRINSIC_VOID) &&
16736 "Should use MaskedValueIsZero if you don't know whether Op"
16737 " is a target node!");
16739 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16753 // These nodes' second result is a boolean.
16754 if (Op.getResNo() == 0)
16757 case X86ISD::SETCC:
16758 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16760 case ISD::INTRINSIC_WO_CHAIN: {
16761 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16762 unsigned NumLoBits = 0;
16765 case Intrinsic::x86_sse_movmsk_ps:
16766 case Intrinsic::x86_avx_movmsk_ps_256:
16767 case Intrinsic::x86_sse2_movmsk_pd:
16768 case Intrinsic::x86_avx_movmsk_pd_256:
16769 case Intrinsic::x86_mmx_pmovmskb:
16770 case Intrinsic::x86_sse2_pmovmskb_128:
16771 case Intrinsic::x86_avx2_pmovmskb: {
16772 // High bits of movmskp{s|d}, pmovmskb are known zero.
16774 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16775 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16776 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16777 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16778 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16779 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16780 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16781 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16783 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16792 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16794 const SelectionDAG &,
16795 unsigned Depth) const {
16796 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16797 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16798 return Op.getValueType().getScalarType().getSizeInBits();
16804 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16805 /// node is a GlobalAddress + offset.
16806 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16807 const GlobalValue* &GA,
16808 int64_t &Offset) const {
16809 if (N->getOpcode() == X86ISD::Wrapper) {
16810 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16811 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16812 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16816 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16819 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16820 /// same as extracting the high 128-bit part of 256-bit vector and then
16821 /// inserting the result into the low part of a new 256-bit vector
16822 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16823 EVT VT = SVOp->getValueType(0);
16824 unsigned NumElems = VT.getVectorNumElements();
16826 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16827 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16828 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16829 SVOp->getMaskElt(j) >= 0)
16835 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16836 /// same as extracting the low 128-bit part of 256-bit vector and then
16837 /// inserting the result into the high part of a new 256-bit vector
16838 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16839 EVT VT = SVOp->getValueType(0);
16840 unsigned NumElems = VT.getVectorNumElements();
16842 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16843 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16844 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16845 SVOp->getMaskElt(j) >= 0)
16851 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16852 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16853 TargetLowering::DAGCombinerInfo &DCI,
16854 const X86Subtarget* Subtarget) {
16856 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16857 SDValue V1 = SVOp->getOperand(0);
16858 SDValue V2 = SVOp->getOperand(1);
16859 EVT VT = SVOp->getValueType(0);
16860 unsigned NumElems = VT.getVectorNumElements();
16862 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16863 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16867 // V UNDEF BUILD_VECTOR UNDEF
16869 // CONCAT_VECTOR CONCAT_VECTOR
16872 // RESULT: V + zero extended
16874 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16875 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16876 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16879 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16882 // To match the shuffle mask, the first half of the mask should
16883 // be exactly the first vector, and all the rest a splat with the
16884 // first element of the second one.
16885 for (unsigned i = 0; i != NumElems/2; ++i)
16886 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16887 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16890 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16891 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16892 if (Ld->hasNUsesOfValue(1, 0)) {
16893 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16894 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16896 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16897 array_lengthof(Ops),
16899 Ld->getPointerInfo(),
16900 Ld->getAlignment(),
16901 false/*isVolatile*/, true/*ReadMem*/,
16902 false/*WriteMem*/);
16904 // Make sure the newly-created LOAD is in the same position as Ld in
16905 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16906 // and update uses of Ld's output chain to use the TokenFactor.
16907 if (Ld->hasAnyUseOfValue(1)) {
16908 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16909 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16910 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16911 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16912 SDValue(ResNode.getNode(), 1));
16915 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16919 // Emit a zeroed vector and insert the desired subvector on its
16921 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16922 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16923 return DCI.CombineTo(N, InsV);
16926 //===--------------------------------------------------------------------===//
16927 // Combine some shuffles into subvector extracts and inserts:
16930 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16931 if (isShuffleHigh128VectorInsertLow(SVOp)) {
16932 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16933 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16934 return DCI.CombineTo(N, InsV);
16937 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16938 if (isShuffleLow128VectorInsertHigh(SVOp)) {
16939 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16940 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16941 return DCI.CombineTo(N, InsV);
16947 /// PerformShuffleCombine - Performs several different shuffle combines.
16948 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16949 TargetLowering::DAGCombinerInfo &DCI,
16950 const X86Subtarget *Subtarget) {
16952 EVT VT = N->getValueType(0);
16954 // Don't create instructions with illegal types after legalize types has run.
16955 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16956 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16959 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16960 if (Subtarget->hasFp256() && VT.is256BitVector() &&
16961 N->getOpcode() == ISD::VECTOR_SHUFFLE)
16962 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16964 // Only handle 128 wide vector from here on.
16965 if (!VT.is128BitVector())
16968 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16969 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16970 // consecutive, non-overlapping, and in the right order.
16971 SmallVector<SDValue, 16> Elts;
16972 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16973 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16975 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16978 /// PerformTruncateCombine - Converts truncate operation to
16979 /// a sequence of vector shuffle operations.
16980 /// It is possible when we truncate 256-bit vector to 128-bit vector
16981 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16982 TargetLowering::DAGCombinerInfo &DCI,
16983 const X86Subtarget *Subtarget) {
16987 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16988 /// specific shuffle of a load can be folded into a single element load.
16989 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16990 /// shuffles have been customed lowered so we need to handle those here.
16991 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16992 TargetLowering::DAGCombinerInfo &DCI) {
16993 if (DCI.isBeforeLegalizeOps())
16996 SDValue InVec = N->getOperand(0);
16997 SDValue EltNo = N->getOperand(1);
16999 if (!isa<ConstantSDNode>(EltNo))
17002 EVT VT = InVec.getValueType();
17004 bool HasShuffleIntoBitcast = false;
17005 if (InVec.getOpcode() == ISD::BITCAST) {
17006 // Don't duplicate a load with other uses.
17007 if (!InVec.hasOneUse())
17009 EVT BCVT = InVec.getOperand(0).getValueType();
17010 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17012 InVec = InVec.getOperand(0);
17013 HasShuffleIntoBitcast = true;
17016 if (!isTargetShuffle(InVec.getOpcode()))
17019 // Don't duplicate a load with other uses.
17020 if (!InVec.hasOneUse())
17023 SmallVector<int, 16> ShuffleMask;
17025 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17029 // Select the input vector, guarding against out of range extract vector.
17030 unsigned NumElems = VT.getVectorNumElements();
17031 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17032 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17033 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17034 : InVec.getOperand(1);
17036 // If inputs to shuffle are the same for both ops, then allow 2 uses
17037 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17039 if (LdNode.getOpcode() == ISD::BITCAST) {
17040 // Don't duplicate a load with other uses.
17041 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17044 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17045 LdNode = LdNode.getOperand(0);
17048 if (!ISD::isNormalLoad(LdNode.getNode()))
17051 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17053 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17056 if (HasShuffleIntoBitcast) {
17057 // If there's a bitcast before the shuffle, check if the load type and
17058 // alignment is valid.
17059 unsigned Align = LN0->getAlignment();
17060 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17061 unsigned NewAlign = TLI.getDataLayout()->
17062 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17064 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17068 // All checks match so transform back to vector_shuffle so that DAG combiner
17069 // can finish the job
17072 // Create shuffle node taking into account the case that its a unary shuffle
17073 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17074 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17075 InVec.getOperand(0), Shuffle,
17077 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17078 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17082 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17083 /// generation and convert it from being a bunch of shuffles and extracts
17084 /// to a simple store and scalar loads to extract the elements.
17085 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17086 TargetLowering::DAGCombinerInfo &DCI) {
17087 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17088 if (NewOp.getNode())
17091 SDValue InputVector = N->getOperand(0);
17093 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17094 // from mmx to v2i32 has a single usage.
17095 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17096 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17097 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17098 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17099 N->getValueType(0),
17100 InputVector.getNode()->getOperand(0));
17102 // Only operate on vectors of 4 elements, where the alternative shuffling
17103 // gets to be more expensive.
17104 if (InputVector.getValueType() != MVT::v4i32)
17107 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17108 // single use which is a sign-extend or zero-extend, and all elements are
17110 SmallVector<SDNode *, 4> Uses;
17111 unsigned ExtractedElements = 0;
17112 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17113 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17114 if (UI.getUse().getResNo() != InputVector.getResNo())
17117 SDNode *Extract = *UI;
17118 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17121 if (Extract->getValueType(0) != MVT::i32)
17123 if (!Extract->hasOneUse())
17125 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17126 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17128 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17131 // Record which element was extracted.
17132 ExtractedElements |=
17133 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17135 Uses.push_back(Extract);
17138 // If not all the elements were used, this may not be worthwhile.
17139 if (ExtractedElements != 15)
17142 // Ok, we've now decided to do the transformation.
17143 SDLoc dl(InputVector);
17145 // Store the value to a temporary stack slot.
17146 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17147 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17148 MachinePointerInfo(), false, false, 0);
17150 // Replace each use (extract) with a load of the appropriate element.
17151 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17152 UE = Uses.end(); UI != UE; ++UI) {
17153 SDNode *Extract = *UI;
17155 // cOMpute the element's address.
17156 SDValue Idx = Extract->getOperand(1);
17158 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17159 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17160 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17161 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17163 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17164 StackPtr, OffsetVal);
17166 // Load the scalar.
17167 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17168 ScalarAddr, MachinePointerInfo(),
17169 false, false, false, 0);
17171 // Replace the exact with the load.
17172 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17175 // The replacement was made in place; don't return anything.
17179 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17180 static std::pair<unsigned, bool>
17181 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17182 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17183 if (!VT.isVector())
17184 return std::make_pair(0, false);
17186 bool NeedSplit = false;
17187 switch (VT.getSimpleVT().SimpleTy) {
17188 default: return std::make_pair(0, false);
17192 if (!Subtarget->hasAVX2())
17194 if (!Subtarget->hasAVX())
17195 return std::make_pair(0, false);
17200 if (!Subtarget->hasSSE2())
17201 return std::make_pair(0, false);
17204 // SSE2 has only a small subset of the operations.
17205 bool hasUnsigned = Subtarget->hasSSE41() ||
17206 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17207 bool hasSigned = Subtarget->hasSSE41() ||
17208 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17210 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17213 // Check for x CC y ? x : y.
17214 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17215 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17220 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17223 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17226 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17229 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17231 // Check for x CC y ? y : x -- a min/max with reversed arms.
17232 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17233 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17238 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17241 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17244 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17247 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17251 return std::make_pair(Opc, NeedSplit);
17254 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17256 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17257 TargetLowering::DAGCombinerInfo &DCI,
17258 const X86Subtarget *Subtarget) {
17260 SDValue Cond = N->getOperand(0);
17261 // Get the LHS/RHS of the select.
17262 SDValue LHS = N->getOperand(1);
17263 SDValue RHS = N->getOperand(2);
17264 EVT VT = LHS.getValueType();
17265 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17267 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17268 // instructions match the semantics of the common C idiom x<y?x:y but not
17269 // x<=y?x:y, because of how they handle negative zero (which can be
17270 // ignored in unsafe-math mode).
17271 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17272 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17273 (Subtarget->hasSSE2() ||
17274 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17275 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17277 unsigned Opcode = 0;
17278 // Check for x CC y ? x : y.
17279 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17280 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17284 // Converting this to a min would handle NaNs incorrectly, and swapping
17285 // the operands would cause it to handle comparisons between positive
17286 // and negative zero incorrectly.
17287 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17288 if (!DAG.getTarget().Options.UnsafeFPMath &&
17289 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17291 std::swap(LHS, RHS);
17293 Opcode = X86ISD::FMIN;
17296 // Converting this to a min would handle comparisons between positive
17297 // and negative zero incorrectly.
17298 if (!DAG.getTarget().Options.UnsafeFPMath &&
17299 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17301 Opcode = X86ISD::FMIN;
17304 // Converting this to a min would handle both negative zeros and NaNs
17305 // incorrectly, but we can swap the operands to fix both.
17306 std::swap(LHS, RHS);
17310 Opcode = X86ISD::FMIN;
17314 // Converting this to a max would handle comparisons between positive
17315 // and negative zero incorrectly.
17316 if (!DAG.getTarget().Options.UnsafeFPMath &&
17317 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17319 Opcode = X86ISD::FMAX;
17322 // Converting this to a max would handle NaNs incorrectly, and swapping
17323 // the operands would cause it to handle comparisons between positive
17324 // and negative zero incorrectly.
17325 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17326 if (!DAG.getTarget().Options.UnsafeFPMath &&
17327 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17329 std::swap(LHS, RHS);
17331 Opcode = X86ISD::FMAX;
17334 // Converting this to a max would handle both negative zeros and NaNs
17335 // incorrectly, but we can swap the operands to fix both.
17336 std::swap(LHS, RHS);
17340 Opcode = X86ISD::FMAX;
17343 // Check for x CC y ? y : x -- a min/max with reversed arms.
17344 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17345 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17349 // Converting this to a min would handle comparisons between positive
17350 // and negative zero incorrectly, and swapping the operands would
17351 // cause it to handle NaNs incorrectly.
17352 if (!DAG.getTarget().Options.UnsafeFPMath &&
17353 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17354 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17356 std::swap(LHS, RHS);
17358 Opcode = X86ISD::FMIN;
17361 // Converting this to a min would handle NaNs incorrectly.
17362 if (!DAG.getTarget().Options.UnsafeFPMath &&
17363 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17365 Opcode = X86ISD::FMIN;
17368 // Converting this to a min would handle both negative zeros and NaNs
17369 // incorrectly, but we can swap the operands to fix both.
17370 std::swap(LHS, RHS);
17374 Opcode = X86ISD::FMIN;
17378 // Converting this to a max would handle NaNs incorrectly.
17379 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17381 Opcode = X86ISD::FMAX;
17384 // Converting this to a max would handle comparisons between positive
17385 // and negative zero incorrectly, and swapping the operands would
17386 // cause it to handle NaNs incorrectly.
17387 if (!DAG.getTarget().Options.UnsafeFPMath &&
17388 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17389 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17391 std::swap(LHS, RHS);
17393 Opcode = X86ISD::FMAX;
17396 // Converting this to a max would handle both negative zeros and NaNs
17397 // incorrectly, but we can swap the operands to fix both.
17398 std::swap(LHS, RHS);
17402 Opcode = X86ISD::FMAX;
17408 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17411 EVT CondVT = Cond.getValueType();
17412 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17413 CondVT.getVectorElementType() == MVT::i1) {
17414 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17415 // lowering on AVX-512. In this case we convert it to
17416 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17417 // The same situation for all 128 and 256-bit vectors of i8 and i16
17418 EVT OpVT = LHS.getValueType();
17419 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17420 (OpVT.getVectorElementType() == MVT::i8 ||
17421 OpVT.getVectorElementType() == MVT::i16)) {
17422 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17423 DCI.AddToWorklist(Cond.getNode());
17424 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17427 // If this is a select between two integer constants, try to do some
17429 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17430 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17431 // Don't do this for crazy integer types.
17432 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17433 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17434 // so that TrueC (the true value) is larger than FalseC.
17435 bool NeedsCondInvert = false;
17437 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17438 // Efficiently invertible.
17439 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17440 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17441 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17442 NeedsCondInvert = true;
17443 std::swap(TrueC, FalseC);
17446 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17447 if (FalseC->getAPIntValue() == 0 &&
17448 TrueC->getAPIntValue().isPowerOf2()) {
17449 if (NeedsCondInvert) // Invert the condition if needed.
17450 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17451 DAG.getConstant(1, Cond.getValueType()));
17453 // Zero extend the condition if needed.
17454 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17456 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17457 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17458 DAG.getConstant(ShAmt, MVT::i8));
17461 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17462 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17463 if (NeedsCondInvert) // Invert the condition if needed.
17464 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17465 DAG.getConstant(1, Cond.getValueType()));
17467 // Zero extend the condition if needed.
17468 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17469 FalseC->getValueType(0), Cond);
17470 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17471 SDValue(FalseC, 0));
17474 // Optimize cases that will turn into an LEA instruction. This requires
17475 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17476 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17477 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17478 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17480 bool isFastMultiplier = false;
17482 switch ((unsigned char)Diff) {
17484 case 1: // result = add base, cond
17485 case 2: // result = lea base( , cond*2)
17486 case 3: // result = lea base(cond, cond*2)
17487 case 4: // result = lea base( , cond*4)
17488 case 5: // result = lea base(cond, cond*4)
17489 case 8: // result = lea base( , cond*8)
17490 case 9: // result = lea base(cond, cond*8)
17491 isFastMultiplier = true;
17496 if (isFastMultiplier) {
17497 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17498 if (NeedsCondInvert) // Invert the condition if needed.
17499 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17500 DAG.getConstant(1, Cond.getValueType()));
17502 // Zero extend the condition if needed.
17503 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17505 // Scale the condition by the difference.
17507 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17508 DAG.getConstant(Diff, Cond.getValueType()));
17510 // Add the base if non-zero.
17511 if (FalseC->getAPIntValue() != 0)
17512 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17513 SDValue(FalseC, 0));
17520 // Canonicalize max and min:
17521 // (x > y) ? x : y -> (x >= y) ? x : y
17522 // (x < y) ? x : y -> (x <= y) ? x : y
17523 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17524 // the need for an extra compare
17525 // against zero. e.g.
17526 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17528 // testl %edi, %edi
17530 // cmovgl %edi, %eax
17534 // cmovsl %eax, %edi
17535 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17536 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17537 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17538 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17543 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17544 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17545 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17546 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17551 // Early exit check
17552 if (!TLI.isTypeLegal(VT))
17555 // Match VSELECTs into subs with unsigned saturation.
17556 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17557 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17558 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17559 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17560 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17562 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17563 // left side invert the predicate to simplify logic below.
17565 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17567 CC = ISD::getSetCCInverse(CC, true);
17568 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17572 if (Other.getNode() && Other->getNumOperands() == 2 &&
17573 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17574 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17575 SDValue CondRHS = Cond->getOperand(1);
17577 // Look for a general sub with unsigned saturation first.
17578 // x >= y ? x-y : 0 --> subus x, y
17579 // x > y ? x-y : 0 --> subus x, y
17580 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17581 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17582 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17584 // If the RHS is a constant we have to reverse the const canonicalization.
17585 // x > C-1 ? x+-C : 0 --> subus x, C
17586 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17587 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17588 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17589 if (CondRHS.getConstantOperandVal(0) == -A-1)
17590 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17591 DAG.getConstant(-A, VT));
17594 // Another special case: If C was a sign bit, the sub has been
17595 // canonicalized into a xor.
17596 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17597 // it's safe to decanonicalize the xor?
17598 // x s< 0 ? x^C : 0 --> subus x, C
17599 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17600 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17601 isSplatVector(OpRHS.getNode())) {
17602 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17604 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17609 // Try to match a min/max vector operation.
17610 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17611 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17612 unsigned Opc = ret.first;
17613 bool NeedSplit = ret.second;
17615 if (Opc && NeedSplit) {
17616 unsigned NumElems = VT.getVectorNumElements();
17617 // Extract the LHS vectors
17618 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17619 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17621 // Extract the RHS vectors
17622 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17623 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17625 // Create min/max for each subvector
17626 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17627 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17629 // Merge the result
17630 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17632 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17635 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17636 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17637 // Check if SETCC has already been promoted
17638 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17639 // Check that condition value type matches vselect operand type
17642 assert(Cond.getValueType().isVector() &&
17643 "vector select expects a vector selector!");
17645 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17646 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17648 if (!TValIsAllOnes && !FValIsAllZeros) {
17649 // Try invert the condition if true value is not all 1s and false value
17651 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17652 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17654 if (TValIsAllZeros || FValIsAllOnes) {
17655 SDValue CC = Cond.getOperand(2);
17656 ISD::CondCode NewCC =
17657 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17658 Cond.getOperand(0).getValueType().isInteger());
17659 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17660 std::swap(LHS, RHS);
17661 TValIsAllOnes = FValIsAllOnes;
17662 FValIsAllZeros = TValIsAllZeros;
17666 if (TValIsAllOnes || FValIsAllZeros) {
17669 if (TValIsAllOnes && FValIsAllZeros)
17671 else if (TValIsAllOnes)
17672 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17673 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17674 else if (FValIsAllZeros)
17675 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17676 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17678 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17682 // Try to fold this VSELECT into a MOVSS/MOVSD
17683 if (N->getOpcode() == ISD::VSELECT &&
17684 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17685 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17686 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17687 bool CanFold = false;
17688 unsigned NumElems = Cond.getNumOperands();
17692 if (isZero(Cond.getOperand(0))) {
17695 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17696 // fold (vselect <0,-1> -> (movsd A, B)
17697 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17698 CanFold = isAllOnes(Cond.getOperand(i));
17699 } else if (isAllOnes(Cond.getOperand(0))) {
17703 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17704 // fold (vselect <-1,0> -> (movsd B, A)
17705 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17706 CanFold = isZero(Cond.getOperand(i));
17710 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17711 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17712 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17715 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17716 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17717 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17718 // (v2i64 (bitcast B)))))
17720 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17721 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17722 // (v2f64 (bitcast B)))))
17724 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17725 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17726 // (v2i64 (bitcast A)))))
17728 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17729 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17730 // (v2f64 (bitcast A)))))
17732 CanFold = (isZero(Cond.getOperand(0)) &&
17733 isZero(Cond.getOperand(1)) &&
17734 isAllOnes(Cond.getOperand(2)) &&
17735 isAllOnes(Cond.getOperand(3)));
17737 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17738 isAllOnes(Cond.getOperand(1)) &&
17739 isZero(Cond.getOperand(2)) &&
17740 isZero(Cond.getOperand(3))) {
17742 std::swap(LHS, RHS);
17746 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17747 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17748 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17749 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17751 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17757 // If we know that this node is legal then we know that it is going to be
17758 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17759 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17760 // to simplify previous instructions.
17761 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17762 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17763 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17765 // Don't optimize vector selects that map to mask-registers.
17769 // Check all uses of that condition operand to check whether it will be
17770 // consumed by non-BLEND instructions, which may depend on all bits are set
17772 for (SDNode::use_iterator I = Cond->use_begin(),
17773 E = Cond->use_end(); I != E; ++I)
17774 if (I->getOpcode() != ISD::VSELECT)
17775 // TODO: Add other opcodes eventually lowered into BLEND.
17778 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17779 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17781 APInt KnownZero, KnownOne;
17782 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17783 DCI.isBeforeLegalizeOps());
17784 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17785 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17786 DCI.CommitTargetLoweringOpt(TLO);
17792 // Check whether a boolean test is testing a boolean value generated by
17793 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17796 // Simplify the following patterns:
17797 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17798 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17799 // to (Op EFLAGS Cond)
17801 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17802 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17803 // to (Op EFLAGS !Cond)
17805 // where Op could be BRCOND or CMOV.
17807 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17808 // Quit if not CMP and SUB with its value result used.
17809 if (Cmp.getOpcode() != X86ISD::CMP &&
17810 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17813 // Quit if not used as a boolean value.
17814 if (CC != X86::COND_E && CC != X86::COND_NE)
17817 // Check CMP operands. One of them should be 0 or 1 and the other should be
17818 // an SetCC or extended from it.
17819 SDValue Op1 = Cmp.getOperand(0);
17820 SDValue Op2 = Cmp.getOperand(1);
17823 const ConstantSDNode* C = 0;
17824 bool needOppositeCond = (CC == X86::COND_E);
17825 bool checkAgainstTrue = false; // Is it a comparison against 1?
17827 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17829 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17831 else // Quit if all operands are not constants.
17834 if (C->getZExtValue() == 1) {
17835 needOppositeCond = !needOppositeCond;
17836 checkAgainstTrue = true;
17837 } else if (C->getZExtValue() != 0)
17838 // Quit if the constant is neither 0 or 1.
17841 bool truncatedToBoolWithAnd = false;
17842 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17843 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17844 SetCC.getOpcode() == ISD::TRUNCATE ||
17845 SetCC.getOpcode() == ISD::AND) {
17846 if (SetCC.getOpcode() == ISD::AND) {
17848 ConstantSDNode *CS;
17849 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17850 CS->getZExtValue() == 1)
17852 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17853 CS->getZExtValue() == 1)
17857 SetCC = SetCC.getOperand(OpIdx);
17858 truncatedToBoolWithAnd = true;
17860 SetCC = SetCC.getOperand(0);
17863 switch (SetCC.getOpcode()) {
17864 case X86ISD::SETCC_CARRY:
17865 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17866 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17867 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17868 // truncated to i1 using 'and'.
17869 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17871 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17872 "Invalid use of SETCC_CARRY!");
17874 case X86ISD::SETCC:
17875 // Set the condition code or opposite one if necessary.
17876 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17877 if (needOppositeCond)
17878 CC = X86::GetOppositeBranchCondition(CC);
17879 return SetCC.getOperand(1);
17880 case X86ISD::CMOV: {
17881 // Check whether false/true value has canonical one, i.e. 0 or 1.
17882 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17883 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17884 // Quit if true value is not a constant.
17887 // Quit if false value is not a constant.
17889 SDValue Op = SetCC.getOperand(0);
17890 // Skip 'zext' or 'trunc' node.
17891 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17892 Op.getOpcode() == ISD::TRUNCATE)
17893 Op = Op.getOperand(0);
17894 // A special case for rdrand/rdseed, where 0 is set if false cond is
17896 if ((Op.getOpcode() != X86ISD::RDRAND &&
17897 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17900 // Quit if false value is not the constant 0 or 1.
17901 bool FValIsFalse = true;
17902 if (FVal && FVal->getZExtValue() != 0) {
17903 if (FVal->getZExtValue() != 1)
17905 // If FVal is 1, opposite cond is needed.
17906 needOppositeCond = !needOppositeCond;
17907 FValIsFalse = false;
17909 // Quit if TVal is not the constant opposite of FVal.
17910 if (FValIsFalse && TVal->getZExtValue() != 1)
17912 if (!FValIsFalse && TVal->getZExtValue() != 0)
17914 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17915 if (needOppositeCond)
17916 CC = X86::GetOppositeBranchCondition(CC);
17917 return SetCC.getOperand(3);
17924 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17925 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17926 TargetLowering::DAGCombinerInfo &DCI,
17927 const X86Subtarget *Subtarget) {
17930 // If the flag operand isn't dead, don't touch this CMOV.
17931 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17934 SDValue FalseOp = N->getOperand(0);
17935 SDValue TrueOp = N->getOperand(1);
17936 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17937 SDValue Cond = N->getOperand(3);
17939 if (CC == X86::COND_E || CC == X86::COND_NE) {
17940 switch (Cond.getOpcode()) {
17944 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17945 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17946 return (CC == X86::COND_E) ? FalseOp : TrueOp;
17952 Flags = checkBoolTestSetCCCombine(Cond, CC);
17953 if (Flags.getNode() &&
17954 // Extra check as FCMOV only supports a subset of X86 cond.
17955 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17956 SDValue Ops[] = { FalseOp, TrueOp,
17957 DAG.getConstant(CC, MVT::i8), Flags };
17958 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17959 Ops, array_lengthof(Ops));
17962 // If this is a select between two integer constants, try to do some
17963 // optimizations. Note that the operands are ordered the opposite of SELECT
17965 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17966 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17967 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17968 // larger than FalseC (the false value).
17969 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17970 CC = X86::GetOppositeBranchCondition(CC);
17971 std::swap(TrueC, FalseC);
17972 std::swap(TrueOp, FalseOp);
17975 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
17976 // This is efficient for any integer data type (including i8/i16) and
17978 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17979 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17980 DAG.getConstant(CC, MVT::i8), Cond);
17982 // Zero extend the condition if needed.
17983 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17985 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17986 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17987 DAG.getConstant(ShAmt, MVT::i8));
17988 if (N->getNumValues() == 2) // Dead flag value?
17989 return DCI.CombineTo(N, Cond, SDValue());
17993 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
17994 // for any integer data type, including i8/i16.
17995 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17996 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17997 DAG.getConstant(CC, MVT::i8), Cond);
17999 // Zero extend the condition if needed.
18000 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18001 FalseC->getValueType(0), Cond);
18002 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18003 SDValue(FalseC, 0));
18005 if (N->getNumValues() == 2) // Dead flag value?
18006 return DCI.CombineTo(N, Cond, SDValue());
18010 // Optimize cases that will turn into an LEA instruction. This requires
18011 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18012 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18013 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18014 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18016 bool isFastMultiplier = false;
18018 switch ((unsigned char)Diff) {
18020 case 1: // result = add base, cond
18021 case 2: // result = lea base( , cond*2)
18022 case 3: // result = lea base(cond, cond*2)
18023 case 4: // result = lea base( , cond*4)
18024 case 5: // result = lea base(cond, cond*4)
18025 case 8: // result = lea base( , cond*8)
18026 case 9: // result = lea base(cond, cond*8)
18027 isFastMultiplier = true;
18032 if (isFastMultiplier) {
18033 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18034 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18035 DAG.getConstant(CC, MVT::i8), Cond);
18036 // Zero extend the condition if needed.
18037 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18039 // Scale the condition by the difference.
18041 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18042 DAG.getConstant(Diff, Cond.getValueType()));
18044 // Add the base if non-zero.
18045 if (FalseC->getAPIntValue() != 0)
18046 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18047 SDValue(FalseC, 0));
18048 if (N->getNumValues() == 2) // Dead flag value?
18049 return DCI.CombineTo(N, Cond, SDValue());
18056 // Handle these cases:
18057 // (select (x != c), e, c) -> select (x != c), e, x),
18058 // (select (x == c), c, e) -> select (x == c), x, e)
18059 // where the c is an integer constant, and the "select" is the combination
18060 // of CMOV and CMP.
18062 // The rationale for this change is that the conditional-move from a constant
18063 // needs two instructions, however, conditional-move from a register needs
18064 // only one instruction.
18066 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18067 // some instruction-combining opportunities. This opt needs to be
18068 // postponed as late as possible.
18070 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18071 // the DCI.xxxx conditions are provided to postpone the optimization as
18072 // late as possible.
18074 ConstantSDNode *CmpAgainst = 0;
18075 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18076 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18077 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18079 if (CC == X86::COND_NE &&
18080 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18081 CC = X86::GetOppositeBranchCondition(CC);
18082 std::swap(TrueOp, FalseOp);
18085 if (CC == X86::COND_E &&
18086 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18087 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18088 DAG.getConstant(CC, MVT::i8), Cond };
18089 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18090 array_lengthof(Ops));
18098 /// PerformMulCombine - Optimize a single multiply with constant into two
18099 /// in order to implement it with two cheaper instructions, e.g.
18100 /// LEA + SHL, LEA + LEA.
18101 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18102 TargetLowering::DAGCombinerInfo &DCI) {
18103 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18106 EVT VT = N->getValueType(0);
18107 if (VT != MVT::i64)
18110 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18113 uint64_t MulAmt = C->getZExtValue();
18114 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18117 uint64_t MulAmt1 = 0;
18118 uint64_t MulAmt2 = 0;
18119 if ((MulAmt % 9) == 0) {
18121 MulAmt2 = MulAmt / 9;
18122 } else if ((MulAmt % 5) == 0) {
18124 MulAmt2 = MulAmt / 5;
18125 } else if ((MulAmt % 3) == 0) {
18127 MulAmt2 = MulAmt / 3;
18130 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18133 if (isPowerOf2_64(MulAmt2) &&
18134 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18135 // If second multiplifer is pow2, issue it first. We want the multiply by
18136 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18138 std::swap(MulAmt1, MulAmt2);
18141 if (isPowerOf2_64(MulAmt1))
18142 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18143 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18145 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18146 DAG.getConstant(MulAmt1, VT));
18148 if (isPowerOf2_64(MulAmt2))
18149 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18150 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18152 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18153 DAG.getConstant(MulAmt2, VT));
18155 // Do not add new nodes to DAG combiner worklist.
18156 DCI.CombineTo(N, NewMul, false);
18161 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18162 SDValue N0 = N->getOperand(0);
18163 SDValue N1 = N->getOperand(1);
18164 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18165 EVT VT = N0.getValueType();
18167 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18168 // since the result of setcc_c is all zero's or all ones.
18169 if (VT.isInteger() && !VT.isVector() &&
18170 N1C && N0.getOpcode() == ISD::AND &&
18171 N0.getOperand(1).getOpcode() == ISD::Constant) {
18172 SDValue N00 = N0.getOperand(0);
18173 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18174 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18175 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18176 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18177 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18178 APInt ShAmt = N1C->getAPIntValue();
18179 Mask = Mask.shl(ShAmt);
18181 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18182 N00, DAG.getConstant(Mask, VT));
18186 // Hardware support for vector shifts is sparse which makes us scalarize the
18187 // vector operations in many cases. Also, on sandybridge ADD is faster than
18189 // (shl V, 1) -> add V,V
18190 if (isSplatVector(N1.getNode())) {
18191 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18193 // We shift all of the values by one. In many cases we do not have
18194 // hardware support for this operation. This is better expressed as an ADD
18196 if (N1C && (1 == N1C->getZExtValue())) {
18197 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18204 /// \brief Returns a vector of 0s if the node in input is a vector logical
18205 /// shift by a constant amount which is known to be bigger than or equal
18206 /// to the vector element size in bits.
18207 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18208 const X86Subtarget *Subtarget) {
18209 EVT VT = N->getValueType(0);
18211 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18212 (!Subtarget->hasInt256() ||
18213 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18216 SDValue Amt = N->getOperand(1);
18218 if (isSplatVector(Amt.getNode())) {
18219 SDValue SclrAmt = Amt->getOperand(0);
18220 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18221 APInt ShiftAmt = C->getAPIntValue();
18222 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18224 // SSE2/AVX2 logical shifts always return a vector of 0s
18225 // if the shift amount is bigger than or equal to
18226 // the element size. The constant shift amount will be
18227 // encoded as a 8-bit immediate.
18228 if (ShiftAmt.trunc(8).uge(MaxAmount))
18229 return getZeroVector(VT, Subtarget, DAG, DL);
18236 /// PerformShiftCombine - Combine shifts.
18237 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18238 TargetLowering::DAGCombinerInfo &DCI,
18239 const X86Subtarget *Subtarget) {
18240 if (N->getOpcode() == ISD::SHL) {
18241 SDValue V = PerformSHLCombine(N, DAG);
18242 if (V.getNode()) return V;
18245 if (N->getOpcode() != ISD::SRA) {
18246 // Try to fold this logical shift into a zero vector.
18247 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18248 if (V.getNode()) return V;
18254 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18255 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18256 // and friends. Likewise for OR -> CMPNEQSS.
18257 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18258 TargetLowering::DAGCombinerInfo &DCI,
18259 const X86Subtarget *Subtarget) {
18262 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18263 // we're requiring SSE2 for both.
18264 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18265 SDValue N0 = N->getOperand(0);
18266 SDValue N1 = N->getOperand(1);
18267 SDValue CMP0 = N0->getOperand(1);
18268 SDValue CMP1 = N1->getOperand(1);
18271 // The SETCCs should both refer to the same CMP.
18272 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18275 SDValue CMP00 = CMP0->getOperand(0);
18276 SDValue CMP01 = CMP0->getOperand(1);
18277 EVT VT = CMP00.getValueType();
18279 if (VT == MVT::f32 || VT == MVT::f64) {
18280 bool ExpectingFlags = false;
18281 // Check for any users that want flags:
18282 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18283 !ExpectingFlags && UI != UE; ++UI)
18284 switch (UI->getOpcode()) {
18289 ExpectingFlags = true;
18291 case ISD::CopyToReg:
18292 case ISD::SIGN_EXTEND:
18293 case ISD::ZERO_EXTEND:
18294 case ISD::ANY_EXTEND:
18298 if (!ExpectingFlags) {
18299 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18300 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18302 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18303 X86::CondCode tmp = cc0;
18308 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18309 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18310 // FIXME: need symbolic constants for these magic numbers.
18311 // See X86ATTInstPrinter.cpp:printSSECC().
18312 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18313 if (Subtarget->hasAVX512()) {
18314 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18315 CMP01, DAG.getConstant(x86cc, MVT::i8));
18316 if (N->getValueType(0) != MVT::i1)
18317 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18321 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18322 CMP00.getValueType(), CMP00, CMP01,
18323 DAG.getConstant(x86cc, MVT::i8));
18325 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18326 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18328 if (is64BitFP && !Subtarget->is64Bit()) {
18329 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18330 // 64-bit integer, since that's not a legal type. Since
18331 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18332 // bits, but can do this little dance to extract the lowest 32 bits
18333 // and work with those going forward.
18334 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18336 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18338 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18339 Vector32, DAG.getIntPtrConstant(0));
18343 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18344 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18345 DAG.getConstant(1, IntVT));
18346 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18347 return OneBitOfTruth;
18355 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18356 /// so it can be folded inside ANDNP.
18357 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18358 EVT VT = N->getValueType(0);
18360 // Match direct AllOnes for 128 and 256-bit vectors
18361 if (ISD::isBuildVectorAllOnes(N))
18364 // Look through a bit convert.
18365 if (N->getOpcode() == ISD::BITCAST)
18366 N = N->getOperand(0).getNode();
18368 // Sometimes the operand may come from a insert_subvector building a 256-bit
18370 if (VT.is256BitVector() &&
18371 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18372 SDValue V1 = N->getOperand(0);
18373 SDValue V2 = N->getOperand(1);
18375 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18376 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18377 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18378 ISD::isBuildVectorAllOnes(V2.getNode()))
18385 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18386 // register. In most cases we actually compare or select YMM-sized registers
18387 // and mixing the two types creates horrible code. This method optimizes
18388 // some of the transition sequences.
18389 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18390 TargetLowering::DAGCombinerInfo &DCI,
18391 const X86Subtarget *Subtarget) {
18392 EVT VT = N->getValueType(0);
18393 if (!VT.is256BitVector())
18396 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18397 N->getOpcode() == ISD::ZERO_EXTEND ||
18398 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18400 SDValue Narrow = N->getOperand(0);
18401 EVT NarrowVT = Narrow->getValueType(0);
18402 if (!NarrowVT.is128BitVector())
18405 if (Narrow->getOpcode() != ISD::XOR &&
18406 Narrow->getOpcode() != ISD::AND &&
18407 Narrow->getOpcode() != ISD::OR)
18410 SDValue N0 = Narrow->getOperand(0);
18411 SDValue N1 = Narrow->getOperand(1);
18414 // The Left side has to be a trunc.
18415 if (N0.getOpcode() != ISD::TRUNCATE)
18418 // The type of the truncated inputs.
18419 EVT WideVT = N0->getOperand(0)->getValueType(0);
18423 // The right side has to be a 'trunc' or a constant vector.
18424 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18425 bool RHSConst = (isSplatVector(N1.getNode()) &&
18426 isa<ConstantSDNode>(N1->getOperand(0)));
18427 if (!RHSTrunc && !RHSConst)
18430 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18432 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18435 // Set N0 and N1 to hold the inputs to the new wide operation.
18436 N0 = N0->getOperand(0);
18438 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18439 N1->getOperand(0));
18440 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18441 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18442 } else if (RHSTrunc) {
18443 N1 = N1->getOperand(0);
18446 // Generate the wide operation.
18447 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18448 unsigned Opcode = N->getOpcode();
18450 case ISD::ANY_EXTEND:
18452 case ISD::ZERO_EXTEND: {
18453 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18454 APInt Mask = APInt::getAllOnesValue(InBits);
18455 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18456 return DAG.getNode(ISD::AND, DL, VT,
18457 Op, DAG.getConstant(Mask, VT));
18459 case ISD::SIGN_EXTEND:
18460 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18461 Op, DAG.getValueType(NarrowVT));
18463 llvm_unreachable("Unexpected opcode");
18467 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18468 TargetLowering::DAGCombinerInfo &DCI,
18469 const X86Subtarget *Subtarget) {
18470 EVT VT = N->getValueType(0);
18471 if (DCI.isBeforeLegalizeOps())
18474 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18478 // Create BEXTR instructions
18479 // BEXTR is ((X >> imm) & (2**size-1))
18480 if (VT == MVT::i32 || VT == MVT::i64) {
18481 SDValue N0 = N->getOperand(0);
18482 SDValue N1 = N->getOperand(1);
18485 // Check for BEXTR.
18486 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18487 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18488 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18489 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18490 if (MaskNode && ShiftNode) {
18491 uint64_t Mask = MaskNode->getZExtValue();
18492 uint64_t Shift = ShiftNode->getZExtValue();
18493 if (isMask_64(Mask)) {
18494 uint64_t MaskSize = CountPopulation_64(Mask);
18495 if (Shift + MaskSize <= VT.getSizeInBits())
18496 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18497 DAG.getConstant(Shift | (MaskSize << 8), VT));
18505 // Want to form ANDNP nodes:
18506 // 1) In the hopes of then easily combining them with OR and AND nodes
18507 // to form PBLEND/PSIGN.
18508 // 2) To match ANDN packed intrinsics
18509 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18512 SDValue N0 = N->getOperand(0);
18513 SDValue N1 = N->getOperand(1);
18516 // Check LHS for vnot
18517 if (N0.getOpcode() == ISD::XOR &&
18518 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18519 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18520 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18522 // Check RHS for vnot
18523 if (N1.getOpcode() == ISD::XOR &&
18524 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18525 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18526 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18531 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18532 TargetLowering::DAGCombinerInfo &DCI,
18533 const X86Subtarget *Subtarget) {
18534 if (DCI.isBeforeLegalizeOps())
18537 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18541 SDValue N0 = N->getOperand(0);
18542 SDValue N1 = N->getOperand(1);
18543 EVT VT = N->getValueType(0);
18545 // look for psign/blend
18546 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18547 if (!Subtarget->hasSSSE3() ||
18548 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18551 // Canonicalize pandn to RHS
18552 if (N0.getOpcode() == X86ISD::ANDNP)
18554 // or (and (m, y), (pandn m, x))
18555 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18556 SDValue Mask = N1.getOperand(0);
18557 SDValue X = N1.getOperand(1);
18559 if (N0.getOperand(0) == Mask)
18560 Y = N0.getOperand(1);
18561 if (N0.getOperand(1) == Mask)
18562 Y = N0.getOperand(0);
18564 // Check to see if the mask appeared in both the AND and ANDNP and
18568 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18569 // Look through mask bitcast.
18570 if (Mask.getOpcode() == ISD::BITCAST)
18571 Mask = Mask.getOperand(0);
18572 if (X.getOpcode() == ISD::BITCAST)
18573 X = X.getOperand(0);
18574 if (Y.getOpcode() == ISD::BITCAST)
18575 Y = Y.getOperand(0);
18577 EVT MaskVT = Mask.getValueType();
18579 // Validate that the Mask operand is a vector sra node.
18580 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18581 // there is no psrai.b
18582 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18583 unsigned SraAmt = ~0;
18584 if (Mask.getOpcode() == ISD::SRA) {
18585 SDValue Amt = Mask.getOperand(1);
18586 if (isSplatVector(Amt.getNode())) {
18587 SDValue SclrAmt = Amt->getOperand(0);
18588 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18589 SraAmt = C->getZExtValue();
18591 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18592 SDValue SraC = Mask.getOperand(1);
18593 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18595 if ((SraAmt + 1) != EltBits)
18600 // Now we know we at least have a plendvb with the mask val. See if
18601 // we can form a psignb/w/d.
18602 // psign = x.type == y.type == mask.type && y = sub(0, x);
18603 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18604 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18605 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18606 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18607 "Unsupported VT for PSIGN");
18608 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18609 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18611 // PBLENDVB only available on SSE 4.1
18612 if (!Subtarget->hasSSE41())
18615 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18617 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18618 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18619 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18620 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18621 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18625 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18628 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18629 MachineFunction &MF = DAG.getMachineFunction();
18630 bool OptForSize = MF.getFunction()->getAttributes().
18631 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18633 // SHLD/SHRD instructions have lower register pressure, but on some
18634 // platforms they have higher latency than the equivalent
18635 // series of shifts/or that would otherwise be generated.
18636 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18637 // have higher latencies and we are not optimizing for size.
18638 if (!OptForSize && Subtarget->isSHLDSlow())
18641 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18643 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18645 if (!N0.hasOneUse() || !N1.hasOneUse())
18648 SDValue ShAmt0 = N0.getOperand(1);
18649 if (ShAmt0.getValueType() != MVT::i8)
18651 SDValue ShAmt1 = N1.getOperand(1);
18652 if (ShAmt1.getValueType() != MVT::i8)
18654 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18655 ShAmt0 = ShAmt0.getOperand(0);
18656 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18657 ShAmt1 = ShAmt1.getOperand(0);
18660 unsigned Opc = X86ISD::SHLD;
18661 SDValue Op0 = N0.getOperand(0);
18662 SDValue Op1 = N1.getOperand(0);
18663 if (ShAmt0.getOpcode() == ISD::SUB) {
18664 Opc = X86ISD::SHRD;
18665 std::swap(Op0, Op1);
18666 std::swap(ShAmt0, ShAmt1);
18669 unsigned Bits = VT.getSizeInBits();
18670 if (ShAmt1.getOpcode() == ISD::SUB) {
18671 SDValue Sum = ShAmt1.getOperand(0);
18672 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18673 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18674 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18675 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18676 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18677 return DAG.getNode(Opc, DL, VT,
18679 DAG.getNode(ISD::TRUNCATE, DL,
18682 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18683 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18685 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18686 return DAG.getNode(Opc, DL, VT,
18687 N0.getOperand(0), N1.getOperand(0),
18688 DAG.getNode(ISD::TRUNCATE, DL,
18695 // Generate NEG and CMOV for integer abs.
18696 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18697 EVT VT = N->getValueType(0);
18699 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18700 // 8-bit integer abs to NEG and CMOV.
18701 if (VT.isInteger() && VT.getSizeInBits() == 8)
18704 SDValue N0 = N->getOperand(0);
18705 SDValue N1 = N->getOperand(1);
18708 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18709 // and change it to SUB and CMOV.
18710 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18711 N0.getOpcode() == ISD::ADD &&
18712 N0.getOperand(1) == N1 &&
18713 N1.getOpcode() == ISD::SRA &&
18714 N1.getOperand(0) == N0.getOperand(0))
18715 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18716 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18717 // Generate SUB & CMOV.
18718 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18719 DAG.getConstant(0, VT), N0.getOperand(0));
18721 SDValue Ops[] = { N0.getOperand(0), Neg,
18722 DAG.getConstant(X86::COND_GE, MVT::i8),
18723 SDValue(Neg.getNode(), 1) };
18724 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18725 Ops, array_lengthof(Ops));
18730 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18731 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18732 TargetLowering::DAGCombinerInfo &DCI,
18733 const X86Subtarget *Subtarget) {
18734 if (DCI.isBeforeLegalizeOps())
18737 if (Subtarget->hasCMov()) {
18738 SDValue RV = performIntegerAbsCombine(N, DAG);
18746 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18747 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18748 TargetLowering::DAGCombinerInfo &DCI,
18749 const X86Subtarget *Subtarget) {
18750 LoadSDNode *Ld = cast<LoadSDNode>(N);
18751 EVT RegVT = Ld->getValueType(0);
18752 EVT MemVT = Ld->getMemoryVT();
18754 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18755 unsigned RegSz = RegVT.getSizeInBits();
18757 // On Sandybridge unaligned 256bit loads are inefficient.
18758 ISD::LoadExtType Ext = Ld->getExtensionType();
18759 unsigned Alignment = Ld->getAlignment();
18760 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18761 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18762 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18763 unsigned NumElems = RegVT.getVectorNumElements();
18767 SDValue Ptr = Ld->getBasePtr();
18768 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18770 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18772 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18773 Ld->getPointerInfo(), Ld->isVolatile(),
18774 Ld->isNonTemporal(), Ld->isInvariant(),
18776 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18777 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18778 Ld->getPointerInfo(), Ld->isVolatile(),
18779 Ld->isNonTemporal(), Ld->isInvariant(),
18780 std::min(16U, Alignment));
18781 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18783 Load2.getValue(1));
18785 SDValue NewVec = DAG.getUNDEF(RegVT);
18786 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18787 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18788 return DCI.CombineTo(N, NewVec, TF, true);
18791 // If this is a vector EXT Load then attempt to optimize it using a
18792 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18793 // expansion is still better than scalar code.
18794 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18795 // emit a shuffle and a arithmetic shift.
18796 // TODO: It is possible to support ZExt by zeroing the undef values
18797 // during the shuffle phase or after the shuffle.
18798 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18799 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18800 assert(MemVT != RegVT && "Cannot extend to the same type");
18801 assert(MemVT.isVector() && "Must load a vector from memory");
18803 unsigned NumElems = RegVT.getVectorNumElements();
18804 unsigned MemSz = MemVT.getSizeInBits();
18805 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18807 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18810 // All sizes must be a power of two.
18811 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18814 // Attempt to load the original value using scalar loads.
18815 // Find the largest scalar type that divides the total loaded size.
18816 MVT SclrLoadTy = MVT::i8;
18817 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18818 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18819 MVT Tp = (MVT::SimpleValueType)tp;
18820 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18825 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18826 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18828 SclrLoadTy = MVT::f64;
18830 // Calculate the number of scalar loads that we need to perform
18831 // in order to load our vector from memory.
18832 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18833 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18836 unsigned loadRegZize = RegSz;
18837 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18840 // Represent our vector as a sequence of elements which are the
18841 // largest scalar that we can load.
18842 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18843 loadRegZize/SclrLoadTy.getSizeInBits());
18845 // Represent the data using the same element type that is stored in
18846 // memory. In practice, we ''widen'' MemVT.
18848 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18849 loadRegZize/MemVT.getScalarType().getSizeInBits());
18851 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18852 "Invalid vector type");
18854 // We can't shuffle using an illegal type.
18855 if (!TLI.isTypeLegal(WideVecVT))
18858 SmallVector<SDValue, 8> Chains;
18859 SDValue Ptr = Ld->getBasePtr();
18860 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18861 TLI.getPointerTy());
18862 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18864 for (unsigned i = 0; i < NumLoads; ++i) {
18865 // Perform a single load.
18866 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18867 Ptr, Ld->getPointerInfo(),
18868 Ld->isVolatile(), Ld->isNonTemporal(),
18869 Ld->isInvariant(), Ld->getAlignment());
18870 Chains.push_back(ScalarLoad.getValue(1));
18871 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18872 // another round of DAGCombining.
18874 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18876 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18877 ScalarLoad, DAG.getIntPtrConstant(i));
18879 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18882 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18885 // Bitcast the loaded value to a vector of the original element type, in
18886 // the size of the target vector type.
18887 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18888 unsigned SizeRatio = RegSz/MemSz;
18890 if (Ext == ISD::SEXTLOAD) {
18891 // If we have SSE4.1 we can directly emit a VSEXT node.
18892 if (Subtarget->hasSSE41()) {
18893 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18894 return DCI.CombineTo(N, Sext, TF, true);
18897 // Otherwise we'll shuffle the small elements in the high bits of the
18898 // larger type and perform an arithmetic shift. If the shift is not legal
18899 // it's better to scalarize.
18900 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18903 // Redistribute the loaded elements into the different locations.
18904 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18905 for (unsigned i = 0; i != NumElems; ++i)
18906 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18908 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18909 DAG.getUNDEF(WideVecVT),
18912 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18914 // Build the arithmetic shift.
18915 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18916 MemVT.getVectorElementType().getSizeInBits();
18917 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18918 DAG.getConstant(Amt, RegVT));
18920 return DCI.CombineTo(N, Shuff, TF, true);
18923 // Redistribute the loaded elements into the different locations.
18924 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18925 for (unsigned i = 0; i != NumElems; ++i)
18926 ShuffleVec[i*SizeRatio] = i;
18928 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18929 DAG.getUNDEF(WideVecVT),
18932 // Bitcast to the requested type.
18933 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18934 // Replace the original load with the new sequence
18935 // and return the new chain.
18936 return DCI.CombineTo(N, Shuff, TF, true);
18942 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18943 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18944 const X86Subtarget *Subtarget) {
18945 StoreSDNode *St = cast<StoreSDNode>(N);
18946 EVT VT = St->getValue().getValueType();
18947 EVT StVT = St->getMemoryVT();
18949 SDValue StoredVal = St->getOperand(1);
18950 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18952 // If we are saving a concatenation of two XMM registers, perform two stores.
18953 // On Sandy Bridge, 256-bit memory operations are executed by two
18954 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18955 // memory operation.
18956 unsigned Alignment = St->getAlignment();
18957 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18958 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18959 StVT == VT && !IsAligned) {
18960 unsigned NumElems = VT.getVectorNumElements();
18964 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18965 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18967 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18968 SDValue Ptr0 = St->getBasePtr();
18969 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18971 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18972 St->getPointerInfo(), St->isVolatile(),
18973 St->isNonTemporal(), Alignment);
18974 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18975 St->getPointerInfo(), St->isVolatile(),
18976 St->isNonTemporal(),
18977 std::min(16U, Alignment));
18978 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18981 // Optimize trunc store (of multiple scalars) to shuffle and store.
18982 // First, pack all of the elements in one place. Next, store to memory
18983 // in fewer chunks.
18984 if (St->isTruncatingStore() && VT.isVector()) {
18985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18986 unsigned NumElems = VT.getVectorNumElements();
18987 assert(StVT != VT && "Cannot truncate to the same type");
18988 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18989 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18991 // From, To sizes and ElemCount must be pow of two
18992 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18993 // We are going to use the original vector elt for storing.
18994 // Accumulated smaller vector elements must be a multiple of the store size.
18995 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18997 unsigned SizeRatio = FromSz / ToSz;
18999 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19001 // Create a type on which we perform the shuffle
19002 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19003 StVT.getScalarType(), NumElems*SizeRatio);
19005 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19007 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19008 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19009 for (unsigned i = 0; i != NumElems; ++i)
19010 ShuffleVec[i] = i * SizeRatio;
19012 // Can't shuffle using an illegal type.
19013 if (!TLI.isTypeLegal(WideVecVT))
19016 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19017 DAG.getUNDEF(WideVecVT),
19019 // At this point all of the data is stored at the bottom of the
19020 // register. We now need to save it to mem.
19022 // Find the largest store unit
19023 MVT StoreType = MVT::i8;
19024 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19025 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19026 MVT Tp = (MVT::SimpleValueType)tp;
19027 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19031 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19032 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19033 (64 <= NumElems * ToSz))
19034 StoreType = MVT::f64;
19036 // Bitcast the original vector into a vector of store-size units
19037 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19038 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19039 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19040 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19041 SmallVector<SDValue, 8> Chains;
19042 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19043 TLI.getPointerTy());
19044 SDValue Ptr = St->getBasePtr();
19046 // Perform one or more big stores into memory.
19047 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19048 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19049 StoreType, ShuffWide,
19050 DAG.getIntPtrConstant(i));
19051 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19052 St->getPointerInfo(), St->isVolatile(),
19053 St->isNonTemporal(), St->getAlignment());
19054 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19055 Chains.push_back(Ch);
19058 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19062 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19063 // the FP state in cases where an emms may be missing.
19064 // A preferable solution to the general problem is to figure out the right
19065 // places to insert EMMS. This qualifies as a quick hack.
19067 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19068 if (VT.getSizeInBits() != 64)
19071 const Function *F = DAG.getMachineFunction().getFunction();
19072 bool NoImplicitFloatOps = F->getAttributes().
19073 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19074 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19075 && Subtarget->hasSSE2();
19076 if ((VT.isVector() ||
19077 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19078 isa<LoadSDNode>(St->getValue()) &&
19079 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19080 St->getChain().hasOneUse() && !St->isVolatile()) {
19081 SDNode* LdVal = St->getValue().getNode();
19082 LoadSDNode *Ld = 0;
19083 int TokenFactorIndex = -1;
19084 SmallVector<SDValue, 8> Ops;
19085 SDNode* ChainVal = St->getChain().getNode();
19086 // Must be a store of a load. We currently handle two cases: the load
19087 // is a direct child, and it's under an intervening TokenFactor. It is
19088 // possible to dig deeper under nested TokenFactors.
19089 if (ChainVal == LdVal)
19090 Ld = cast<LoadSDNode>(St->getChain());
19091 else if (St->getValue().hasOneUse() &&
19092 ChainVal->getOpcode() == ISD::TokenFactor) {
19093 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19094 if (ChainVal->getOperand(i).getNode() == LdVal) {
19095 TokenFactorIndex = i;
19096 Ld = cast<LoadSDNode>(St->getValue());
19098 Ops.push_back(ChainVal->getOperand(i));
19102 if (!Ld || !ISD::isNormalLoad(Ld))
19105 // If this is not the MMX case, i.e. we are just turning i64 load/store
19106 // into f64 load/store, avoid the transformation if there are multiple
19107 // uses of the loaded value.
19108 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19113 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19114 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19116 if (Subtarget->is64Bit() || F64IsLegal) {
19117 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19118 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19119 Ld->getPointerInfo(), Ld->isVolatile(),
19120 Ld->isNonTemporal(), Ld->isInvariant(),
19121 Ld->getAlignment());
19122 SDValue NewChain = NewLd.getValue(1);
19123 if (TokenFactorIndex != -1) {
19124 Ops.push_back(NewChain);
19125 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19128 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19129 St->getPointerInfo(),
19130 St->isVolatile(), St->isNonTemporal(),
19131 St->getAlignment());
19134 // Otherwise, lower to two pairs of 32-bit loads / stores.
19135 SDValue LoAddr = Ld->getBasePtr();
19136 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19137 DAG.getConstant(4, MVT::i32));
19139 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19140 Ld->getPointerInfo(),
19141 Ld->isVolatile(), Ld->isNonTemporal(),
19142 Ld->isInvariant(), Ld->getAlignment());
19143 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19144 Ld->getPointerInfo().getWithOffset(4),
19145 Ld->isVolatile(), Ld->isNonTemporal(),
19147 MinAlign(Ld->getAlignment(), 4));
19149 SDValue NewChain = LoLd.getValue(1);
19150 if (TokenFactorIndex != -1) {
19151 Ops.push_back(LoLd);
19152 Ops.push_back(HiLd);
19153 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19157 LoAddr = St->getBasePtr();
19158 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19159 DAG.getConstant(4, MVT::i32));
19161 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19162 St->getPointerInfo(),
19163 St->isVolatile(), St->isNonTemporal(),
19164 St->getAlignment());
19165 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19166 St->getPointerInfo().getWithOffset(4),
19168 St->isNonTemporal(),
19169 MinAlign(St->getAlignment(), 4));
19170 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19175 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19176 /// and return the operands for the horizontal operation in LHS and RHS. A
19177 /// horizontal operation performs the binary operation on successive elements
19178 /// of its first operand, then on successive elements of its second operand,
19179 /// returning the resulting values in a vector. For example, if
19180 /// A = < float a0, float a1, float a2, float a3 >
19182 /// B = < float b0, float b1, float b2, float b3 >
19183 /// then the result of doing a horizontal operation on A and B is
19184 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19185 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19186 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19187 /// set to A, RHS to B, and the routine returns 'true'.
19188 /// Note that the binary operation should have the property that if one of the
19189 /// operands is UNDEF then the result is UNDEF.
19190 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19191 // Look for the following pattern: if
19192 // A = < float a0, float a1, float a2, float a3 >
19193 // B = < float b0, float b1, float b2, float b3 >
19195 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19196 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19197 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19198 // which is A horizontal-op B.
19200 // At least one of the operands should be a vector shuffle.
19201 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19202 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19205 MVT VT = LHS.getSimpleValueType();
19207 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19208 "Unsupported vector type for horizontal add/sub");
19210 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19211 // operate independently on 128-bit lanes.
19212 unsigned NumElts = VT.getVectorNumElements();
19213 unsigned NumLanes = VT.getSizeInBits()/128;
19214 unsigned NumLaneElts = NumElts / NumLanes;
19215 assert((NumLaneElts % 2 == 0) &&
19216 "Vector type should have an even number of elements in each lane");
19217 unsigned HalfLaneElts = NumLaneElts/2;
19219 // View LHS in the form
19220 // LHS = VECTOR_SHUFFLE A, B, LMask
19221 // If LHS is not a shuffle then pretend it is the shuffle
19222 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19223 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19226 SmallVector<int, 16> LMask(NumElts);
19227 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19228 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19229 A = LHS.getOperand(0);
19230 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19231 B = LHS.getOperand(1);
19232 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19233 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19235 if (LHS.getOpcode() != ISD::UNDEF)
19237 for (unsigned i = 0; i != NumElts; ++i)
19241 // Likewise, view RHS in the form
19242 // RHS = VECTOR_SHUFFLE C, D, RMask
19244 SmallVector<int, 16> RMask(NumElts);
19245 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19246 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19247 C = RHS.getOperand(0);
19248 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19249 D = RHS.getOperand(1);
19250 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19251 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19253 if (RHS.getOpcode() != ISD::UNDEF)
19255 for (unsigned i = 0; i != NumElts; ++i)
19259 // Check that the shuffles are both shuffling the same vectors.
19260 if (!(A == C && B == D) && !(A == D && B == C))
19263 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19264 if (!A.getNode() && !B.getNode())
19267 // If A and B occur in reverse order in RHS, then "swap" them (which means
19268 // rewriting the mask).
19270 CommuteVectorShuffleMask(RMask, NumElts);
19272 // At this point LHS and RHS are equivalent to
19273 // LHS = VECTOR_SHUFFLE A, B, LMask
19274 // RHS = VECTOR_SHUFFLE A, B, RMask
19275 // Check that the masks correspond to performing a horizontal operation.
19276 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19277 for (unsigned i = 0; i != NumLaneElts; ++i) {
19278 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19280 // Ignore any UNDEF components.
19281 if (LIdx < 0 || RIdx < 0 ||
19282 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19283 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19286 // Check that successive elements are being operated on. If not, this is
19287 // not a horizontal operation.
19288 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19289 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19290 if (!(LIdx == Index && RIdx == Index + 1) &&
19291 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19296 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19297 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19301 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19302 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19303 const X86Subtarget *Subtarget) {
19304 EVT VT = N->getValueType(0);
19305 SDValue LHS = N->getOperand(0);
19306 SDValue RHS = N->getOperand(1);
19308 // Try to synthesize horizontal adds from adds of shuffles.
19309 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19310 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19311 isHorizontalBinOp(LHS, RHS, true))
19312 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19316 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19317 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19318 const X86Subtarget *Subtarget) {
19319 EVT VT = N->getValueType(0);
19320 SDValue LHS = N->getOperand(0);
19321 SDValue RHS = N->getOperand(1);
19323 // Try to synthesize horizontal subs from subs of shuffles.
19324 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19325 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19326 isHorizontalBinOp(LHS, RHS, false))
19327 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19331 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19332 /// X86ISD::FXOR nodes.
19333 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19334 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19335 // F[X]OR(0.0, x) -> x
19336 // F[X]OR(x, 0.0) -> x
19337 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19338 if (C->getValueAPF().isPosZero())
19339 return N->getOperand(1);
19340 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19341 if (C->getValueAPF().isPosZero())
19342 return N->getOperand(0);
19346 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19347 /// X86ISD::FMAX nodes.
19348 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19349 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19351 // Only perform optimizations if UnsafeMath is used.
19352 if (!DAG.getTarget().Options.UnsafeFPMath)
19355 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19356 // into FMINC and FMAXC, which are Commutative operations.
19357 unsigned NewOp = 0;
19358 switch (N->getOpcode()) {
19359 default: llvm_unreachable("unknown opcode");
19360 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19361 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19364 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19365 N->getOperand(0), N->getOperand(1));
19368 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19369 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19370 // FAND(0.0, x) -> 0.0
19371 // FAND(x, 0.0) -> 0.0
19372 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19373 if (C->getValueAPF().isPosZero())
19374 return N->getOperand(0);
19375 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19376 if (C->getValueAPF().isPosZero())
19377 return N->getOperand(1);
19381 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19382 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19383 // FANDN(x, 0.0) -> 0.0
19384 // FANDN(0.0, x) -> x
19385 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19386 if (C->getValueAPF().isPosZero())
19387 return N->getOperand(1);
19388 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19389 if (C->getValueAPF().isPosZero())
19390 return N->getOperand(1);
19394 static SDValue PerformBTCombine(SDNode *N,
19396 TargetLowering::DAGCombinerInfo &DCI) {
19397 // BT ignores high bits in the bit index operand.
19398 SDValue Op1 = N->getOperand(1);
19399 if (Op1.hasOneUse()) {
19400 unsigned BitWidth = Op1.getValueSizeInBits();
19401 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19402 APInt KnownZero, KnownOne;
19403 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19404 !DCI.isBeforeLegalizeOps());
19405 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19406 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19407 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19408 DCI.CommitTargetLoweringOpt(TLO);
19413 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19414 SDValue Op = N->getOperand(0);
19415 if (Op.getOpcode() == ISD::BITCAST)
19416 Op = Op.getOperand(0);
19417 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19418 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19419 VT.getVectorElementType().getSizeInBits() ==
19420 OpVT.getVectorElementType().getSizeInBits()) {
19421 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19426 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19427 const X86Subtarget *Subtarget) {
19428 EVT VT = N->getValueType(0);
19429 if (!VT.isVector())
19432 SDValue N0 = N->getOperand(0);
19433 SDValue N1 = N->getOperand(1);
19434 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19437 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19438 // both SSE and AVX2 since there is no sign-extended shift right
19439 // operation on a vector with 64-bit elements.
19440 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19441 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19442 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19443 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19444 SDValue N00 = N0.getOperand(0);
19446 // EXTLOAD has a better solution on AVX2,
19447 // it may be replaced with X86ISD::VSEXT node.
19448 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19449 if (!ISD::isNormalLoad(N00.getNode()))
19452 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19453 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19455 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19461 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19462 TargetLowering::DAGCombinerInfo &DCI,
19463 const X86Subtarget *Subtarget) {
19464 if (!DCI.isBeforeLegalizeOps())
19467 if (!Subtarget->hasFp256())
19470 EVT VT = N->getValueType(0);
19471 if (VT.isVector() && VT.getSizeInBits() == 256) {
19472 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19480 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19481 const X86Subtarget* Subtarget) {
19483 EVT VT = N->getValueType(0);
19485 // Let legalize expand this if it isn't a legal type yet.
19486 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19489 EVT ScalarVT = VT.getScalarType();
19490 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19491 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19494 SDValue A = N->getOperand(0);
19495 SDValue B = N->getOperand(1);
19496 SDValue C = N->getOperand(2);
19498 bool NegA = (A.getOpcode() == ISD::FNEG);
19499 bool NegB = (B.getOpcode() == ISD::FNEG);
19500 bool NegC = (C.getOpcode() == ISD::FNEG);
19502 // Negative multiplication when NegA xor NegB
19503 bool NegMul = (NegA != NegB);
19505 A = A.getOperand(0);
19507 B = B.getOperand(0);
19509 C = C.getOperand(0);
19513 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19515 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19517 return DAG.getNode(Opcode, dl, VT, A, B, C);
19520 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19521 TargetLowering::DAGCombinerInfo &DCI,
19522 const X86Subtarget *Subtarget) {
19523 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19524 // (and (i32 x86isd::setcc_carry), 1)
19525 // This eliminates the zext. This transformation is necessary because
19526 // ISD::SETCC is always legalized to i8.
19528 SDValue N0 = N->getOperand(0);
19529 EVT VT = N->getValueType(0);
19531 if (N0.getOpcode() == ISD::AND &&
19533 N0.getOperand(0).hasOneUse()) {
19534 SDValue N00 = N0.getOperand(0);
19535 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19536 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19537 if (!C || C->getZExtValue() != 1)
19539 return DAG.getNode(ISD::AND, dl, VT,
19540 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19541 N00.getOperand(0), N00.getOperand(1)),
19542 DAG.getConstant(1, VT));
19546 if (N0.getOpcode() == ISD::TRUNCATE &&
19548 N0.getOperand(0).hasOneUse()) {
19549 SDValue N00 = N0.getOperand(0);
19550 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19551 return DAG.getNode(ISD::AND, dl, VT,
19552 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19553 N00.getOperand(0), N00.getOperand(1)),
19554 DAG.getConstant(1, VT));
19557 if (VT.is256BitVector()) {
19558 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19566 // Optimize x == -y --> x+y == 0
19567 // x != -y --> x+y != 0
19568 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19569 const X86Subtarget* Subtarget) {
19570 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19571 SDValue LHS = N->getOperand(0);
19572 SDValue RHS = N->getOperand(1);
19573 EVT VT = N->getValueType(0);
19576 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19577 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19578 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19579 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19580 LHS.getValueType(), RHS, LHS.getOperand(1));
19581 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19582 addV, DAG.getConstant(0, addV.getValueType()), CC);
19584 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19585 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19586 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19587 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19588 RHS.getValueType(), LHS, RHS.getOperand(1));
19589 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19590 addV, DAG.getConstant(0, addV.getValueType()), CC);
19593 if (VT.getScalarType() == MVT::i1) {
19594 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19595 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19596 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19597 if (!IsSEXT0 && !IsVZero0)
19599 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19600 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19601 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19603 if (!IsSEXT1 && !IsVZero1)
19606 if (IsSEXT0 && IsVZero1) {
19607 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19608 if (CC == ISD::SETEQ)
19609 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19610 return LHS.getOperand(0);
19612 if (IsSEXT1 && IsVZero0) {
19613 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19614 if (CC == ISD::SETEQ)
19615 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19616 return RHS.getOperand(0);
19623 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19624 // as "sbb reg,reg", since it can be extended without zext and produces
19625 // an all-ones bit which is more useful than 0/1 in some cases.
19626 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19629 return DAG.getNode(ISD::AND, DL, VT,
19630 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19631 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19632 DAG.getConstant(1, VT));
19633 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19634 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19635 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19636 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19639 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19640 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19641 TargetLowering::DAGCombinerInfo &DCI,
19642 const X86Subtarget *Subtarget) {
19644 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19645 SDValue EFLAGS = N->getOperand(1);
19647 if (CC == X86::COND_A) {
19648 // Try to convert COND_A into COND_B in an attempt to facilitate
19649 // materializing "setb reg".
19651 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19652 // cannot take an immediate as its first operand.
19654 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19655 EFLAGS.getValueType().isInteger() &&
19656 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19657 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19658 EFLAGS.getNode()->getVTList(),
19659 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19660 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19661 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19665 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19666 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19668 if (CC == X86::COND_B)
19669 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19673 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19674 if (Flags.getNode()) {
19675 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19676 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19682 // Optimize branch condition evaluation.
19684 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19685 TargetLowering::DAGCombinerInfo &DCI,
19686 const X86Subtarget *Subtarget) {
19688 SDValue Chain = N->getOperand(0);
19689 SDValue Dest = N->getOperand(1);
19690 SDValue EFLAGS = N->getOperand(3);
19691 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19695 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19696 if (Flags.getNode()) {
19697 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19698 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19705 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19706 const X86TargetLowering *XTLI) {
19707 SDValue Op0 = N->getOperand(0);
19708 EVT InVT = Op0->getValueType(0);
19710 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19711 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19713 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19714 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19715 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19718 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19719 // a 32-bit target where SSE doesn't support i64->FP operations.
19720 if (Op0.getOpcode() == ISD::LOAD) {
19721 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19722 EVT VT = Ld->getValueType(0);
19723 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19724 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19725 !XTLI->getSubtarget()->is64Bit() &&
19727 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19728 Ld->getChain(), Op0, DAG);
19729 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19736 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19737 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19738 X86TargetLowering::DAGCombinerInfo &DCI) {
19739 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19740 // the result is either zero or one (depending on the input carry bit).
19741 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19742 if (X86::isZeroNode(N->getOperand(0)) &&
19743 X86::isZeroNode(N->getOperand(1)) &&
19744 // We don't have a good way to replace an EFLAGS use, so only do this when
19746 SDValue(N, 1).use_empty()) {
19748 EVT VT = N->getValueType(0);
19749 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19750 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19751 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19752 DAG.getConstant(X86::COND_B,MVT::i8),
19754 DAG.getConstant(1, VT));
19755 return DCI.CombineTo(N, Res1, CarryOut);
19761 // fold (add Y, (sete X, 0)) -> adc 0, Y
19762 // (add Y, (setne X, 0)) -> sbb -1, Y
19763 // (sub (sete X, 0), Y) -> sbb 0, Y
19764 // (sub (setne X, 0), Y) -> adc -1, Y
19765 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19768 // Look through ZExts.
19769 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19770 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19773 SDValue SetCC = Ext.getOperand(0);
19774 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19777 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19778 if (CC != X86::COND_E && CC != X86::COND_NE)
19781 SDValue Cmp = SetCC.getOperand(1);
19782 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19783 !X86::isZeroNode(Cmp.getOperand(1)) ||
19784 !Cmp.getOperand(0).getValueType().isInteger())
19787 SDValue CmpOp0 = Cmp.getOperand(0);
19788 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19789 DAG.getConstant(1, CmpOp0.getValueType()));
19791 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19792 if (CC == X86::COND_NE)
19793 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19794 DL, OtherVal.getValueType(), OtherVal,
19795 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19796 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19797 DL, OtherVal.getValueType(), OtherVal,
19798 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19801 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19802 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19803 const X86Subtarget *Subtarget) {
19804 EVT VT = N->getValueType(0);
19805 SDValue Op0 = N->getOperand(0);
19806 SDValue Op1 = N->getOperand(1);
19808 // Try to synthesize horizontal adds from adds of shuffles.
19809 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19810 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19811 isHorizontalBinOp(Op0, Op1, true))
19812 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19814 return OptimizeConditionalInDecrement(N, DAG);
19817 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19818 const X86Subtarget *Subtarget) {
19819 SDValue Op0 = N->getOperand(0);
19820 SDValue Op1 = N->getOperand(1);
19822 // X86 can't encode an immediate LHS of a sub. See if we can push the
19823 // negation into a preceding instruction.
19824 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19825 // If the RHS of the sub is a XOR with one use and a constant, invert the
19826 // immediate. Then add one to the LHS of the sub so we can turn
19827 // X-Y -> X+~Y+1, saving one register.
19828 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19829 isa<ConstantSDNode>(Op1.getOperand(1))) {
19830 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19831 EVT VT = Op0.getValueType();
19832 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19834 DAG.getConstant(~XorC, VT));
19835 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19836 DAG.getConstant(C->getAPIntValue()+1, VT));
19840 // Try to synthesize horizontal adds from adds of shuffles.
19841 EVT VT = N->getValueType(0);
19842 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19843 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19844 isHorizontalBinOp(Op0, Op1, true))
19845 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19847 return OptimizeConditionalInDecrement(N, DAG);
19850 /// performVZEXTCombine - Performs build vector combines
19851 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19852 TargetLowering::DAGCombinerInfo &DCI,
19853 const X86Subtarget *Subtarget) {
19854 // (vzext (bitcast (vzext (x)) -> (vzext x)
19855 SDValue In = N->getOperand(0);
19856 while (In.getOpcode() == ISD::BITCAST)
19857 In = In.getOperand(0);
19859 if (In.getOpcode() != X86ISD::VZEXT)
19862 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19866 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19867 DAGCombinerInfo &DCI) const {
19868 SelectionDAG &DAG = DCI.DAG;
19869 switch (N->getOpcode()) {
19871 case ISD::EXTRACT_VECTOR_ELT:
19872 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19874 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19875 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19876 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19877 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19878 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19879 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19882 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19883 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19884 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19885 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19886 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19887 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19888 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19889 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19890 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19892 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19894 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19895 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19896 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19897 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19898 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19899 case ISD::ANY_EXTEND:
19900 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19901 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19902 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19903 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19904 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
19905 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19906 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19907 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19908 case X86ISD::SHUFP: // Handle all target specific shuffles
19909 case X86ISD::PALIGNR:
19910 case X86ISD::UNPCKH:
19911 case X86ISD::UNPCKL:
19912 case X86ISD::MOVHLPS:
19913 case X86ISD::MOVLHPS:
19914 case X86ISD::PSHUFD:
19915 case X86ISD::PSHUFHW:
19916 case X86ISD::PSHUFLW:
19917 case X86ISD::MOVSS:
19918 case X86ISD::MOVSD:
19919 case X86ISD::VPERMILP:
19920 case X86ISD::VPERM2X128:
19921 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19922 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19928 /// isTypeDesirableForOp - Return true if the target has native support for
19929 /// the specified value type and it is 'desirable' to use the type for the
19930 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19931 /// instruction encodings are longer and some i16 instructions are slow.
19932 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19933 if (!isTypeLegal(VT))
19935 if (VT != MVT::i16)
19942 case ISD::SIGN_EXTEND:
19943 case ISD::ZERO_EXTEND:
19944 case ISD::ANY_EXTEND:
19957 /// IsDesirableToPromoteOp - This method query the target whether it is
19958 /// beneficial for dag combiner to promote the specified node. If true, it
19959 /// should return the desired promotion type by reference.
19960 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19961 EVT VT = Op.getValueType();
19962 if (VT != MVT::i16)
19965 bool Promote = false;
19966 bool Commute = false;
19967 switch (Op.getOpcode()) {
19970 LoadSDNode *LD = cast<LoadSDNode>(Op);
19971 // If the non-extending load has a single use and it's not live out, then it
19972 // might be folded.
19973 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19974 Op.hasOneUse()*/) {
19975 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19976 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19977 // The only case where we'd want to promote LOAD (rather then it being
19978 // promoted as an operand is when it's only use is liveout.
19979 if (UI->getOpcode() != ISD::CopyToReg)
19986 case ISD::SIGN_EXTEND:
19987 case ISD::ZERO_EXTEND:
19988 case ISD::ANY_EXTEND:
19993 SDValue N0 = Op.getOperand(0);
19994 // Look out for (store (shl (load), x)).
19995 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20008 SDValue N0 = Op.getOperand(0);
20009 SDValue N1 = Op.getOperand(1);
20010 if (!Commute && MayFoldLoad(N1))
20012 // Avoid disabling potential load folding opportunities.
20013 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20015 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20025 //===----------------------------------------------------------------------===//
20026 // X86 Inline Assembly Support
20027 //===----------------------------------------------------------------------===//
20030 // Helper to match a string separated by whitespace.
20031 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20032 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20034 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20035 StringRef piece(*args[i]);
20036 if (!s.startswith(piece)) // Check if the piece matches.
20039 s = s.substr(piece.size());
20040 StringRef::size_type pos = s.find_first_not_of(" \t");
20041 if (pos == 0) // We matched a prefix.
20049 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20052 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20054 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20055 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20056 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20057 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20059 if (AsmPieces.size() == 3)
20061 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20068 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20069 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20071 std::string AsmStr = IA->getAsmString();
20073 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20074 if (!Ty || Ty->getBitWidth() % 16 != 0)
20077 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20078 SmallVector<StringRef, 4> AsmPieces;
20079 SplitString(AsmStr, AsmPieces, ";\n");
20081 switch (AsmPieces.size()) {
20082 default: return false;
20084 // FIXME: this should verify that we are targeting a 486 or better. If not,
20085 // we will turn this bswap into something that will be lowered to logical
20086 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20087 // lower so don't worry about this.
20089 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20090 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20091 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20092 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20093 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20094 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20095 // No need to check constraints, nothing other than the equivalent of
20096 // "=r,0" would be valid here.
20097 return IntrinsicLowering::LowerToByteSwap(CI);
20100 // rorw $$8, ${0:w} --> llvm.bswap.i16
20101 if (CI->getType()->isIntegerTy(16) &&
20102 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20103 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20104 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20106 const std::string &ConstraintsStr = IA->getConstraintString();
20107 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20108 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20109 if (clobbersFlagRegisters(AsmPieces))
20110 return IntrinsicLowering::LowerToByteSwap(CI);
20114 if (CI->getType()->isIntegerTy(32) &&
20115 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20116 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20117 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20118 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20120 const std::string &ConstraintsStr = IA->getConstraintString();
20121 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20122 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20123 if (clobbersFlagRegisters(AsmPieces))
20124 return IntrinsicLowering::LowerToByteSwap(CI);
20127 if (CI->getType()->isIntegerTy(64)) {
20128 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20129 if (Constraints.size() >= 2 &&
20130 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20131 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20132 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20133 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20134 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20135 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20136 return IntrinsicLowering::LowerToByteSwap(CI);
20144 /// getConstraintType - Given a constraint letter, return the type of
20145 /// constraint it is for this target.
20146 X86TargetLowering::ConstraintType
20147 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20148 if (Constraint.size() == 1) {
20149 switch (Constraint[0]) {
20160 return C_RegisterClass;
20184 return TargetLowering::getConstraintType(Constraint);
20187 /// Examine constraint type and operand type and determine a weight value.
20188 /// This object must already have been set up with the operand type
20189 /// and the current alternative constraint selected.
20190 TargetLowering::ConstraintWeight
20191 X86TargetLowering::getSingleConstraintMatchWeight(
20192 AsmOperandInfo &info, const char *constraint) const {
20193 ConstraintWeight weight = CW_Invalid;
20194 Value *CallOperandVal = info.CallOperandVal;
20195 // If we don't have a value, we can't do a match,
20196 // but allow it at the lowest weight.
20197 if (CallOperandVal == NULL)
20199 Type *type = CallOperandVal->getType();
20200 // Look at the constraint type.
20201 switch (*constraint) {
20203 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20214 if (CallOperandVal->getType()->isIntegerTy())
20215 weight = CW_SpecificReg;
20220 if (type->isFloatingPointTy())
20221 weight = CW_SpecificReg;
20224 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20225 weight = CW_SpecificReg;
20229 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20230 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20231 weight = CW_Register;
20234 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20235 if (C->getZExtValue() <= 31)
20236 weight = CW_Constant;
20240 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20241 if (C->getZExtValue() <= 63)
20242 weight = CW_Constant;
20246 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20247 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20248 weight = CW_Constant;
20252 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20253 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20254 weight = CW_Constant;
20258 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20259 if (C->getZExtValue() <= 3)
20260 weight = CW_Constant;
20264 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20265 if (C->getZExtValue() <= 0xff)
20266 weight = CW_Constant;
20271 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20272 weight = CW_Constant;
20276 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20277 if ((C->getSExtValue() >= -0x80000000LL) &&
20278 (C->getSExtValue() <= 0x7fffffffLL))
20279 weight = CW_Constant;
20283 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20284 if (C->getZExtValue() <= 0xffffffff)
20285 weight = CW_Constant;
20292 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20293 /// with another that has more specific requirements based on the type of the
20294 /// corresponding operand.
20295 const char *X86TargetLowering::
20296 LowerXConstraint(EVT ConstraintVT) const {
20297 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20298 // 'f' like normal targets.
20299 if (ConstraintVT.isFloatingPoint()) {
20300 if (Subtarget->hasSSE2())
20302 if (Subtarget->hasSSE1())
20306 return TargetLowering::LowerXConstraint(ConstraintVT);
20309 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20310 /// vector. If it is invalid, don't add anything to Ops.
20311 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20312 std::string &Constraint,
20313 std::vector<SDValue>&Ops,
20314 SelectionDAG &DAG) const {
20315 SDValue Result(0, 0);
20317 // Only support length 1 constraints for now.
20318 if (Constraint.length() > 1) return;
20320 char ConstraintLetter = Constraint[0];
20321 switch (ConstraintLetter) {
20324 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20325 if (C->getZExtValue() <= 31) {
20326 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20333 if (C->getZExtValue() <= 63) {
20334 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20340 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20341 if (isInt<8>(C->getSExtValue())) {
20342 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20348 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20349 if (C->getZExtValue() <= 255) {
20350 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20356 // 32-bit signed value
20357 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20358 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20359 C->getSExtValue())) {
20360 // Widen to 64 bits here to get it sign extended.
20361 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20364 // FIXME gcc accepts some relocatable values here too, but only in certain
20365 // memory models; it's complicated.
20370 // 32-bit unsigned value
20371 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20372 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20373 C->getZExtValue())) {
20374 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20378 // FIXME gcc accepts some relocatable values here too, but only in certain
20379 // memory models; it's complicated.
20383 // Literal immediates are always ok.
20384 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20385 // Widen to 64 bits here to get it sign extended.
20386 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20390 // In any sort of PIC mode addresses need to be computed at runtime by
20391 // adding in a register or some sort of table lookup. These can't
20392 // be used as immediates.
20393 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20396 // If we are in non-pic codegen mode, we allow the address of a global (with
20397 // an optional displacement) to be used with 'i'.
20398 GlobalAddressSDNode *GA = 0;
20399 int64_t Offset = 0;
20401 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20403 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20404 Offset += GA->getOffset();
20406 } else if (Op.getOpcode() == ISD::ADD) {
20407 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20408 Offset += C->getZExtValue();
20409 Op = Op.getOperand(0);
20412 } else if (Op.getOpcode() == ISD::SUB) {
20413 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20414 Offset += -C->getZExtValue();
20415 Op = Op.getOperand(0);
20420 // Otherwise, this isn't something we can handle, reject it.
20424 const GlobalValue *GV = GA->getGlobal();
20425 // If we require an extra load to get this address, as in PIC mode, we
20426 // can't accept it.
20427 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20428 getTargetMachine())))
20431 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20432 GA->getValueType(0), Offset);
20437 if (Result.getNode()) {
20438 Ops.push_back(Result);
20441 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20444 std::pair<unsigned, const TargetRegisterClass*>
20445 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20447 // First, see if this is a constraint that directly corresponds to an LLVM
20449 if (Constraint.size() == 1) {
20450 // GCC Constraint Letters
20451 switch (Constraint[0]) {
20453 // TODO: Slight differences here in allocation order and leaving
20454 // RIP in the class. Do they matter any more here than they do
20455 // in the normal allocation?
20456 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20457 if (Subtarget->is64Bit()) {
20458 if (VT == MVT::i32 || VT == MVT::f32)
20459 return std::make_pair(0U, &X86::GR32RegClass);
20460 if (VT == MVT::i16)
20461 return std::make_pair(0U, &X86::GR16RegClass);
20462 if (VT == MVT::i8 || VT == MVT::i1)
20463 return std::make_pair(0U, &X86::GR8RegClass);
20464 if (VT == MVT::i64 || VT == MVT::f64)
20465 return std::make_pair(0U, &X86::GR64RegClass);
20468 // 32-bit fallthrough
20469 case 'Q': // Q_REGS
20470 if (VT == MVT::i32 || VT == MVT::f32)
20471 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20472 if (VT == MVT::i16)
20473 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20474 if (VT == MVT::i8 || VT == MVT::i1)
20475 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20476 if (VT == MVT::i64)
20477 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20479 case 'r': // GENERAL_REGS
20480 case 'l': // INDEX_REGS
20481 if (VT == MVT::i8 || VT == MVT::i1)
20482 return std::make_pair(0U, &X86::GR8RegClass);
20483 if (VT == MVT::i16)
20484 return std::make_pair(0U, &X86::GR16RegClass);
20485 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20486 return std::make_pair(0U, &X86::GR32RegClass);
20487 return std::make_pair(0U, &X86::GR64RegClass);
20488 case 'R': // LEGACY_REGS
20489 if (VT == MVT::i8 || VT == MVT::i1)
20490 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20491 if (VT == MVT::i16)
20492 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20493 if (VT == MVT::i32 || !Subtarget->is64Bit())
20494 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20495 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20496 case 'f': // FP Stack registers.
20497 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20498 // value to the correct fpstack register class.
20499 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20500 return std::make_pair(0U, &X86::RFP32RegClass);
20501 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20502 return std::make_pair(0U, &X86::RFP64RegClass);
20503 return std::make_pair(0U, &X86::RFP80RegClass);
20504 case 'y': // MMX_REGS if MMX allowed.
20505 if (!Subtarget->hasMMX()) break;
20506 return std::make_pair(0U, &X86::VR64RegClass);
20507 case 'Y': // SSE_REGS if SSE2 allowed
20508 if (!Subtarget->hasSSE2()) break;
20510 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20511 if (!Subtarget->hasSSE1()) break;
20513 switch (VT.SimpleTy) {
20515 // Scalar SSE types.
20518 return std::make_pair(0U, &X86::FR32RegClass);
20521 return std::make_pair(0U, &X86::FR64RegClass);
20529 return std::make_pair(0U, &X86::VR128RegClass);
20537 return std::make_pair(0U, &X86::VR256RegClass);
20542 return std::make_pair(0U, &X86::VR512RegClass);
20548 // Use the default implementation in TargetLowering to convert the register
20549 // constraint into a member of a register class.
20550 std::pair<unsigned, const TargetRegisterClass*> Res;
20551 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20553 // Not found as a standard register?
20554 if (Res.second == 0) {
20555 // Map st(0) -> st(7) -> ST0
20556 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20557 tolower(Constraint[1]) == 's' &&
20558 tolower(Constraint[2]) == 't' &&
20559 Constraint[3] == '(' &&
20560 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20561 Constraint[5] == ')' &&
20562 Constraint[6] == '}') {
20564 Res.first = X86::ST0+Constraint[4]-'0';
20565 Res.second = &X86::RFP80RegClass;
20569 // GCC allows "st(0)" to be called just plain "st".
20570 if (StringRef("{st}").equals_lower(Constraint)) {
20571 Res.first = X86::ST0;
20572 Res.second = &X86::RFP80RegClass;
20577 if (StringRef("{flags}").equals_lower(Constraint)) {
20578 Res.first = X86::EFLAGS;
20579 Res.second = &X86::CCRRegClass;
20583 // 'A' means EAX + EDX.
20584 if (Constraint == "A") {
20585 Res.first = X86::EAX;
20586 Res.second = &X86::GR32_ADRegClass;
20592 // Otherwise, check to see if this is a register class of the wrong value
20593 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20594 // turn into {ax},{dx}.
20595 if (Res.second->hasType(VT))
20596 return Res; // Correct type already, nothing to do.
20598 // All of the single-register GCC register classes map their values onto
20599 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20600 // really want an 8-bit or 32-bit register, map to the appropriate register
20601 // class and return the appropriate register.
20602 if (Res.second == &X86::GR16RegClass) {
20603 if (VT == MVT::i8 || VT == MVT::i1) {
20604 unsigned DestReg = 0;
20605 switch (Res.first) {
20607 case X86::AX: DestReg = X86::AL; break;
20608 case X86::DX: DestReg = X86::DL; break;
20609 case X86::CX: DestReg = X86::CL; break;
20610 case X86::BX: DestReg = X86::BL; break;
20613 Res.first = DestReg;
20614 Res.second = &X86::GR8RegClass;
20616 } else if (VT == MVT::i32 || VT == MVT::f32) {
20617 unsigned DestReg = 0;
20618 switch (Res.first) {
20620 case X86::AX: DestReg = X86::EAX; break;
20621 case X86::DX: DestReg = X86::EDX; break;
20622 case X86::CX: DestReg = X86::ECX; break;
20623 case X86::BX: DestReg = X86::EBX; break;
20624 case X86::SI: DestReg = X86::ESI; break;
20625 case X86::DI: DestReg = X86::EDI; break;
20626 case X86::BP: DestReg = X86::EBP; break;
20627 case X86::SP: DestReg = X86::ESP; break;
20630 Res.first = DestReg;
20631 Res.second = &X86::GR32RegClass;
20633 } else if (VT == MVT::i64 || VT == MVT::f64) {
20634 unsigned DestReg = 0;
20635 switch (Res.first) {
20637 case X86::AX: DestReg = X86::RAX; break;
20638 case X86::DX: DestReg = X86::RDX; break;
20639 case X86::CX: DestReg = X86::RCX; break;
20640 case X86::BX: DestReg = X86::RBX; break;
20641 case X86::SI: DestReg = X86::RSI; break;
20642 case X86::DI: DestReg = X86::RDI; break;
20643 case X86::BP: DestReg = X86::RBP; break;
20644 case X86::SP: DestReg = X86::RSP; break;
20647 Res.first = DestReg;
20648 Res.second = &X86::GR64RegClass;
20651 } else if (Res.second == &X86::FR32RegClass ||
20652 Res.second == &X86::FR64RegClass ||
20653 Res.second == &X86::VR128RegClass ||
20654 Res.second == &X86::VR256RegClass ||
20655 Res.second == &X86::FR32XRegClass ||
20656 Res.second == &X86::FR64XRegClass ||
20657 Res.second == &X86::VR128XRegClass ||
20658 Res.second == &X86::VR256XRegClass ||
20659 Res.second == &X86::VR512RegClass) {
20660 // Handle references to XMM physical registers that got mapped into the
20661 // wrong class. This can happen with constraints like {xmm0} where the
20662 // target independent register mapper will just pick the first match it can
20663 // find, ignoring the required type.
20665 if (VT == MVT::f32 || VT == MVT::i32)
20666 Res.second = &X86::FR32RegClass;
20667 else if (VT == MVT::f64 || VT == MVT::i64)
20668 Res.second = &X86::FR64RegClass;
20669 else if (X86::VR128RegClass.hasType(VT))
20670 Res.second = &X86::VR128RegClass;
20671 else if (X86::VR256RegClass.hasType(VT))
20672 Res.second = &X86::VR256RegClass;
20673 else if (X86::VR512RegClass.hasType(VT))
20674 Res.second = &X86::VR512RegClass;