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 ArrayRef<SDUse>(Vec->op_begin()+NormalizedIdxVal,
91 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
92 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
98 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
99 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
100 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
101 /// instructions or a simple subregister reference. Idx is an index in the
102 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
103 /// lowering EXTRACT_VECTOR_ELT operations easier.
104 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
105 SelectionDAG &DAG, SDLoc dl) {
106 assert((Vec.getValueType().is256BitVector() ||
107 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
108 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
111 /// Generate a DAG to grab 256-bits from a 512-bit vector.
112 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
113 SelectionDAG &DAG, SDLoc dl) {
114 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
115 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
118 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
119 unsigned IdxVal, SelectionDAG &DAG,
120 SDLoc dl, unsigned vectorWidth) {
121 assert((vectorWidth == 128 || vectorWidth == 256) &&
122 "Unsupported vector width");
123 // Inserting UNDEF is Result
124 if (Vec.getOpcode() == ISD::UNDEF)
126 EVT VT = Vec.getValueType();
127 EVT ElVT = VT.getVectorElementType();
128 EVT ResultVT = Result.getValueType();
130 // Insert the relevant vectorWidth bits.
131 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133 // This is the index of the first element of the vectorWidth-bit chunk
135 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
138 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
139 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
142 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
143 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
144 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
145 /// simple superregister reference. Idx is an index in the 128 bits
146 /// we want. It need not be aligned to a 128-bit bounday. That makes
147 /// lowering INSERT_VECTOR_ELT operations easier.
148 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
149 unsigned IdxVal, SelectionDAG &DAG,
151 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
152 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
155 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
156 unsigned IdxVal, SelectionDAG &DAG,
158 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
159 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
162 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
163 /// instructions. This is used because creating CONCAT_VECTOR nodes of
164 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
165 /// large BUILD_VECTORS.
166 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
167 unsigned NumElems, SelectionDAG &DAG,
169 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
170 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
173 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
174 unsigned NumElems, SelectionDAG &DAG,
176 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
177 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
180 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
181 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
182 bool is64Bit = Subtarget->is64Bit();
184 if (Subtarget->isTargetMacho()) {
186 return new X86_64MachoTargetObjectFile();
187 return new TargetLoweringObjectFileMachO();
190 if (Subtarget->isTargetLinux())
191 return new X86LinuxTargetObjectFile();
192 if (Subtarget->isTargetELF())
193 return new TargetLoweringObjectFileELF();
194 if (Subtarget->isTargetKnownWindowsMSVC())
195 return new X86WindowsTargetObjectFile();
196 if (Subtarget->isTargetCOFF())
197 return new TargetLoweringObjectFileCOFF();
198 llvm_unreachable("unknown subtarget type");
201 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
202 : TargetLowering(TM, createTLOF(TM)) {
203 Subtarget = &TM.getSubtarget<X86Subtarget>();
204 X86ScalarSSEf64 = Subtarget->hasSSE2();
205 X86ScalarSSEf32 = Subtarget->hasSSE1();
206 TD = getDataLayout();
208 resetOperationActions();
211 void X86TargetLowering::resetOperationActions() {
212 const TargetMachine &TM = getTargetMachine();
213 static bool FirstTimeThrough = true;
215 // If none of the target options have changed, then we don't need to reset the
216 // operation actions.
217 if (!FirstTimeThrough && TO == TM.Options) return;
219 if (!FirstTimeThrough) {
220 // Reinitialize the actions.
222 FirstTimeThrough = false;
227 // Set up the TargetLowering object.
228 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230 // X86 is weird, it always uses i8 for shift amounts and setcc results.
231 setBooleanContents(ZeroOrOneBooleanContent);
232 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
233 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235 // For 64-bit since we have so many registers use the ILP scheduler, for
236 // 32-bit code use the register pressure specific scheduling.
237 // For Atom, always use ILP scheduling.
238 if (Subtarget->isAtom())
239 setSchedulingPreference(Sched::ILP);
240 else if (Subtarget->is64Bit())
241 setSchedulingPreference(Sched::ILP);
243 setSchedulingPreference(Sched::RegPressure);
244 const X86RegisterInfo *RegInfo =
245 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
246 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248 // Bypass expensive divides on Atom when compiling with O2
249 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
250 addBypassSlowDiv(32, 8);
251 if (Subtarget->is64Bit())
252 addBypassSlowDiv(64, 16);
255 if (Subtarget->isTargetKnownWindowsMSVC()) {
256 // Setup Windows compiler runtime calls.
257 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
258 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
259 setLibcallName(RTLIB::SREM_I64, "_allrem");
260 setLibcallName(RTLIB::UREM_I64, "_aullrem");
261 setLibcallName(RTLIB::MUL_I64, "_allmul");
262 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268 // The _ftol2 runtime function has an unusual calling conv, which
269 // is modeled by a special pseudo-instruction.
270 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
276 if (Subtarget->isTargetDarwin()) {
277 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
278 setUseUnderscoreSetJmp(false);
279 setUseUnderscoreLongJmp(false);
280 } else if (Subtarget->isTargetWindowsGNU()) {
281 // MS runtime is weird: it exports _setjmp, but longjmp!
282 setUseUnderscoreSetJmp(true);
283 setUseUnderscoreLongJmp(false);
285 setUseUnderscoreSetJmp(true);
286 setUseUnderscoreLongJmp(true);
289 // Set up the register classes.
290 addRegisterClass(MVT::i8, &X86::GR8RegClass);
291 addRegisterClass(MVT::i16, &X86::GR16RegClass);
292 addRegisterClass(MVT::i32, &X86::GR32RegClass);
293 if (Subtarget->is64Bit())
294 addRegisterClass(MVT::i64, &X86::GR64RegClass);
296 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298 // We don't accept any truncstore of integer registers.
299 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
303 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
304 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
306 // SETOEQ and SETUNE require checking two conditions.
307 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
320 if (Subtarget->is64Bit()) {
321 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
323 } else if (!TM.Options.UseSoftFloat) {
324 // We have an algorithm for SSE2->double, and we turn this into a
325 // 64-bit FILD followed by conditional FADD for other targets.
326 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
327 // We have an algorithm for SSE2, and we turn this into a 64-bit
328 // FILD for other targets.
329 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
332 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
335 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
337 if (!TM.Options.UseSoftFloat) {
338 // SSE has no i16 to fp conversion, only i32
339 if (X86ScalarSSEf32) {
340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
341 // f32 and f64 cases are Legal, f80 case is not
342 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
352 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
353 // are Legal, f80 is custom lowered.
354 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
355 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
357 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
360 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
362 if (X86ScalarSSEf32) {
363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
364 // f32 and f64 cases are Legal, f80 case is not
365 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
371 // Handle FP_TO_UINT by promoting the destination to a larger signed
373 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
377 if (Subtarget->is64Bit()) {
378 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
379 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
380 } else if (!TM.Options.UseSoftFloat) {
381 // Since AVX is a superset of SSE3, only check for SSE here.
382 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
383 // Expand FP_TO_UINT into a select.
384 // FIXME: We would like to use a Custom expander here eventually to do
385 // the optimal thing for SSE vs. the default expansion in the legalizer.
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
388 // With SSE3 we can use fisttpll to convert to a signed i64; without
389 // SSE, we're stuck with a fistpll.
390 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
393 if (isTargetFTOL()) {
394 // Use the _ftol2 runtime function, which has a pseudo-instruction
395 // to handle its weird calling convention.
396 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
399 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
400 if (!X86ScalarSSEf64) {
401 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
402 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
403 if (Subtarget->is64Bit()) {
404 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
405 // Without SSE, i64->f64 goes through memory.
406 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
410 // Scalar integer divide and remainder are lowered to use operations that
411 // produce two results, to match the available instructions. This exposes
412 // the two-result form to trivial CSE, which is able to combine x/y and x%y
413 // into a single instruction.
415 // Scalar integer multiply-high is also lowered to use two-result
416 // operations, to match the available instructions. However, plain multiply
417 // (low) operations are left as Legal, as there are single-result
418 // instructions for this in x86. Using the two-result multiply instructions
419 // when both high and low results are needed must be arranged by dagcombine.
420 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422 setOperationAction(ISD::MULHS, VT, Expand);
423 setOperationAction(ISD::MULHU, VT, Expand);
424 setOperationAction(ISD::SDIV, VT, Expand);
425 setOperationAction(ISD::UDIV, VT, Expand);
426 setOperationAction(ISD::SREM, VT, Expand);
427 setOperationAction(ISD::UREM, VT, Expand);
429 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
430 setOperationAction(ISD::ADDC, VT, Custom);
431 setOperationAction(ISD::ADDE, VT, Custom);
432 setOperationAction(ISD::SUBC, VT, Custom);
433 setOperationAction(ISD::SUBE, VT, Custom);
436 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
437 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
438 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
445 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
446 if (Subtarget->is64Bit())
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
450 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
451 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
452 setOperationAction(ISD::FREM , MVT::f32 , Expand);
453 setOperationAction(ISD::FREM , MVT::f64 , Expand);
454 setOperationAction(ISD::FREM , MVT::f80 , Expand);
455 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
457 // Promote the i8 variants and force them on up to i32 which has a shorter
459 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
462 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
463 if (Subtarget->hasBMI()) {
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
466 if (Subtarget->is64Bit())
467 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
469 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
470 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
471 if (Subtarget->is64Bit())
472 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
475 if (Subtarget->hasLZCNT()) {
476 // When promoting the i8 variants, force them to i32 for a shorter
478 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
482 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
484 if (Subtarget->is64Bit())
485 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
487 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
488 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
492 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
493 if (Subtarget->is64Bit()) {
494 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
495 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
499 if (Subtarget->hasPOPCNT()) {
500 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
502 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
503 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
504 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
505 if (Subtarget->is64Bit())
506 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
509 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
511 if (!Subtarget->hasMOVBE())
512 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
514 // These should be promoted to a larger select which is supported.
515 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
516 // X86 wants to expand cmov itself.
517 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
518 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
519 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
529 if (Subtarget->is64Bit()) {
530 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
531 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
533 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
534 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
535 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
536 // support continuation, user-level threading, and etc.. As a result, no
537 // other SjLj exception interfaces are implemented and please don't build
538 // your own exception handling based on them.
539 // LLVM/Clang supports zero-cost DWARF exception handling.
540 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
541 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
544 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
545 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
546 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
548 if (Subtarget->is64Bit())
549 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
550 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
551 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
552 if (Subtarget->is64Bit()) {
553 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
554 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
555 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
556 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
557 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
559 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
560 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
561 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
562 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
563 if (Subtarget->is64Bit()) {
564 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
565 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
566 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
569 if (Subtarget->hasSSE1())
570 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
572 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
574 // Expand certain atomics
575 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
577 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
578 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
579 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
582 if (!Subtarget->is64Bit()) {
583 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
597 if (Subtarget->hasCmpxchg16b()) {
598 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
601 // FIXME - use subtarget debug flags
602 if (!Subtarget->isTargetDarwin() &&
603 !Subtarget->isTargetELF() &&
604 !Subtarget->isTargetCygMing()) {
605 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
608 if (Subtarget->is64Bit()) {
609 setExceptionPointerRegister(X86::RAX);
610 setExceptionSelectorRegister(X86::RDX);
612 setExceptionPointerRegister(X86::EAX);
613 setExceptionSelectorRegister(X86::EDX);
615 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
616 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
618 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
621 setOperationAction(ISD::TRAP, MVT::Other, Legal);
622 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
624 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
625 setOperationAction(ISD::VASTART , MVT::Other, Custom);
626 setOperationAction(ISD::VAEND , MVT::Other, Expand);
627 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
628 // TargetInfo::X86_64ABIBuiltinVaList
629 setOperationAction(ISD::VAARG , MVT::Other, Custom);
630 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
632 // TargetInfo::CharPtrBuiltinVaList
633 setOperationAction(ISD::VAARG , MVT::Other, Expand);
634 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
637 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
638 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
640 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
641 MVT::i64 : MVT::i32, Custom);
643 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
644 // f32 and f64 use SSE.
645 // Set up the FP register classes.
646 addRegisterClass(MVT::f32, &X86::FR32RegClass);
647 addRegisterClass(MVT::f64, &X86::FR64RegClass);
649 // Use ANDPD to simulate FABS.
650 setOperationAction(ISD::FABS , MVT::f64, Custom);
651 setOperationAction(ISD::FABS , MVT::f32, Custom);
653 // Use XORP to simulate FNEG.
654 setOperationAction(ISD::FNEG , MVT::f64, Custom);
655 setOperationAction(ISD::FNEG , MVT::f32, Custom);
657 // Use ANDPD and ORPD to simulate FCOPYSIGN.
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661 // Lower this to FGETSIGNx86 plus an AND.
662 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
663 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665 // We don't support sin/cos/fmod
666 setOperationAction(ISD::FSIN , MVT::f64, Expand);
667 setOperationAction(ISD::FCOS , MVT::f64, Expand);
668 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
669 setOperationAction(ISD::FSIN , MVT::f32, Expand);
670 setOperationAction(ISD::FCOS , MVT::f32, Expand);
671 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673 // Expand FP immediates into loads from the stack, except for the special
675 addLegalFPImmediate(APFloat(+0.0)); // xorpd
676 addLegalFPImmediate(APFloat(+0.0f)); // xorps
677 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
678 // Use SSE for f32, x87 for f64.
679 // Set up the FP register classes.
680 addRegisterClass(MVT::f32, &X86::FR32RegClass);
681 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683 // Use ANDPS to simulate FABS.
684 setOperationAction(ISD::FABS , MVT::f32, Custom);
686 // Use XORP to simulate FNEG.
687 setOperationAction(ISD::FNEG , MVT::f32, Custom);
689 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
691 // Use ANDPS and ORPS to simulate FCOPYSIGN.
692 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
693 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695 // We don't support sin/cos/fmod
696 setOperationAction(ISD::FSIN , MVT::f32, Expand);
697 setOperationAction(ISD::FCOS , MVT::f32, Expand);
698 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700 // Special cases we handle for FP constants.
701 addLegalFPImmediate(APFloat(+0.0f)); // xorps
702 addLegalFPImmediate(APFloat(+0.0)); // FLD0
703 addLegalFPImmediate(APFloat(+1.0)); // FLD1
704 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
705 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707 if (!TM.Options.UnsafeFPMath) {
708 setOperationAction(ISD::FSIN , MVT::f64, Expand);
709 setOperationAction(ISD::FCOS , MVT::f64, Expand);
710 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712 } else if (!TM.Options.UseSoftFloat) {
713 // f32 and f64 in x87.
714 // Set up the FP register classes.
715 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
716 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
719 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
720 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
721 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723 if (!TM.Options.UnsafeFPMath) {
724 setOperationAction(ISD::FSIN , MVT::f64, Expand);
725 setOperationAction(ISD::FSIN , MVT::f32, Expand);
726 setOperationAction(ISD::FCOS , MVT::f64, Expand);
727 setOperationAction(ISD::FCOS , MVT::f32, Expand);
728 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
729 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731 addLegalFPImmediate(APFloat(+0.0)); // FLD0
732 addLegalFPImmediate(APFloat(+1.0)); // FLD1
733 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
734 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
735 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
736 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
737 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
738 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
741 // We don't support FMA.
742 setOperationAction(ISD::FMA, MVT::f64, Expand);
743 setOperationAction(ISD::FMA, MVT::f32, Expand);
745 // Long double always uses X87.
746 if (!TM.Options.UseSoftFloat) {
747 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
748 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
749 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
752 addLegalFPImmediate(TmpFlt); // FLD0
754 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
757 APFloat TmpFlt2(+1.0);
758 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760 addLegalFPImmediate(TmpFlt2); // FLD1
761 TmpFlt2.changeSign();
762 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
765 if (!TM.Options.UnsafeFPMath) {
766 setOperationAction(ISD::FSIN , MVT::f80, Expand);
767 setOperationAction(ISD::FCOS , MVT::f80, Expand);
768 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
771 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
772 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
773 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
774 setOperationAction(ISD::FRINT, MVT::f80, Expand);
775 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
776 setOperationAction(ISD::FMA, MVT::f80, Expand);
779 // Always use a library call for pow.
780 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
781 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
782 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
784 setOperationAction(ISD::FLOG, MVT::f80, Expand);
785 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
786 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
787 setOperationAction(ISD::FEXP, MVT::f80, Expand);
788 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790 // First set operation action for all vector types to either promote
791 // (for widening) or expand (for scalarization). Then we will selectively
792 // turn on ones that can be effectively codegen'd.
793 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
794 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
795 MVT VT = (MVT::SimpleValueType)i;
796 setOperationAction(ISD::ADD , VT, Expand);
797 setOperationAction(ISD::SUB , VT, Expand);
798 setOperationAction(ISD::FADD, VT, Expand);
799 setOperationAction(ISD::FNEG, VT, Expand);
800 setOperationAction(ISD::FSUB, VT, Expand);
801 setOperationAction(ISD::MUL , VT, Expand);
802 setOperationAction(ISD::FMUL, VT, Expand);
803 setOperationAction(ISD::SDIV, VT, Expand);
804 setOperationAction(ISD::UDIV, VT, Expand);
805 setOperationAction(ISD::FDIV, VT, Expand);
806 setOperationAction(ISD::SREM, VT, Expand);
807 setOperationAction(ISD::UREM, VT, Expand);
808 setOperationAction(ISD::LOAD, VT, Expand);
809 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
811 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
812 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
813 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
814 setOperationAction(ISD::FABS, VT, Expand);
815 setOperationAction(ISD::FSIN, VT, Expand);
816 setOperationAction(ISD::FSINCOS, VT, Expand);
817 setOperationAction(ISD::FCOS, VT, Expand);
818 setOperationAction(ISD::FSINCOS, VT, Expand);
819 setOperationAction(ISD::FREM, VT, Expand);
820 setOperationAction(ISD::FMA, VT, Expand);
821 setOperationAction(ISD::FPOWI, VT, Expand);
822 setOperationAction(ISD::FSQRT, VT, Expand);
823 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
824 setOperationAction(ISD::FFLOOR, VT, Expand);
825 setOperationAction(ISD::FCEIL, VT, Expand);
826 setOperationAction(ISD::FTRUNC, VT, Expand);
827 setOperationAction(ISD::FRINT, VT, Expand);
828 setOperationAction(ISD::FNEARBYINT, VT, Expand);
829 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
830 setOperationAction(ISD::MULHS, VT, Expand);
831 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832 setOperationAction(ISD::MULHU, VT, Expand);
833 setOperationAction(ISD::SDIVREM, VT, Expand);
834 setOperationAction(ISD::UDIVREM, VT, Expand);
835 setOperationAction(ISD::FPOW, VT, Expand);
836 setOperationAction(ISD::CTPOP, VT, Expand);
837 setOperationAction(ISD::CTTZ, VT, Expand);
838 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
839 setOperationAction(ISD::CTLZ, VT, Expand);
840 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
841 setOperationAction(ISD::SHL, VT, Expand);
842 setOperationAction(ISD::SRA, VT, Expand);
843 setOperationAction(ISD::SRL, VT, Expand);
844 setOperationAction(ISD::ROTL, VT, Expand);
845 setOperationAction(ISD::ROTR, VT, Expand);
846 setOperationAction(ISD::BSWAP, VT, Expand);
847 setOperationAction(ISD::SETCC, VT, Expand);
848 setOperationAction(ISD::FLOG, VT, Expand);
849 setOperationAction(ISD::FLOG2, VT, Expand);
850 setOperationAction(ISD::FLOG10, VT, Expand);
851 setOperationAction(ISD::FEXP, VT, Expand);
852 setOperationAction(ISD::FEXP2, VT, Expand);
853 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
854 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
855 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
857 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
858 setOperationAction(ISD::TRUNCATE, VT, Expand);
859 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
860 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
861 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
862 setOperationAction(ISD::VSELECT, VT, Expand);
863 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
864 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
865 setTruncStoreAction(VT,
866 (MVT::SimpleValueType)InnerVT, Expand);
867 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
869 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
872 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
873 // with -msoft-float, disable use of MMX as well.
874 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
875 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
876 // No operations on x86mmx supported, everything uses intrinsics.
879 // MMX-sized vectors (other than x86mmx) are expected to be expanded
880 // into smaller operations.
881 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
882 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
883 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
884 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
885 setOperationAction(ISD::AND, MVT::v8i8, Expand);
886 setOperationAction(ISD::AND, MVT::v4i16, Expand);
887 setOperationAction(ISD::AND, MVT::v2i32, Expand);
888 setOperationAction(ISD::AND, MVT::v1i64, Expand);
889 setOperationAction(ISD::OR, MVT::v8i8, Expand);
890 setOperationAction(ISD::OR, MVT::v4i16, Expand);
891 setOperationAction(ISD::OR, MVT::v2i32, Expand);
892 setOperationAction(ISD::OR, MVT::v1i64, Expand);
893 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
894 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
895 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
896 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
901 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
902 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
903 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
904 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
905 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
911 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
912 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
915 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
916 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
917 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
918 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
919 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
920 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
921 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
922 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
923 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
924 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
925 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
928 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
929 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
932 // registers cannot be used even for integer operations.
933 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
934 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
935 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
936 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
939 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
940 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
941 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
942 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
943 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
944 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
945 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
946 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
947 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
948 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
949 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
950 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
951 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
952 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
953 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
954 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
955 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
956 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
957 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
958 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
959 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
961 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
962 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
963 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
964 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
966 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
967 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
970 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
972 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
973 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
974 MVT VT = (MVT::SimpleValueType)i;
975 // Do not attempt to custom lower non-power-of-2 vectors
976 if (!isPowerOf2_32(VT.getVectorNumElements()))
978 // Do not attempt to custom lower non-128-bit vectors
979 if (!VT.is128BitVector())
981 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
982 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
983 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
986 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
987 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
990 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
993 if (Subtarget->is64Bit()) {
994 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
998 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
999 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1000 MVT VT = (MVT::SimpleValueType)i;
1002 // Do not attempt to promote non-128-bit vectors
1003 if (!VT.is128BitVector())
1006 setOperationAction(ISD::AND, VT, Promote);
1007 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1008 setOperationAction(ISD::OR, VT, Promote);
1009 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1010 setOperationAction(ISD::XOR, VT, Promote);
1011 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1012 setOperationAction(ISD::LOAD, VT, Promote);
1013 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1014 setOperationAction(ISD::SELECT, VT, Promote);
1015 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1018 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1020 // Custom lower v2i64 and v2f64 selects.
1021 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1022 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1023 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1024 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1026 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1027 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1031 // As there is no 64-bit GPR available, we need build a special custom
1032 // sequence to convert from v2i32 to v2f32.
1033 if (!Subtarget->is64Bit())
1034 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1036 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1037 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1039 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1042 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1043 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1044 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1045 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1046 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1047 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1048 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1049 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1050 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1051 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1052 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1054 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1065 // FIXME: Do we need to handle scalar-to-vector here?
1066 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1074 // i8 and i16 vectors are custom , because the source register and source
1075 // source memory operand types are not the same width. f32 vectors are
1076 // custom since the immediate controlling the insert encodes additional
1078 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1080 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1081 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1086 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1088 // FIXME: these should be Legal but thats only for the case where
1089 // the index is constant. For now custom expand to deal with that.
1090 if (Subtarget->is64Bit()) {
1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1092 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1096 if (Subtarget->hasSSE2()) {
1097 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1098 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1100 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1101 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1103 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1104 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1106 // In the customized shift lowering, the legal cases in AVX2 will be
1108 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1109 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1111 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1112 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1114 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1117 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1118 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1125 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1126 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1127 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1129 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1140 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1142 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1153 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1155 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1156 // even though v8i16 is a legal type.
1157 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1158 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1159 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1161 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1162 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1163 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1166 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1168 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1170 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1171 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1173 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1174 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1176 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1186 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1188 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1191 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1198 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1200 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1201 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1203 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1204 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1206 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1207 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1208 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1209 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1210 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1211 setOperationAction(ISD::FMA, MVT::f32, Legal);
1212 setOperationAction(ISD::FMA, MVT::f64, Legal);
1215 if (Subtarget->hasInt256()) {
1216 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1217 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1218 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1219 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1221 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1222 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1223 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1224 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1226 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1227 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1228 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1229 // Don't lower v32i8 because there is no 128-bit byte mul
1231 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1232 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1233 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1234 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1236 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1238 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1239 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1240 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1241 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1243 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1244 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1245 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1246 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1248 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1249 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1250 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1251 // Don't lower v32i8 because there is no 128-bit byte mul
1254 // In the customized shift lowering, the legal cases in AVX2 will be
1256 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1257 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1259 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1260 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1262 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1264 // Custom lower several nodes for 256-bit types.
1265 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1266 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1267 MVT VT = (MVT::SimpleValueType)i;
1269 // Extract subvector is special because the value type
1270 // (result) is 128-bit but the source is 256-bit wide.
1271 if (VT.is128BitVector())
1272 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1274 // Do not attempt to custom lower other non-256-bit vectors
1275 if (!VT.is256BitVector())
1278 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1279 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1280 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1281 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1282 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1283 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1284 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1287 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1288 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1289 MVT VT = (MVT::SimpleValueType)i;
1291 // Do not attempt to promote non-256-bit vectors
1292 if (!VT.is256BitVector())
1295 setOperationAction(ISD::AND, VT, Promote);
1296 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1297 setOperationAction(ISD::OR, VT, Promote);
1298 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1299 setOperationAction(ISD::XOR, VT, Promote);
1300 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1301 setOperationAction(ISD::LOAD, VT, Promote);
1302 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1303 setOperationAction(ISD::SELECT, VT, Promote);
1304 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1308 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1309 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1310 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1314 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1315 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1316 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1318 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1319 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1320 setOperationAction(ISD::XOR, MVT::i1, Legal);
1321 setOperationAction(ISD::OR, MVT::i1, Legal);
1322 setOperationAction(ISD::AND, MVT::i1, Legal);
1323 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1324 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1328 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1330 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1331 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1337 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1343 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1344 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1347 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1348 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1349 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1350 if (Subtarget->is64Bit()) {
1351 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1353 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1354 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1356 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1357 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1358 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1359 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1360 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1361 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1364 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1365 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1367 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1373 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1374 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1388 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1389 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1391 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1397 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1398 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1399 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1400 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1401 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1403 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1404 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1406 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1407 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1409 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1411 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1412 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1414 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1415 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1417 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1418 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1420 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1421 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1422 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1423 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1424 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1425 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1427 // Custom lower several nodes.
1428 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1429 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1430 MVT VT = (MVT::SimpleValueType)i;
1432 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1433 // Extract subvector is special because the value type
1434 // (result) is 256/128-bit but the source is 512-bit wide.
1435 if (VT.is128BitVector() || VT.is256BitVector())
1436 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1438 if (VT.getVectorElementType() == MVT::i1)
1439 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1441 // Do not attempt to custom lower other non-512-bit vectors
1442 if (!VT.is512BitVector())
1445 if ( EltSize >= 32) {
1446 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1447 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1448 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1449 setOperationAction(ISD::VSELECT, VT, Legal);
1450 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1451 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1452 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1455 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1456 MVT VT = (MVT::SimpleValueType)i;
1458 // Do not attempt to promote non-256-bit vectors
1459 if (!VT.is512BitVector())
1462 setOperationAction(ISD::SELECT, VT, Promote);
1463 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1467 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1468 // of this type with custom code.
1469 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1470 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1471 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1475 // We want to custom lower some of our intrinsics.
1476 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1477 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1478 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1479 if (!Subtarget->is64Bit())
1480 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1482 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1483 // handle type legalization for these operations here.
1485 // FIXME: We really should do custom legalization for addition and
1486 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1487 // than generic legalization for 64-bit multiplication-with-overflow, though.
1488 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1489 // Add/Sub/Mul with overflow operations are custom lowered.
1491 setOperationAction(ISD::SADDO, VT, Custom);
1492 setOperationAction(ISD::UADDO, VT, Custom);
1493 setOperationAction(ISD::SSUBO, VT, Custom);
1494 setOperationAction(ISD::USUBO, VT, Custom);
1495 setOperationAction(ISD::SMULO, VT, Custom);
1496 setOperationAction(ISD::UMULO, VT, Custom);
1499 // There are no 8-bit 3-address imul/mul instructions
1500 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1501 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1503 if (!Subtarget->is64Bit()) {
1504 // These libcalls are not available in 32-bit.
1505 setLibcallName(RTLIB::SHL_I128, nullptr);
1506 setLibcallName(RTLIB::SRL_I128, nullptr);
1507 setLibcallName(RTLIB::SRA_I128, nullptr);
1510 // Combine sin / cos into one node or libcall if possible.
1511 if (Subtarget->hasSinCos()) {
1512 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1513 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1514 if (Subtarget->isTargetDarwin()) {
1515 // For MacOSX, we don't want to the normal expansion of a libcall to
1516 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1518 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1519 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1523 // We have target-specific dag combine patterns for the following nodes:
1524 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1525 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1526 setTargetDAGCombine(ISD::VSELECT);
1527 setTargetDAGCombine(ISD::SELECT);
1528 setTargetDAGCombine(ISD::SHL);
1529 setTargetDAGCombine(ISD::SRA);
1530 setTargetDAGCombine(ISD::SRL);
1531 setTargetDAGCombine(ISD::OR);
1532 setTargetDAGCombine(ISD::AND);
1533 setTargetDAGCombine(ISD::ADD);
1534 setTargetDAGCombine(ISD::FADD);
1535 setTargetDAGCombine(ISD::FSUB);
1536 setTargetDAGCombine(ISD::FMA);
1537 setTargetDAGCombine(ISD::SUB);
1538 setTargetDAGCombine(ISD::LOAD);
1539 setTargetDAGCombine(ISD::STORE);
1540 setTargetDAGCombine(ISD::ZERO_EXTEND);
1541 setTargetDAGCombine(ISD::ANY_EXTEND);
1542 setTargetDAGCombine(ISD::SIGN_EXTEND);
1543 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1544 setTargetDAGCombine(ISD::TRUNCATE);
1545 setTargetDAGCombine(ISD::SINT_TO_FP);
1546 setTargetDAGCombine(ISD::SETCC);
1547 if (Subtarget->is64Bit())
1548 setTargetDAGCombine(ISD::MUL);
1549 setTargetDAGCombine(ISD::XOR);
1551 computeRegisterProperties();
1553 // On Darwin, -Os means optimize for size without hurting performance,
1554 // do not reduce the limit.
1555 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1556 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1557 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1558 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1559 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1560 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1561 setPrefLoopAlignment(4); // 2^4 bytes.
1563 // Predictable cmov don't hurt on atom because it's in-order.
1564 PredictableSelectIsExpensive = !Subtarget->isAtom();
1566 setPrefFunctionAlignment(4); // 2^4 bytes.
1569 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1571 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1573 if (Subtarget->hasAVX512())
1574 switch(VT.getVectorNumElements()) {
1575 case 8: return MVT::v8i1;
1576 case 16: return MVT::v16i1;
1579 return VT.changeVectorElementTypeToInteger();
1582 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1583 /// the desired ByVal argument alignment.
1584 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1587 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1588 if (VTy->getBitWidth() == 128)
1590 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1591 unsigned EltAlign = 0;
1592 getMaxByValAlign(ATy->getElementType(), EltAlign);
1593 if (EltAlign > MaxAlign)
1594 MaxAlign = EltAlign;
1595 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1596 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1597 unsigned EltAlign = 0;
1598 getMaxByValAlign(STy->getElementType(i), EltAlign);
1599 if (EltAlign > MaxAlign)
1600 MaxAlign = EltAlign;
1607 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1608 /// function arguments in the caller parameter area. For X86, aggregates
1609 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1610 /// are at 4-byte boundaries.
1611 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1612 if (Subtarget->is64Bit()) {
1613 // Max of 8 and alignment of type.
1614 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1621 if (Subtarget->hasSSE1())
1622 getMaxByValAlign(Ty, Align);
1626 /// getOptimalMemOpType - Returns the target specific optimal type for load
1627 /// and store operations as a result of memset, memcpy, and memmove
1628 /// lowering. If DstAlign is zero that means it's safe to destination
1629 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1630 /// means there isn't a need to check it against alignment requirement,
1631 /// probably because the source does not need to be loaded. If 'IsMemset' is
1632 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1633 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1634 /// source is constant so it does not need to be loaded.
1635 /// It returns EVT::Other if the type should be determined using generic
1636 /// target-independent logic.
1638 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1639 unsigned DstAlign, unsigned SrcAlign,
1640 bool IsMemset, bool ZeroMemset,
1642 MachineFunction &MF) const {
1643 const Function *F = MF.getFunction();
1644 if ((!IsMemset || ZeroMemset) &&
1645 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1646 Attribute::NoImplicitFloat)) {
1648 (Subtarget->isUnalignedMemAccessFast() ||
1649 ((DstAlign == 0 || DstAlign >= 16) &&
1650 (SrcAlign == 0 || SrcAlign >= 16)))) {
1652 if (Subtarget->hasInt256())
1654 if (Subtarget->hasFp256())
1657 if (Subtarget->hasSSE2())
1659 if (Subtarget->hasSSE1())
1661 } else if (!MemcpyStrSrc && Size >= 8 &&
1662 !Subtarget->is64Bit() &&
1663 Subtarget->hasSSE2()) {
1664 // Do not use f64 to lower memcpy if source is string constant. It's
1665 // better to use i32 to avoid the loads.
1669 if (Subtarget->is64Bit() && Size >= 8)
1674 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1676 return X86ScalarSSEf32;
1677 else if (VT == MVT::f64)
1678 return X86ScalarSSEf64;
1683 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1687 *Fast = Subtarget->isUnalignedMemAccessFast();
1691 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1692 /// current function. The returned value is a member of the
1693 /// MachineJumpTableInfo::JTEntryKind enum.
1694 unsigned X86TargetLowering::getJumpTableEncoding() const {
1695 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1697 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1698 Subtarget->isPICStyleGOT())
1699 return MachineJumpTableInfo::EK_Custom32;
1701 // Otherwise, use the normal jump table encoding heuristics.
1702 return TargetLowering::getJumpTableEncoding();
1706 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1707 const MachineBasicBlock *MBB,
1708 unsigned uid,MCContext &Ctx) const{
1709 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1710 Subtarget->isPICStyleGOT());
1711 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1713 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1714 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1717 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1719 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1720 SelectionDAG &DAG) const {
1721 if (!Subtarget->is64Bit())
1722 // This doesn't have SDLoc associated with it, but is not really the
1723 // same as a Register.
1724 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1728 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1729 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1731 const MCExpr *X86TargetLowering::
1732 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1733 MCContext &Ctx) const {
1734 // X86-64 uses RIP relative addressing based on the jump table label.
1735 if (Subtarget->isPICStyleRIPRel())
1736 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1738 // Otherwise, the reference is relative to the PIC base.
1739 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1742 // FIXME: Why this routine is here? Move to RegInfo!
1743 std::pair<const TargetRegisterClass*, uint8_t>
1744 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1745 const TargetRegisterClass *RRC = nullptr;
1747 switch (VT.SimpleTy) {
1749 return TargetLowering::findRepresentativeClass(VT);
1750 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1751 RRC = Subtarget->is64Bit() ?
1752 (const TargetRegisterClass*)&X86::GR64RegClass :
1753 (const TargetRegisterClass*)&X86::GR32RegClass;
1756 RRC = &X86::VR64RegClass;
1758 case MVT::f32: case MVT::f64:
1759 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1760 case MVT::v4f32: case MVT::v2f64:
1761 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1763 RRC = &X86::VR128RegClass;
1766 return std::make_pair(RRC, Cost);
1769 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1770 unsigned &Offset) const {
1771 if (!Subtarget->isTargetLinux())
1774 if (Subtarget->is64Bit()) {
1775 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1777 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1789 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1790 unsigned DestAS) const {
1791 assert(SrcAS != DestAS && "Expected different address spaces!");
1793 return SrcAS < 256 && DestAS < 256;
1796 //===----------------------------------------------------------------------===//
1797 // Return Value Calling Convention Implementation
1798 //===----------------------------------------------------------------------===//
1800 #include "X86GenCallingConv.inc"
1803 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1804 MachineFunction &MF, bool isVarArg,
1805 const SmallVectorImpl<ISD::OutputArg> &Outs,
1806 LLVMContext &Context) const {
1807 SmallVector<CCValAssign, 16> RVLocs;
1808 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1810 return CCInfo.CheckReturn(Outs, RetCC_X86);
1813 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1814 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1819 X86TargetLowering::LowerReturn(SDValue Chain,
1820 CallingConv::ID CallConv, bool isVarArg,
1821 const SmallVectorImpl<ISD::OutputArg> &Outs,
1822 const SmallVectorImpl<SDValue> &OutVals,
1823 SDLoc dl, SelectionDAG &DAG) const {
1824 MachineFunction &MF = DAG.getMachineFunction();
1825 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1827 SmallVector<CCValAssign, 16> RVLocs;
1828 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1829 RVLocs, *DAG.getContext());
1830 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1833 SmallVector<SDValue, 6> RetOps;
1834 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1835 // Operand #1 = Bytes To Pop
1836 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1839 // Copy the result values into the output registers.
1840 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1841 CCValAssign &VA = RVLocs[i];
1842 assert(VA.isRegLoc() && "Can only return in registers!");
1843 SDValue ValToCopy = OutVals[i];
1844 EVT ValVT = ValToCopy.getValueType();
1846 // Promote values to the appropriate types
1847 if (VA.getLocInfo() == CCValAssign::SExt)
1848 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849 else if (VA.getLocInfo() == CCValAssign::ZExt)
1850 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1851 else if (VA.getLocInfo() == CCValAssign::AExt)
1852 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1853 else if (VA.getLocInfo() == CCValAssign::BCvt)
1854 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1856 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1857 "Unexpected FP-extend for return value.");
1859 // If this is x86-64, and we disabled SSE, we can't return FP values,
1860 // or SSE or MMX vectors.
1861 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1862 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1863 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1864 report_fatal_error("SSE register return with SSE disabled");
1866 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1867 // llvm-gcc has never done it right and no one has noticed, so this
1868 // should be OK for now.
1869 if (ValVT == MVT::f64 &&
1870 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1871 report_fatal_error("SSE2 register return with SSE2 disabled");
1873 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1874 // the RET instruction and handled by the FP Stackifier.
1875 if (VA.getLocReg() == X86::ST0 ||
1876 VA.getLocReg() == X86::ST1) {
1877 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1878 // change the value to the FP stack register class.
1879 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1880 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1881 RetOps.push_back(ValToCopy);
1882 // Don't emit a copytoreg.
1886 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1887 // which is returned in RAX / RDX.
1888 if (Subtarget->is64Bit()) {
1889 if (ValVT == MVT::x86mmx) {
1890 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1891 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1892 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1894 // If we don't have SSE2 available, convert to v4f32 so the generated
1895 // register is legal.
1896 if (!Subtarget->hasSSE2())
1897 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1902 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1903 Flag = Chain.getValue(1);
1904 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1907 // The x86-64 ABIs require that for returning structs by value we copy
1908 // the sret argument into %rax/%eax (depending on ABI) for the return.
1909 // Win32 requires us to put the sret argument to %eax as well.
1910 // We saved the argument into a virtual register in the entry block,
1911 // so now we copy the value out and into %rax/%eax.
1912 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1913 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1914 MachineFunction &MF = DAG.getMachineFunction();
1915 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1916 unsigned Reg = FuncInfo->getSRetReturnReg();
1918 "SRetReturnReg should have been set in LowerFormalArguments().");
1919 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1922 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1923 X86::RAX : X86::EAX;
1924 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1925 Flag = Chain.getValue(1);
1927 // RAX/EAX now acts like a return value.
1928 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1931 RetOps[0] = Chain; // Update chain.
1933 // Add the flag if we have it.
1935 RetOps.push_back(Flag);
1937 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1940 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1941 if (N->getNumValues() != 1)
1943 if (!N->hasNUsesOfValue(1, 0))
1946 SDValue TCChain = Chain;
1947 SDNode *Copy = *N->use_begin();
1948 if (Copy->getOpcode() == ISD::CopyToReg) {
1949 // If the copy has a glue operand, we conservatively assume it isn't safe to
1950 // perform a tail call.
1951 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1953 TCChain = Copy->getOperand(0);
1954 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1957 bool HasRet = false;
1958 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1960 if (UI->getOpcode() != X86ISD::RET_FLAG)
1973 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1974 ISD::NodeType ExtendKind) const {
1976 // TODO: Is this also valid on 32-bit?
1977 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1978 ReturnMVT = MVT::i8;
1980 ReturnMVT = MVT::i32;
1982 MVT MinVT = getRegisterType(ReturnMVT);
1983 return VT.bitsLT(MinVT) ? MinVT : VT;
1986 /// LowerCallResult - Lower the result values of a call into the
1987 /// appropriate copies out of appropriate physical registers.
1990 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1991 CallingConv::ID CallConv, bool isVarArg,
1992 const SmallVectorImpl<ISD::InputArg> &Ins,
1993 SDLoc dl, SelectionDAG &DAG,
1994 SmallVectorImpl<SDValue> &InVals) const {
1996 // Assign locations to each value returned by this call.
1997 SmallVector<CCValAssign, 16> RVLocs;
1998 bool Is64Bit = Subtarget->is64Bit();
1999 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2000 getTargetMachine(), RVLocs, *DAG.getContext());
2001 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2003 // Copy all of the result registers out of their specified physreg.
2004 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2005 CCValAssign &VA = RVLocs[i];
2006 EVT CopyVT = VA.getValVT();
2008 // If this is x86-64, and we disabled SSE, we can't return FP values
2009 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2010 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2011 report_fatal_error("SSE register return with SSE disabled");
2016 // If this is a call to a function that returns an fp value on the floating
2017 // point stack, we must guarantee the value is popped from the stack, so
2018 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2019 // if the return value is not used. We use the FpPOP_RETVAL instruction
2021 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2022 // If we prefer to use the value in xmm registers, copy it out as f80 and
2023 // use a truncate to move it from fp stack reg to xmm reg.
2024 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2025 SDValue Ops[] = { Chain, InFlag };
2026 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2027 MVT::Other, MVT::Glue, Ops), 1);
2028 Val = Chain.getValue(0);
2030 // Round the f80 to the right size, which also moves it to the appropriate
2032 if (CopyVT != VA.getValVT())
2033 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2034 // This truncation won't change the value.
2035 DAG.getIntPtrConstant(1));
2037 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2038 CopyVT, InFlag).getValue(1);
2039 Val = Chain.getValue(0);
2041 InFlag = Chain.getValue(2);
2042 InVals.push_back(Val);
2048 //===----------------------------------------------------------------------===//
2049 // C & StdCall & Fast Calling Convention implementation
2050 //===----------------------------------------------------------------------===//
2051 // StdCall calling convention seems to be standard for many Windows' API
2052 // routines and around. It differs from C calling convention just a little:
2053 // callee should clean up the stack, not caller. Symbols should be also
2054 // decorated in some fancy way :) It doesn't support any vector arguments.
2055 // For info on fast calling convention see Fast Calling Convention (tail call)
2056 // implementation LowerX86_32FastCCCallTo.
2058 /// CallIsStructReturn - Determines whether a call uses struct return
2060 enum StructReturnType {
2065 static StructReturnType
2066 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2068 return NotStructReturn;
2070 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2071 if (!Flags.isSRet())
2072 return NotStructReturn;
2073 if (Flags.isInReg())
2074 return RegStructReturn;
2075 return StackStructReturn;
2078 /// ArgsAreStructReturn - Determines whether a function uses struct
2079 /// return semantics.
2080 static StructReturnType
2081 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2083 return NotStructReturn;
2085 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2086 if (!Flags.isSRet())
2087 return NotStructReturn;
2088 if (Flags.isInReg())
2089 return RegStructReturn;
2090 return StackStructReturn;
2093 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2094 /// by "Src" to address "Dst" with size and alignment information specified by
2095 /// the specific parameter attribute. The copy will be passed as a byval
2096 /// function parameter.
2098 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2099 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2101 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2103 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2104 /*isVolatile*/false, /*AlwaysInline=*/true,
2105 MachinePointerInfo(), MachinePointerInfo());
2108 /// IsTailCallConvention - Return true if the calling convention is one that
2109 /// supports tail call optimization.
2110 static bool IsTailCallConvention(CallingConv::ID CC) {
2111 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2112 CC == CallingConv::HiPE);
2115 /// \brief Return true if the calling convention is a C calling convention.
2116 static bool IsCCallConvention(CallingConv::ID CC) {
2117 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2118 CC == CallingConv::X86_64_SysV);
2121 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2122 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2126 CallingConv::ID CalleeCC = CS.getCallingConv();
2127 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2133 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2134 /// a tailcall target by changing its ABI.
2135 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2136 bool GuaranteedTailCallOpt) {
2137 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2141 X86TargetLowering::LowerMemArgument(SDValue Chain,
2142 CallingConv::ID CallConv,
2143 const SmallVectorImpl<ISD::InputArg> &Ins,
2144 SDLoc dl, SelectionDAG &DAG,
2145 const CCValAssign &VA,
2146 MachineFrameInfo *MFI,
2148 // Create the nodes corresponding to a load from this parameter slot.
2149 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2150 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2151 getTargetMachine().Options.GuaranteedTailCallOpt);
2152 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2155 // If value is passed by pointer we have address passed instead of the value
2157 if (VA.getLocInfo() == CCValAssign::Indirect)
2158 ValVT = VA.getLocVT();
2160 ValVT = VA.getValVT();
2162 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2163 // changed with more analysis.
2164 // In case of tail call optimization mark all arguments mutable. Since they
2165 // could be overwritten by lowering of arguments in case of a tail call.
2166 if (Flags.isByVal()) {
2167 unsigned Bytes = Flags.getByValSize();
2168 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2169 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2170 return DAG.getFrameIndex(FI, getPointerTy());
2172 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2173 VA.getLocMemOffset(), isImmutable);
2174 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2175 return DAG.getLoad(ValVT, dl, Chain, FIN,
2176 MachinePointerInfo::getFixedStack(FI),
2177 false, false, false, 0);
2182 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2183 CallingConv::ID CallConv,
2185 const SmallVectorImpl<ISD::InputArg> &Ins,
2188 SmallVectorImpl<SDValue> &InVals)
2190 MachineFunction &MF = DAG.getMachineFunction();
2191 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2193 const Function* Fn = MF.getFunction();
2194 if (Fn->hasExternalLinkage() &&
2195 Subtarget->isTargetCygMing() &&
2196 Fn->getName() == "main")
2197 FuncInfo->setForceFramePointer(true);
2199 MachineFrameInfo *MFI = MF.getFrameInfo();
2200 bool Is64Bit = Subtarget->is64Bit();
2201 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2203 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2204 "Var args not supported with calling convention fastcc, ghc or hipe");
2206 // Assign locations to all of the incoming arguments.
2207 SmallVector<CCValAssign, 16> ArgLocs;
2208 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2209 ArgLocs, *DAG.getContext());
2211 // Allocate shadow area for Win64
2213 CCInfo.AllocateStack(32, 8);
2215 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2217 unsigned LastVal = ~0U;
2219 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2220 CCValAssign &VA = ArgLocs[i];
2221 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2223 assert(VA.getValNo() != LastVal &&
2224 "Don't support value assigned to multiple locs yet");
2226 LastVal = VA.getValNo();
2228 if (VA.isRegLoc()) {
2229 EVT RegVT = VA.getLocVT();
2230 const TargetRegisterClass *RC;
2231 if (RegVT == MVT::i32)
2232 RC = &X86::GR32RegClass;
2233 else if (Is64Bit && RegVT == MVT::i64)
2234 RC = &X86::GR64RegClass;
2235 else if (RegVT == MVT::f32)
2236 RC = &X86::FR32RegClass;
2237 else if (RegVT == MVT::f64)
2238 RC = &X86::FR64RegClass;
2239 else if (RegVT.is512BitVector())
2240 RC = &X86::VR512RegClass;
2241 else if (RegVT.is256BitVector())
2242 RC = &X86::VR256RegClass;
2243 else if (RegVT.is128BitVector())
2244 RC = &X86::VR128RegClass;
2245 else if (RegVT == MVT::x86mmx)
2246 RC = &X86::VR64RegClass;
2247 else if (RegVT == MVT::i1)
2248 RC = &X86::VK1RegClass;
2249 else if (RegVT == MVT::v8i1)
2250 RC = &X86::VK8RegClass;
2251 else if (RegVT == MVT::v16i1)
2252 RC = &X86::VK16RegClass;
2254 llvm_unreachable("Unknown argument type!");
2256 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2257 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2259 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2260 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2262 if (VA.getLocInfo() == CCValAssign::SExt)
2263 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2264 DAG.getValueType(VA.getValVT()));
2265 else if (VA.getLocInfo() == CCValAssign::ZExt)
2266 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2267 DAG.getValueType(VA.getValVT()));
2268 else if (VA.getLocInfo() == CCValAssign::BCvt)
2269 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2271 if (VA.isExtInLoc()) {
2272 // Handle MMX values passed in XMM regs.
2273 if (RegVT.isVector())
2274 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2276 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2279 assert(VA.isMemLoc());
2280 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2283 // If value is passed via pointer - do a load.
2284 if (VA.getLocInfo() == CCValAssign::Indirect)
2285 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2286 MachinePointerInfo(), false, false, false, 0);
2288 InVals.push_back(ArgValue);
2291 // The x86-64 ABIs require that for returning structs by value we copy
2292 // the sret argument into %rax/%eax (depending on ABI) for the return.
2293 // Win32 requires us to put the sret argument to %eax as well.
2294 // Save the argument into a virtual register so that we can access it
2295 // from the return points.
2296 if (MF.getFunction()->hasStructRetAttr() &&
2297 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2298 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2299 unsigned Reg = FuncInfo->getSRetReturnReg();
2301 MVT PtrTy = getPointerTy();
2302 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2303 FuncInfo->setSRetReturnReg(Reg);
2305 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2306 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2309 unsigned StackSize = CCInfo.getNextStackOffset();
2310 // Align stack specially for tail calls.
2311 if (FuncIsMadeTailCallSafe(CallConv,
2312 MF.getTarget().Options.GuaranteedTailCallOpt))
2313 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2315 // If the function takes variable number of arguments, make a frame index for
2316 // the start of the first vararg value... for expansion of llvm.va_start.
2318 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2319 CallConv != CallingConv::X86_ThisCall)) {
2320 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2323 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2325 // FIXME: We should really autogenerate these arrays
2326 static const MCPhysReg GPR64ArgRegsWin64[] = {
2327 X86::RCX, X86::RDX, X86::R8, X86::R9
2329 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2330 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2332 static const MCPhysReg XMMArgRegs64Bit[] = {
2333 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2334 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2336 const MCPhysReg *GPR64ArgRegs;
2337 unsigned NumXMMRegs = 0;
2340 // The XMM registers which might contain var arg parameters are shadowed
2341 // in their paired GPR. So we only need to save the GPR to their home
2343 TotalNumIntRegs = 4;
2344 GPR64ArgRegs = GPR64ArgRegsWin64;
2346 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2347 GPR64ArgRegs = GPR64ArgRegs64Bit;
2349 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2352 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2355 bool NoImplicitFloatOps = Fn->getAttributes().
2356 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2357 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2358 "SSE register cannot be used when SSE is disabled!");
2359 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2360 NoImplicitFloatOps) &&
2361 "SSE register cannot be used when SSE is disabled!");
2362 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2363 !Subtarget->hasSSE1())
2364 // Kernel mode asks for SSE to be disabled, so don't push them
2366 TotalNumXMMRegs = 0;
2369 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2370 // Get to the caller-allocated home save location. Add 8 to account
2371 // for the return address.
2372 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2373 FuncInfo->setRegSaveFrameIndex(
2374 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2375 // Fixup to set vararg frame on shadow area (4 x i64).
2377 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2379 // For X86-64, if there are vararg parameters that are passed via
2380 // registers, then we must store them to their spots on the stack so
2381 // they may be loaded by deferencing the result of va_next.
2382 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2383 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2384 FuncInfo->setRegSaveFrameIndex(
2385 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2389 // Store the integer parameter registers.
2390 SmallVector<SDValue, 8> MemOps;
2391 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2393 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2394 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2395 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2396 DAG.getIntPtrConstant(Offset));
2397 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2398 &X86::GR64RegClass);
2399 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2401 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2402 MachinePointerInfo::getFixedStack(
2403 FuncInfo->getRegSaveFrameIndex(), Offset),
2405 MemOps.push_back(Store);
2409 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2410 // Now store the XMM (fp + vector) parameter registers.
2411 SmallVector<SDValue, 11> SaveXMMOps;
2412 SaveXMMOps.push_back(Chain);
2414 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2415 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2416 SaveXMMOps.push_back(ALVal);
2418 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2419 FuncInfo->getRegSaveFrameIndex()));
2420 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2421 FuncInfo->getVarArgsFPOffset()));
2423 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2424 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2425 &X86::VR128RegClass);
2426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2427 SaveXMMOps.push_back(Val);
2429 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2430 MVT::Other, SaveXMMOps));
2433 if (!MemOps.empty())
2434 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2438 // Some CCs need callee pop.
2439 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2440 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2441 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2443 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2444 // If this is an sret function, the return should pop the hidden pointer.
2445 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2446 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2447 argsAreStructReturn(Ins) == StackStructReturn)
2448 FuncInfo->setBytesToPopOnReturn(4);
2452 // RegSaveFrameIndex is X86-64 only.
2453 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2454 if (CallConv == CallingConv::X86_FastCall ||
2455 CallConv == CallingConv::X86_ThisCall)
2456 // fastcc functions can't have varargs.
2457 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2460 FuncInfo->setArgumentStackSize(StackSize);
2466 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2467 SDValue StackPtr, SDValue Arg,
2468 SDLoc dl, SelectionDAG &DAG,
2469 const CCValAssign &VA,
2470 ISD::ArgFlagsTy Flags) const {
2471 unsigned LocMemOffset = VA.getLocMemOffset();
2472 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2473 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2474 if (Flags.isByVal())
2475 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2477 return DAG.getStore(Chain, dl, Arg, PtrOff,
2478 MachinePointerInfo::getStack(LocMemOffset),
2482 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2483 /// optimization is performed and it is required.
2485 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2486 SDValue &OutRetAddr, SDValue Chain,
2487 bool IsTailCall, bool Is64Bit,
2488 int FPDiff, SDLoc dl) const {
2489 // Adjust the Return address stack slot.
2490 EVT VT = getPointerTy();
2491 OutRetAddr = getReturnAddressFrameIndex(DAG);
2493 // Load the "old" Return address.
2494 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2495 false, false, false, 0);
2496 return SDValue(OutRetAddr.getNode(), 1);
2499 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2500 /// optimization is performed and it is required (FPDiff!=0).
2501 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2502 SDValue Chain, SDValue RetAddrFrIdx,
2503 EVT PtrVT, unsigned SlotSize,
2504 int FPDiff, SDLoc dl) {
2505 // Store the return address to the appropriate stack slot.
2506 if (!FPDiff) return Chain;
2507 // Calculate the new stack slot for the return address.
2508 int NewReturnAddrFI =
2509 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2511 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2512 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2513 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2519 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2520 SmallVectorImpl<SDValue> &InVals) const {
2521 SelectionDAG &DAG = CLI.DAG;
2523 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2524 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2525 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2526 SDValue Chain = CLI.Chain;
2527 SDValue Callee = CLI.Callee;
2528 CallingConv::ID CallConv = CLI.CallConv;
2529 bool &isTailCall = CLI.IsTailCall;
2530 bool isVarArg = CLI.IsVarArg;
2532 MachineFunction &MF = DAG.getMachineFunction();
2533 bool Is64Bit = Subtarget->is64Bit();
2534 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2535 StructReturnType SR = callIsStructReturn(Outs);
2536 bool IsSibcall = false;
2538 if (MF.getTarget().Options.DisableTailCalls)
2541 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2543 // Force this to be a tail call. The verifier rules are enough to ensure
2544 // that we can lower this successfully without moving the return address
2547 } else if (isTailCall) {
2548 // Check if it's really possible to do a tail call.
2549 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2550 isVarArg, SR != NotStructReturn,
2551 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2552 Outs, OutVals, Ins, DAG);
2554 // Sibcalls are automatically detected tailcalls which do not require
2556 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2563 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2564 "Var args not supported with calling convention fastcc, ghc or hipe");
2566 // Analyze operands of the call, assigning locations to each operand.
2567 SmallVector<CCValAssign, 16> ArgLocs;
2568 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2569 ArgLocs, *DAG.getContext());
2571 // Allocate shadow area for Win64
2573 CCInfo.AllocateStack(32, 8);
2575 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2577 // Get a count of how many bytes are to be pushed on the stack.
2578 unsigned NumBytes = CCInfo.getNextStackOffset();
2580 // This is a sibcall. The memory operands are available in caller's
2581 // own caller's stack.
2583 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2584 IsTailCallConvention(CallConv))
2585 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2588 if (isTailCall && !IsSibcall && !IsMustTail) {
2589 // Lower arguments at fp - stackoffset + fpdiff.
2590 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2591 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2593 FPDiff = NumBytesCallerPushed - NumBytes;
2595 // Set the delta of movement of the returnaddr stackslot.
2596 // But only set if delta is greater than previous delta.
2597 if (FPDiff < X86Info->getTCReturnAddrDelta())
2598 X86Info->setTCReturnAddrDelta(FPDiff);
2601 unsigned NumBytesToPush = NumBytes;
2602 unsigned NumBytesToPop = NumBytes;
2604 // If we have an inalloca argument, all stack space has already been allocated
2605 // for us and be right at the top of the stack. We don't support multiple
2606 // arguments passed in memory when using inalloca.
2607 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2609 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2610 "an inalloca argument must be the only memory argument");
2614 Chain = DAG.getCALLSEQ_START(
2615 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2617 SDValue RetAddrFrIdx;
2618 // Load return address for tail calls.
2619 if (isTailCall && FPDiff)
2620 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2621 Is64Bit, FPDiff, dl);
2623 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2624 SmallVector<SDValue, 8> MemOpChains;
2627 // Walk the register/memloc assignments, inserting copies/loads. In the case
2628 // of tail call optimization arguments are handle later.
2629 const X86RegisterInfo *RegInfo =
2630 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2631 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2632 // Skip inalloca arguments, they have already been written.
2633 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2634 if (Flags.isInAlloca())
2637 CCValAssign &VA = ArgLocs[i];
2638 EVT RegVT = VA.getLocVT();
2639 SDValue Arg = OutVals[i];
2640 bool isByVal = Flags.isByVal();
2642 // Promote the value if needed.
2643 switch (VA.getLocInfo()) {
2644 default: llvm_unreachable("Unknown loc info!");
2645 case CCValAssign::Full: break;
2646 case CCValAssign::SExt:
2647 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2649 case CCValAssign::ZExt:
2650 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2652 case CCValAssign::AExt:
2653 if (RegVT.is128BitVector()) {
2654 // Special case: passing MMX values in XMM registers.
2655 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2656 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2657 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2659 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2661 case CCValAssign::BCvt:
2662 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2664 case CCValAssign::Indirect: {
2665 // Store the argument.
2666 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2667 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2668 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2669 MachinePointerInfo::getFixedStack(FI),
2676 if (VA.isRegLoc()) {
2677 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2678 if (isVarArg && IsWin64) {
2679 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2680 // shadow reg if callee is a varargs function.
2681 unsigned ShadowReg = 0;
2682 switch (VA.getLocReg()) {
2683 case X86::XMM0: ShadowReg = X86::RCX; break;
2684 case X86::XMM1: ShadowReg = X86::RDX; break;
2685 case X86::XMM2: ShadowReg = X86::R8; break;
2686 case X86::XMM3: ShadowReg = X86::R9; break;
2689 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2691 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2692 assert(VA.isMemLoc());
2693 if (!StackPtr.getNode())
2694 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2696 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2697 dl, DAG, VA, Flags));
2701 if (!MemOpChains.empty())
2702 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2704 if (Subtarget->isPICStyleGOT()) {
2705 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2708 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2709 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2711 // If we are tail calling and generating PIC/GOT style code load the
2712 // address of the callee into ECX. The value in ecx is used as target of
2713 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2714 // for tail calls on PIC/GOT architectures. Normally we would just put the
2715 // address of GOT into ebx and then call target@PLT. But for tail calls
2716 // ebx would be restored (since ebx is callee saved) before jumping to the
2719 // Note: The actual moving to ECX is done further down.
2720 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2721 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2722 !G->getGlobal()->hasProtectedVisibility())
2723 Callee = LowerGlobalAddress(Callee, DAG);
2724 else if (isa<ExternalSymbolSDNode>(Callee))
2725 Callee = LowerExternalSymbol(Callee, DAG);
2729 if (Is64Bit && isVarArg && !IsWin64) {
2730 // From AMD64 ABI document:
2731 // For calls that may call functions that use varargs or stdargs
2732 // (prototype-less calls or calls to functions containing ellipsis (...) in
2733 // the declaration) %al is used as hidden argument to specify the number
2734 // of SSE registers used. The contents of %al do not need to match exactly
2735 // the number of registers, but must be an ubound on the number of SSE
2736 // registers used and is in the range 0 - 8 inclusive.
2738 // Count the number of XMM registers allocated.
2739 static const MCPhysReg XMMArgRegs[] = {
2740 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2741 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2743 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2744 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2745 && "SSE registers cannot be used when SSE is disabled");
2747 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2748 DAG.getConstant(NumXMMRegs, MVT::i8)));
2751 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2752 // don't need this because the eligibility check rejects calls that require
2753 // shuffling arguments passed in memory.
2754 if (!IsSibcall && isTailCall) {
2755 // Force all the incoming stack arguments to be loaded from the stack
2756 // before any new outgoing arguments are stored to the stack, because the
2757 // outgoing stack slots may alias the incoming argument stack slots, and
2758 // the alias isn't otherwise explicit. This is slightly more conservative
2759 // than necessary, because it means that each store effectively depends
2760 // on every argument instead of just those arguments it would clobber.
2761 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2763 SmallVector<SDValue, 8> MemOpChains2;
2766 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2767 CCValAssign &VA = ArgLocs[i];
2770 assert(VA.isMemLoc());
2771 SDValue Arg = OutVals[i];
2772 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2773 // Skip inalloca arguments. They don't require any work.
2774 if (Flags.isInAlloca())
2776 // Create frame index.
2777 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2778 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2779 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2780 FIN = DAG.getFrameIndex(FI, getPointerTy());
2782 if (Flags.isByVal()) {
2783 // Copy relative to framepointer.
2784 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2785 if (!StackPtr.getNode())
2786 StackPtr = DAG.getCopyFromReg(Chain, dl,
2787 RegInfo->getStackRegister(),
2789 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2791 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2795 // Store relative to framepointer.
2796 MemOpChains2.push_back(
2797 DAG.getStore(ArgChain, dl, Arg, FIN,
2798 MachinePointerInfo::getFixedStack(FI),
2803 if (!MemOpChains2.empty())
2804 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2806 // Store the return address to the appropriate stack slot.
2807 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2808 getPointerTy(), RegInfo->getSlotSize(),
2812 // Build a sequence of copy-to-reg nodes chained together with token chain
2813 // and flag operands which copy the outgoing args into registers.
2815 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2816 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2817 RegsToPass[i].second, InFlag);
2818 InFlag = Chain.getValue(1);
2821 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2822 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2823 // In the 64-bit large code model, we have to make all calls
2824 // through a register, since the call instruction's 32-bit
2825 // pc-relative offset may not be large enough to hold the whole
2827 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2828 // If the callee is a GlobalAddress node (quite common, every direct call
2829 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2832 // We should use extra load for direct calls to dllimported functions in
2834 const GlobalValue *GV = G->getGlobal();
2835 if (!GV->hasDLLImportStorageClass()) {
2836 unsigned char OpFlags = 0;
2837 bool ExtraLoad = false;
2838 unsigned WrapperKind = ISD::DELETED_NODE;
2840 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2841 // external symbols most go through the PLT in PIC mode. If the symbol
2842 // has hidden or protected visibility, or if it is static or local, then
2843 // we don't need to use the PLT - we can directly call it.
2844 if (Subtarget->isTargetELF() &&
2845 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2846 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2847 OpFlags = X86II::MO_PLT;
2848 } else if (Subtarget->isPICStyleStubAny() &&
2849 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2850 (!Subtarget->getTargetTriple().isMacOSX() ||
2851 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2852 // PC-relative references to external symbols should go through $stub,
2853 // unless we're building with the leopard linker or later, which
2854 // automatically synthesizes these stubs.
2855 OpFlags = X86II::MO_DARWIN_STUB;
2856 } else if (Subtarget->isPICStyleRIPRel() &&
2857 isa<Function>(GV) &&
2858 cast<Function>(GV)->getAttributes().
2859 hasAttribute(AttributeSet::FunctionIndex,
2860 Attribute::NonLazyBind)) {
2861 // If the function is marked as non-lazy, generate an indirect call
2862 // which loads from the GOT directly. This avoids runtime overhead
2863 // at the cost of eager binding (and one extra byte of encoding).
2864 OpFlags = X86II::MO_GOTPCREL;
2865 WrapperKind = X86ISD::WrapperRIP;
2869 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2870 G->getOffset(), OpFlags);
2872 // Add a wrapper if needed.
2873 if (WrapperKind != ISD::DELETED_NODE)
2874 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2875 // Add extra indirection if needed.
2877 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2878 MachinePointerInfo::getGOT(),
2879 false, false, false, 0);
2881 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2882 unsigned char OpFlags = 0;
2884 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2885 // external symbols should go through the PLT.
2886 if (Subtarget->isTargetELF() &&
2887 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2888 OpFlags = X86II::MO_PLT;
2889 } else if (Subtarget->isPICStyleStubAny() &&
2890 (!Subtarget->getTargetTriple().isMacOSX() ||
2891 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2892 // PC-relative references to external symbols should go through $stub,
2893 // unless we're building with the leopard linker or later, which
2894 // automatically synthesizes these stubs.
2895 OpFlags = X86II::MO_DARWIN_STUB;
2898 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2902 // Returns a chain & a flag for retval copy to use.
2903 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2904 SmallVector<SDValue, 8> Ops;
2906 if (!IsSibcall && isTailCall) {
2907 Chain = DAG.getCALLSEQ_END(Chain,
2908 DAG.getIntPtrConstant(NumBytesToPop, true),
2909 DAG.getIntPtrConstant(0, true), InFlag, dl);
2910 InFlag = Chain.getValue(1);
2913 Ops.push_back(Chain);
2914 Ops.push_back(Callee);
2917 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2919 // Add argument registers to the end of the list so that they are known live
2921 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2922 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2923 RegsToPass[i].second.getValueType()));
2925 // Add a register mask operand representing the call-preserved registers.
2926 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2927 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2928 assert(Mask && "Missing call preserved mask for calling convention");
2929 Ops.push_back(DAG.getRegisterMask(Mask));
2931 if (InFlag.getNode())
2932 Ops.push_back(InFlag);
2936 //// If this is the first return lowered for this function, add the regs
2937 //// to the liveout set for the function.
2938 // This isn't right, although it's probably harmless on x86; liveouts
2939 // should be computed from returns not tail calls. Consider a void
2940 // function making a tail call to a function returning int.
2941 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2944 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2945 InFlag = Chain.getValue(1);
2947 // Create the CALLSEQ_END node.
2948 unsigned NumBytesForCalleeToPop;
2949 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2950 getTargetMachine().Options.GuaranteedTailCallOpt))
2951 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2952 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2953 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2954 SR == StackStructReturn)
2955 // If this is a call to a struct-return function, the callee
2956 // pops the hidden struct pointer, so we have to push it back.
2957 // This is common for Darwin/X86, Linux & Mingw32 targets.
2958 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2959 NumBytesForCalleeToPop = 4;
2961 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2963 // Returns a flag for retval copy to use.
2965 Chain = DAG.getCALLSEQ_END(Chain,
2966 DAG.getIntPtrConstant(NumBytesToPop, true),
2967 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2970 InFlag = Chain.getValue(1);
2973 // Handle result values, copying them out of physregs into vregs that we
2975 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2976 Ins, dl, DAG, InVals);
2979 //===----------------------------------------------------------------------===//
2980 // Fast Calling Convention (tail call) implementation
2981 //===----------------------------------------------------------------------===//
2983 // Like std call, callee cleans arguments, convention except that ECX is
2984 // reserved for storing the tail called function address. Only 2 registers are
2985 // free for argument passing (inreg). Tail call optimization is performed
2987 // * tailcallopt is enabled
2988 // * caller/callee are fastcc
2989 // On X86_64 architecture with GOT-style position independent code only local
2990 // (within module) calls are supported at the moment.
2991 // To keep the stack aligned according to platform abi the function
2992 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2993 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2994 // If a tail called function callee has more arguments than the caller the
2995 // caller needs to make sure that there is room to move the RETADDR to. This is
2996 // achieved by reserving an area the size of the argument delta right after the
2997 // original REtADDR, but before the saved framepointer or the spilled registers
2998 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3010 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3011 /// for a 16 byte align requirement.
3013 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3014 SelectionDAG& DAG) const {
3015 MachineFunction &MF = DAG.getMachineFunction();
3016 const TargetMachine &TM = MF.getTarget();
3017 const X86RegisterInfo *RegInfo =
3018 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3019 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3020 unsigned StackAlignment = TFI.getStackAlignment();
3021 uint64_t AlignMask = StackAlignment - 1;
3022 int64_t Offset = StackSize;
3023 unsigned SlotSize = RegInfo->getSlotSize();
3024 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3025 // Number smaller than 12 so just add the difference.
3026 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3028 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3029 Offset = ((~AlignMask) & Offset) + StackAlignment +
3030 (StackAlignment-SlotSize);
3035 /// MatchingStackOffset - Return true if the given stack call argument is
3036 /// already available in the same position (relatively) of the caller's
3037 /// incoming argument stack.
3039 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3040 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3041 const X86InstrInfo *TII) {
3042 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3044 if (Arg.getOpcode() == ISD::CopyFromReg) {
3045 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3046 if (!TargetRegisterInfo::isVirtualRegister(VR))
3048 MachineInstr *Def = MRI->getVRegDef(VR);
3051 if (!Flags.isByVal()) {
3052 if (!TII->isLoadFromStackSlot(Def, FI))
3055 unsigned Opcode = Def->getOpcode();
3056 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3057 Def->getOperand(1).isFI()) {
3058 FI = Def->getOperand(1).getIndex();
3059 Bytes = Flags.getByValSize();
3063 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3064 if (Flags.isByVal())
3065 // ByVal argument is passed in as a pointer but it's now being
3066 // dereferenced. e.g.
3067 // define @foo(%struct.X* %A) {
3068 // tail call @bar(%struct.X* byval %A)
3071 SDValue Ptr = Ld->getBasePtr();
3072 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3075 FI = FINode->getIndex();
3076 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3077 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3078 FI = FINode->getIndex();
3079 Bytes = Flags.getByValSize();
3083 assert(FI != INT_MAX);
3084 if (!MFI->isFixedObjectIndex(FI))
3086 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3089 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3090 /// for tail call optimization. Targets which want to do tail call
3091 /// optimization should implement this function.
3093 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3094 CallingConv::ID CalleeCC,
3096 bool isCalleeStructRet,
3097 bool isCallerStructRet,
3099 const SmallVectorImpl<ISD::OutputArg> &Outs,
3100 const SmallVectorImpl<SDValue> &OutVals,
3101 const SmallVectorImpl<ISD::InputArg> &Ins,
3102 SelectionDAG &DAG) const {
3103 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3106 // If -tailcallopt is specified, make fastcc functions tail-callable.
3107 const MachineFunction &MF = DAG.getMachineFunction();
3108 const Function *CallerF = MF.getFunction();
3110 // If the function return type is x86_fp80 and the callee return type is not,
3111 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3112 // perform a tailcall optimization here.
3113 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3116 CallingConv::ID CallerCC = CallerF->getCallingConv();
3117 bool CCMatch = CallerCC == CalleeCC;
3118 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3119 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3121 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3122 if (IsTailCallConvention(CalleeCC) && CCMatch)
3127 // Look for obvious safe cases to perform tail call optimization that do not
3128 // require ABI changes. This is what gcc calls sibcall.
3130 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3131 // emit a special epilogue.
3132 const X86RegisterInfo *RegInfo =
3133 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3134 if (RegInfo->needsStackRealignment(MF))
3137 // Also avoid sibcall optimization if either caller or callee uses struct
3138 // return semantics.
3139 if (isCalleeStructRet || isCallerStructRet)
3142 // An stdcall/thiscall caller is expected to clean up its arguments; the
3143 // callee isn't going to do that.
3144 // FIXME: this is more restrictive than needed. We could produce a tailcall
3145 // when the stack adjustment matches. For example, with a thiscall that takes
3146 // only one argument.
3147 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3148 CallerCC == CallingConv::X86_ThisCall))
3151 // Do not sibcall optimize vararg calls unless all arguments are passed via
3153 if (isVarArg && !Outs.empty()) {
3155 // Optimizing for varargs on Win64 is unlikely to be safe without
3156 // additional testing.
3157 if (IsCalleeWin64 || IsCallerWin64)
3160 SmallVector<CCValAssign, 16> ArgLocs;
3161 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3162 getTargetMachine(), ArgLocs, *DAG.getContext());
3164 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3165 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3166 if (!ArgLocs[i].isRegLoc())
3170 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3171 // stack. Therefore, if it's not used by the call it is not safe to optimize
3172 // this into a sibcall.
3173 bool Unused = false;
3174 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3181 SmallVector<CCValAssign, 16> RVLocs;
3182 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3183 getTargetMachine(), RVLocs, *DAG.getContext());
3184 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3185 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3186 CCValAssign &VA = RVLocs[i];
3187 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3192 // If the calling conventions do not match, then we'd better make sure the
3193 // results are returned in the same way as what the caller expects.
3195 SmallVector<CCValAssign, 16> RVLocs1;
3196 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3197 getTargetMachine(), RVLocs1, *DAG.getContext());
3198 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3200 SmallVector<CCValAssign, 16> RVLocs2;
3201 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3202 getTargetMachine(), RVLocs2, *DAG.getContext());
3203 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3205 if (RVLocs1.size() != RVLocs2.size())
3207 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3208 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3210 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3212 if (RVLocs1[i].isRegLoc()) {
3213 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3216 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3222 // If the callee takes no arguments then go on to check the results of the
3224 if (!Outs.empty()) {
3225 // Check if stack adjustment is needed. For now, do not do this if any
3226 // argument is passed on the stack.
3227 SmallVector<CCValAssign, 16> ArgLocs;
3228 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3229 getTargetMachine(), ArgLocs, *DAG.getContext());
3231 // Allocate shadow area for Win64
3233 CCInfo.AllocateStack(32, 8);
3235 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3236 if (CCInfo.getNextStackOffset()) {
3237 MachineFunction &MF = DAG.getMachineFunction();
3238 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3241 // Check if the arguments are already laid out in the right way as
3242 // the caller's fixed stack objects.
3243 MachineFrameInfo *MFI = MF.getFrameInfo();
3244 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3245 const X86InstrInfo *TII =
3246 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3247 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3248 CCValAssign &VA = ArgLocs[i];
3249 SDValue Arg = OutVals[i];
3250 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3251 if (VA.getLocInfo() == CCValAssign::Indirect)
3253 if (!VA.isRegLoc()) {
3254 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3261 // If the tailcall address may be in a register, then make sure it's
3262 // possible to register allocate for it. In 32-bit, the call address can
3263 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3264 // callee-saved registers are restored. These happen to be the same
3265 // registers used to pass 'inreg' arguments so watch out for those.
3266 if (!Subtarget->is64Bit() &&
3267 ((!isa<GlobalAddressSDNode>(Callee) &&
3268 !isa<ExternalSymbolSDNode>(Callee)) ||
3269 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3270 unsigned NumInRegs = 0;
3271 // In PIC we need an extra register to formulate the address computation
3273 unsigned MaxInRegs =
3274 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3276 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3277 CCValAssign &VA = ArgLocs[i];
3280 unsigned Reg = VA.getLocReg();
3283 case X86::EAX: case X86::EDX: case X86::ECX:
3284 if (++NumInRegs == MaxInRegs)
3296 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3297 const TargetLibraryInfo *libInfo) const {
3298 return X86::createFastISel(funcInfo, libInfo);
3301 //===----------------------------------------------------------------------===//
3302 // Other Lowering Hooks
3303 //===----------------------------------------------------------------------===//
3305 static bool MayFoldLoad(SDValue Op) {
3306 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3309 static bool MayFoldIntoStore(SDValue Op) {
3310 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3313 static bool isTargetShuffle(unsigned Opcode) {
3315 default: return false;
3316 case X86ISD::PSHUFD:
3317 case X86ISD::PSHUFHW:
3318 case X86ISD::PSHUFLW:
3320 case X86ISD::PALIGNR:
3321 case X86ISD::MOVLHPS:
3322 case X86ISD::MOVLHPD:
3323 case X86ISD::MOVHLPS:
3324 case X86ISD::MOVLPS:
3325 case X86ISD::MOVLPD:
3326 case X86ISD::MOVSHDUP:
3327 case X86ISD::MOVSLDUP:
3328 case X86ISD::MOVDDUP:
3331 case X86ISD::UNPCKL:
3332 case X86ISD::UNPCKH:
3333 case X86ISD::VPERMILP:
3334 case X86ISD::VPERM2X128:
3335 case X86ISD::VPERMI:
3340 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3341 SDValue V1, SelectionDAG &DAG) {
3343 default: llvm_unreachable("Unknown x86 shuffle node");
3344 case X86ISD::MOVSHDUP:
3345 case X86ISD::MOVSLDUP:
3346 case X86ISD::MOVDDUP:
3347 return DAG.getNode(Opc, dl, VT, V1);
3351 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3352 SDValue V1, unsigned TargetMask,
3353 SelectionDAG &DAG) {
3355 default: llvm_unreachable("Unknown x86 shuffle node");
3356 case X86ISD::PSHUFD:
3357 case X86ISD::PSHUFHW:
3358 case X86ISD::PSHUFLW:
3359 case X86ISD::VPERMILP:
3360 case X86ISD::VPERMI:
3361 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3365 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3366 SDValue V1, SDValue V2, unsigned TargetMask,
3367 SelectionDAG &DAG) {
3369 default: llvm_unreachable("Unknown x86 shuffle node");
3370 case X86ISD::PALIGNR:
3372 case X86ISD::VPERM2X128:
3373 return DAG.getNode(Opc, dl, VT, V1, V2,
3374 DAG.getConstant(TargetMask, MVT::i8));
3378 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3379 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3381 default: llvm_unreachable("Unknown x86 shuffle node");
3382 case X86ISD::MOVLHPS:
3383 case X86ISD::MOVLHPD:
3384 case X86ISD::MOVHLPS:
3385 case X86ISD::MOVLPS:
3386 case X86ISD::MOVLPD:
3389 case X86ISD::UNPCKL:
3390 case X86ISD::UNPCKH:
3391 return DAG.getNode(Opc, dl, VT, V1, V2);
3395 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3396 MachineFunction &MF = DAG.getMachineFunction();
3397 const X86RegisterInfo *RegInfo =
3398 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3399 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3400 int ReturnAddrIndex = FuncInfo->getRAIndex();
3402 if (ReturnAddrIndex == 0) {
3403 // Set up a frame object for the return address.
3404 unsigned SlotSize = RegInfo->getSlotSize();
3405 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3408 FuncInfo->setRAIndex(ReturnAddrIndex);
3411 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3414 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3415 bool hasSymbolicDisplacement) {
3416 // Offset should fit into 32 bit immediate field.
3417 if (!isInt<32>(Offset))
3420 // If we don't have a symbolic displacement - we don't have any extra
3422 if (!hasSymbolicDisplacement)
3425 // FIXME: Some tweaks might be needed for medium code model.
3426 if (M != CodeModel::Small && M != CodeModel::Kernel)
3429 // For small code model we assume that latest object is 16MB before end of 31
3430 // bits boundary. We may also accept pretty large negative constants knowing
3431 // that all objects are in the positive half of address space.
3432 if (M == CodeModel::Small && Offset < 16*1024*1024)
3435 // For kernel code model we know that all object resist in the negative half
3436 // of 32bits address space. We may not accept negative offsets, since they may
3437 // be just off and we may accept pretty large positive ones.
3438 if (M == CodeModel::Kernel && Offset > 0)
3444 /// isCalleePop - Determines whether the callee is required to pop its
3445 /// own arguments. Callee pop is necessary to support tail calls.
3446 bool X86::isCalleePop(CallingConv::ID CallingConv,
3447 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3451 switch (CallingConv) {
3454 case CallingConv::X86_StdCall:
3456 case CallingConv::X86_FastCall:
3458 case CallingConv::X86_ThisCall:
3460 case CallingConv::Fast:
3462 case CallingConv::GHC:
3464 case CallingConv::HiPE:
3469 /// \brief Return true if the condition is an unsigned comparison operation.
3470 static bool isX86CCUnsigned(unsigned X86CC) {
3472 default: llvm_unreachable("Invalid integer condition!");
3473 case X86::COND_E: return true;
3474 case X86::COND_G: return false;
3475 case X86::COND_GE: return false;
3476 case X86::COND_L: return false;
3477 case X86::COND_LE: return false;
3478 case X86::COND_NE: return true;
3479 case X86::COND_B: return true;
3480 case X86::COND_A: return true;
3481 case X86::COND_BE: return true;
3482 case X86::COND_AE: return true;
3484 llvm_unreachable("covered switch fell through?!");
3487 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3488 /// specific condition code, returning the condition code and the LHS/RHS of the
3489 /// comparison to make.
3490 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3491 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3493 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3494 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3495 // X > -1 -> X == 0, jump !sign.
3496 RHS = DAG.getConstant(0, RHS.getValueType());
3497 return X86::COND_NS;
3499 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3500 // X < 0 -> X == 0, jump on sign.
3503 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3505 RHS = DAG.getConstant(0, RHS.getValueType());
3506 return X86::COND_LE;
3510 switch (SetCCOpcode) {
3511 default: llvm_unreachable("Invalid integer condition!");
3512 case ISD::SETEQ: return X86::COND_E;
3513 case ISD::SETGT: return X86::COND_G;
3514 case ISD::SETGE: return X86::COND_GE;
3515 case ISD::SETLT: return X86::COND_L;
3516 case ISD::SETLE: return X86::COND_LE;
3517 case ISD::SETNE: return X86::COND_NE;
3518 case ISD::SETULT: return X86::COND_B;
3519 case ISD::SETUGT: return X86::COND_A;
3520 case ISD::SETULE: return X86::COND_BE;
3521 case ISD::SETUGE: return X86::COND_AE;
3525 // First determine if it is required or is profitable to flip the operands.
3527 // If LHS is a foldable load, but RHS is not, flip the condition.
3528 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3529 !ISD::isNON_EXTLoad(RHS.getNode())) {
3530 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3531 std::swap(LHS, RHS);
3534 switch (SetCCOpcode) {
3540 std::swap(LHS, RHS);
3544 // On a floating point condition, the flags are set as follows:
3546 // 0 | 0 | 0 | X > Y
3547 // 0 | 0 | 1 | X < Y
3548 // 1 | 0 | 0 | X == Y
3549 // 1 | 1 | 1 | unordered
3550 switch (SetCCOpcode) {
3551 default: llvm_unreachable("Condcode should be pre-legalized away");
3553 case ISD::SETEQ: return X86::COND_E;
3554 case ISD::SETOLT: // flipped
3556 case ISD::SETGT: return X86::COND_A;
3557 case ISD::SETOLE: // flipped
3559 case ISD::SETGE: return X86::COND_AE;
3560 case ISD::SETUGT: // flipped
3562 case ISD::SETLT: return X86::COND_B;
3563 case ISD::SETUGE: // flipped
3565 case ISD::SETLE: return X86::COND_BE;
3567 case ISD::SETNE: return X86::COND_NE;
3568 case ISD::SETUO: return X86::COND_P;
3569 case ISD::SETO: return X86::COND_NP;
3571 case ISD::SETUNE: return X86::COND_INVALID;
3575 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3576 /// code. Current x86 isa includes the following FP cmov instructions:
3577 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3578 static bool hasFPCMov(unsigned X86CC) {
3594 /// isFPImmLegal - Returns true if the target can instruction select the
3595 /// specified FP immediate natively. If false, the legalizer will
3596 /// materialize the FP immediate as a load from a constant pool.
3597 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3598 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3599 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3605 /// \brief Returns true if it is beneficial to convert a load of a constant
3606 /// to just the constant itself.
3607 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3609 assert(Ty->isIntegerTy());
3611 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3612 if (BitSize == 0 || BitSize > 64)
3617 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3618 /// the specified range (L, H].
3619 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3620 return (Val < 0) || (Val >= Low && Val < Hi);
3623 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3624 /// specified value.
3625 static bool isUndefOrEqual(int Val, int CmpVal) {
3626 return (Val < 0 || Val == CmpVal);
3629 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3630 /// from position Pos and ending in Pos+Size, falls within the specified
3631 /// sequential range (L, L+Pos]. or is undef.
3632 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3633 unsigned Pos, unsigned Size, int Low) {
3634 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3635 if (!isUndefOrEqual(Mask[i], Low))
3640 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3641 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3642 /// the second operand.
3643 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3644 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3645 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3646 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3647 return (Mask[0] < 2 && Mask[1] < 2);
3651 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3652 /// is suitable for input to PSHUFHW.
3653 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3654 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3657 // Lower quadword copied in order or undef.
3658 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3661 // Upper quadword shuffled.
3662 for (unsigned i = 4; i != 8; ++i)
3663 if (!isUndefOrInRange(Mask[i], 4, 8))
3666 if (VT == MVT::v16i16) {
3667 // Lower quadword copied in order or undef.
3668 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3671 // Upper quadword shuffled.
3672 for (unsigned i = 12; i != 16; ++i)
3673 if (!isUndefOrInRange(Mask[i], 12, 16))
3680 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3681 /// is suitable for input to PSHUFLW.
3682 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3683 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3686 // Upper quadword copied in order.
3687 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3690 // Lower quadword shuffled.
3691 for (unsigned i = 0; i != 4; ++i)
3692 if (!isUndefOrInRange(Mask[i], 0, 4))
3695 if (VT == MVT::v16i16) {
3696 // Upper quadword copied in order.
3697 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3700 // Lower quadword shuffled.
3701 for (unsigned i = 8; i != 12; ++i)
3702 if (!isUndefOrInRange(Mask[i], 8, 12))
3709 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3710 /// is suitable for input to PALIGNR.
3711 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3712 const X86Subtarget *Subtarget) {
3713 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3714 (VT.is256BitVector() && !Subtarget->hasInt256()))
3717 unsigned NumElts = VT.getVectorNumElements();
3718 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3719 unsigned NumLaneElts = NumElts/NumLanes;
3721 // Do not handle 64-bit element shuffles with palignr.
3722 if (NumLaneElts == 2)
3725 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3727 for (i = 0; i != NumLaneElts; ++i) {
3732 // Lane is all undef, go to next lane
3733 if (i == NumLaneElts)
3736 int Start = Mask[i+l];
3738 // Make sure its in this lane in one of the sources
3739 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3740 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3743 // If not lane 0, then we must match lane 0
3744 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3747 // Correct second source to be contiguous with first source
3748 if (Start >= (int)NumElts)
3749 Start -= NumElts - NumLaneElts;
3751 // Make sure we're shifting in the right direction.
3752 if (Start <= (int)(i+l))
3757 // Check the rest of the elements to see if they are consecutive.
3758 for (++i; i != NumLaneElts; ++i) {
3759 int Idx = Mask[i+l];
3761 // Make sure its in this lane
3762 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3763 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3766 // If not lane 0, then we must match lane 0
3767 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3770 if (Idx >= (int)NumElts)
3771 Idx -= NumElts - NumLaneElts;
3773 if (!isUndefOrEqual(Idx, Start+i))
3782 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3783 /// the two vector operands have swapped position.
3784 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3785 unsigned NumElems) {
3786 for (unsigned i = 0; i != NumElems; ++i) {
3790 else if (idx < (int)NumElems)
3791 Mask[i] = idx + NumElems;
3793 Mask[i] = idx - NumElems;
3797 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3798 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3799 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3800 /// reverse of what x86 shuffles want.
3801 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3803 unsigned NumElems = VT.getVectorNumElements();
3804 unsigned NumLanes = VT.getSizeInBits()/128;
3805 unsigned NumLaneElems = NumElems/NumLanes;
3807 if (NumLaneElems != 2 && NumLaneElems != 4)
3810 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3811 bool symetricMaskRequired =
3812 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3814 // VSHUFPSY 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 => X7 X6 X5 X4 X3 X2 X1 X0
3819 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3821 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3822 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3824 // VSHUFPDY divides the resulting vector into 4 chunks.
3825 // The sources are also splitted into 4 chunks, and each destination
3826 // chunk must come from a different source chunk.
3828 // SRC1 => X3 X2 X1 X0
3829 // SRC2 => Y3 Y2 Y1 Y0
3831 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3833 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3834 unsigned HalfLaneElems = NumLaneElems/2;
3835 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3836 for (unsigned i = 0; i != NumLaneElems; ++i) {
3837 int Idx = Mask[i+l];
3838 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3839 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3841 // For VSHUFPSY, the mask of the second half must be the same as the
3842 // first but with the appropriate offsets. This works in the same way as
3843 // VPERMILPS works with masks.
3844 if (!symetricMaskRequired || Idx < 0)
3846 if (MaskVal[i] < 0) {
3847 MaskVal[i] = Idx - l;
3850 if ((signed)(Idx - l) != MaskVal[i])
3858 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3859 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3860 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3861 if (!VT.is128BitVector())
3864 unsigned NumElems = VT.getVectorNumElements();
3869 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3870 return isUndefOrEqual(Mask[0], 6) &&
3871 isUndefOrEqual(Mask[1], 7) &&
3872 isUndefOrEqual(Mask[2], 2) &&
3873 isUndefOrEqual(Mask[3], 3);
3876 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3877 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3879 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3880 if (!VT.is128BitVector())
3883 unsigned NumElems = VT.getVectorNumElements();
3888 return isUndefOrEqual(Mask[0], 2) &&
3889 isUndefOrEqual(Mask[1], 3) &&
3890 isUndefOrEqual(Mask[2], 2) &&
3891 isUndefOrEqual(Mask[3], 3);
3894 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3895 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3896 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3897 if (!VT.is128BitVector())
3900 unsigned NumElems = VT.getVectorNumElements();
3902 if (NumElems != 2 && NumElems != 4)
3905 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3906 if (!isUndefOrEqual(Mask[i], i + NumElems))
3909 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3910 if (!isUndefOrEqual(Mask[i], i))
3916 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3917 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3918 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3919 if (!VT.is128BitVector())
3922 unsigned NumElems = VT.getVectorNumElements();
3924 if (NumElems != 2 && NumElems != 4)
3927 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3928 if (!isUndefOrEqual(Mask[i], i))
3931 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3932 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3938 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3939 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3940 /// i. e: If all but one element come from the same vector.
3941 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3942 // TODO: Deal with AVX's VINSERTPS
3943 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3946 unsigned CorrectPosV1 = 0;
3947 unsigned CorrectPosV2 = 0;
3948 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3951 else if (Mask[i] == i + 4)
3954 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3955 // We have 3 elements from one vector, and one from another.
3962 // Some special combinations that can be optimized.
3965 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3966 SelectionDAG &DAG) {
3967 MVT VT = SVOp->getSimpleValueType(0);
3970 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3973 ArrayRef<int> Mask = SVOp->getMask();
3975 // These are the special masks that may be optimized.
3976 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3977 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3978 bool MatchEvenMask = true;
3979 bool MatchOddMask = true;
3980 for (int i=0; i<8; ++i) {
3981 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3982 MatchEvenMask = false;
3983 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3984 MatchOddMask = false;
3987 if (!MatchEvenMask && !MatchOddMask)
3990 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3992 SDValue Op0 = SVOp->getOperand(0);
3993 SDValue Op1 = SVOp->getOperand(1);
3995 if (MatchEvenMask) {
3996 // Shift the second operand right to 32 bits.
3997 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3998 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4000 // Shift the first operand left to 32 bits.
4001 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4002 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4004 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4005 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4008 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4009 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4010 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4011 bool HasInt256, bool V2IsSplat = false) {
4013 assert(VT.getSizeInBits() >= 128 &&
4014 "Unsupported vector type for unpckl");
4016 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4018 unsigned NumOf256BitLanes;
4019 unsigned NumElts = VT.getVectorNumElements();
4020 if (VT.is256BitVector()) {
4021 if (NumElts != 4 && NumElts != 8 &&
4022 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4025 NumOf256BitLanes = 1;
4026 } else if (VT.is512BitVector()) {
4027 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4028 "Unsupported vector type for unpckh");
4030 NumOf256BitLanes = 2;
4033 NumOf256BitLanes = 1;
4036 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4037 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4039 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4040 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4041 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4042 int BitI = Mask[l256*NumEltsInStride+l+i];
4043 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4044 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4046 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4048 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4056 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4057 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4058 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4059 bool HasInt256, bool V2IsSplat = false) {
4060 assert(VT.getSizeInBits() >= 128 &&
4061 "Unsupported vector type for unpckh");
4063 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4065 unsigned NumOf256BitLanes;
4066 unsigned NumElts = VT.getVectorNumElements();
4067 if (VT.is256BitVector()) {
4068 if (NumElts != 4 && NumElts != 8 &&
4069 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4072 NumOf256BitLanes = 1;
4073 } else if (VT.is512BitVector()) {
4074 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4075 "Unsupported vector type for unpckh");
4077 NumOf256BitLanes = 2;
4080 NumOf256BitLanes = 1;
4083 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4084 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4086 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4087 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4088 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4089 int BitI = Mask[l256*NumEltsInStride+l+i];
4090 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4091 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4093 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4095 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4103 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4104 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4106 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4107 unsigned NumElts = VT.getVectorNumElements();
4108 bool Is256BitVec = VT.is256BitVector();
4110 if (VT.is512BitVector())
4112 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4113 "Unsupported vector type for unpckh");
4115 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4116 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4119 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4120 // FIXME: Need a better way to get rid of this, there's no latency difference
4121 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4122 // the former later. We should also remove the "_undef" special mask.
4123 if (NumElts == 4 && Is256BitVec)
4126 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4127 // independently on 128-bit lanes.
4128 unsigned NumLanes = VT.getSizeInBits()/128;
4129 unsigned NumLaneElts = NumElts/NumLanes;
4131 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4132 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4133 int BitI = Mask[l+i];
4134 int BitI1 = Mask[l+i+1];
4136 if (!isUndefOrEqual(BitI, j))
4138 if (!isUndefOrEqual(BitI1, j))
4146 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4147 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4149 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4150 unsigned NumElts = VT.getVectorNumElements();
4152 if (VT.is512BitVector())
4155 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4156 "Unsupported vector type for unpckh");
4158 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4159 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4162 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4163 // independently on 128-bit lanes.
4164 unsigned NumLanes = VT.getSizeInBits()/128;
4165 unsigned NumLaneElts = NumElts/NumLanes;
4167 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4168 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4169 int BitI = Mask[l+i];
4170 int BitI1 = Mask[l+i+1];
4171 if (!isUndefOrEqual(BitI, j))
4173 if (!isUndefOrEqual(BitI1, j))
4180 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4181 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4182 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4183 if (!VT.is512BitVector())
4186 unsigned NumElts = VT.getVectorNumElements();
4187 unsigned HalfSize = NumElts/2;
4188 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4189 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4194 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4195 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4203 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4204 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4205 /// MOVSD, and MOVD, i.e. setting the lowest element.
4206 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4207 if (VT.getVectorElementType().getSizeInBits() < 32)
4209 if (!VT.is128BitVector())
4212 unsigned NumElts = VT.getVectorNumElements();
4214 if (!isUndefOrEqual(Mask[0], NumElts))
4217 for (unsigned i = 1; i != NumElts; ++i)
4218 if (!isUndefOrEqual(Mask[i], i))
4224 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4225 /// as permutations between 128-bit chunks or halves. As an example: this
4227 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4228 /// The first half comes from the second half of V1 and the second half from the
4229 /// the second half of V2.
4230 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4231 if (!HasFp256 || !VT.is256BitVector())
4234 // The shuffle result is divided into half A and half B. In total the two
4235 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4236 // B must come from C, D, E or F.
4237 unsigned HalfSize = VT.getVectorNumElements()/2;
4238 bool MatchA = false, MatchB = false;
4240 // Check if A comes from one of C, D, E, F.
4241 for (unsigned Half = 0; Half != 4; ++Half) {
4242 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4248 // Check if B comes from one of C, D, E, F.
4249 for (unsigned Half = 0; Half != 4; ++Half) {
4250 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4256 return MatchA && MatchB;
4259 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4260 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4261 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4262 MVT VT = SVOp->getSimpleValueType(0);
4264 unsigned HalfSize = VT.getVectorNumElements()/2;
4266 unsigned FstHalf = 0, SndHalf = 0;
4267 for (unsigned i = 0; i < HalfSize; ++i) {
4268 if (SVOp->getMaskElt(i) > 0) {
4269 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4273 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4274 if (SVOp->getMaskElt(i) > 0) {
4275 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4280 return (FstHalf | (SndHalf << 4));
4283 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4284 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4285 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4289 unsigned NumElts = VT.getVectorNumElements();
4291 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4292 for (unsigned i = 0; i != NumElts; ++i) {
4295 Imm8 |= Mask[i] << (i*2);
4300 unsigned LaneSize = 4;
4301 SmallVector<int, 4> MaskVal(LaneSize, -1);
4303 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4304 for (unsigned i = 0; i != LaneSize; ++i) {
4305 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4309 if (MaskVal[i] < 0) {
4310 MaskVal[i] = Mask[i+l] - l;
4311 Imm8 |= MaskVal[i] << (i*2);
4314 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4321 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4322 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4323 /// Note that VPERMIL mask matching is different depending whether theunderlying
4324 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4325 /// to the same elements of the low, but to the higher half of the source.
4326 /// In VPERMILPD the two lanes could be shuffled independently of each other
4327 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4328 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4329 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4330 if (VT.getSizeInBits() < 256 || EltSize < 32)
4332 bool symetricMaskRequired = (EltSize == 32);
4333 unsigned NumElts = VT.getVectorNumElements();
4335 unsigned NumLanes = VT.getSizeInBits()/128;
4336 unsigned LaneSize = NumElts/NumLanes;
4337 // 2 or 4 elements in one lane
4339 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4340 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4341 for (unsigned i = 0; i != LaneSize; ++i) {
4342 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4344 if (symetricMaskRequired) {
4345 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4346 ExpectedMaskVal[i] = Mask[i+l] - l;
4349 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4357 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4358 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4359 /// element of vector 2 and the other elements to come from vector 1 in order.
4360 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4361 bool V2IsSplat = false, bool V2IsUndef = false) {
4362 if (!VT.is128BitVector())
4365 unsigned NumOps = VT.getVectorNumElements();
4366 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4369 if (!isUndefOrEqual(Mask[0], 0))
4372 for (unsigned i = 1; i != NumOps; ++i)
4373 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4374 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4375 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4381 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4382 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4383 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4384 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4385 const X86Subtarget *Subtarget) {
4386 if (!Subtarget->hasSSE3())
4389 unsigned NumElems = VT.getVectorNumElements();
4391 if ((VT.is128BitVector() && NumElems != 4) ||
4392 (VT.is256BitVector() && NumElems != 8) ||
4393 (VT.is512BitVector() && NumElems != 16))
4396 // "i+1" is the value the indexed mask element must have
4397 for (unsigned i = 0; i != NumElems; i += 2)
4398 if (!isUndefOrEqual(Mask[i], i+1) ||
4399 !isUndefOrEqual(Mask[i+1], i+1))
4405 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4406 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4407 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4408 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4409 const X86Subtarget *Subtarget) {
4410 if (!Subtarget->hasSSE3())
4413 unsigned NumElems = VT.getVectorNumElements();
4415 if ((VT.is128BitVector() && NumElems != 4) ||
4416 (VT.is256BitVector() && NumElems != 8) ||
4417 (VT.is512BitVector() && NumElems != 16))
4420 // "i" is the value the indexed mask element must have
4421 for (unsigned i = 0; i != NumElems; i += 2)
4422 if (!isUndefOrEqual(Mask[i], i) ||
4423 !isUndefOrEqual(Mask[i+1], i))
4429 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4430 /// specifies a shuffle of elements that is suitable for input to 256-bit
4431 /// version of MOVDDUP.
4432 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4433 if (!HasFp256 || !VT.is256BitVector())
4436 unsigned NumElts = VT.getVectorNumElements();
4440 for (unsigned i = 0; i != NumElts/2; ++i)
4441 if (!isUndefOrEqual(Mask[i], 0))
4443 for (unsigned i = NumElts/2; i != NumElts; ++i)
4444 if (!isUndefOrEqual(Mask[i], NumElts/2))
4449 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4450 /// specifies a shuffle of elements that is suitable for input to 128-bit
4451 /// version of MOVDDUP.
4452 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4453 if (!VT.is128BitVector())
4456 unsigned e = VT.getVectorNumElements() / 2;
4457 for (unsigned i = 0; i != e; ++i)
4458 if (!isUndefOrEqual(Mask[i], i))
4460 for (unsigned i = 0; i != e; ++i)
4461 if (!isUndefOrEqual(Mask[e+i], i))
4466 /// isVEXTRACTIndex - Return true if the specified
4467 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4468 /// suitable for instruction that extract 128 or 256 bit vectors
4469 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4470 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4471 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4474 // The index should be aligned on a vecWidth-bit boundary.
4476 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4478 MVT VT = N->getSimpleValueType(0);
4479 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4480 bool Result = (Index * ElSize) % vecWidth == 0;
4485 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4486 /// operand specifies a subvector insert that is suitable for input to
4487 /// insertion of 128 or 256-bit subvectors
4488 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4489 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4490 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4492 // The index should be aligned on a vecWidth-bit boundary.
4494 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4496 MVT VT = N->getSimpleValueType(0);
4497 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4498 bool Result = (Index * ElSize) % vecWidth == 0;
4503 bool X86::isVINSERT128Index(SDNode *N) {
4504 return isVINSERTIndex(N, 128);
4507 bool X86::isVINSERT256Index(SDNode *N) {
4508 return isVINSERTIndex(N, 256);
4511 bool X86::isVEXTRACT128Index(SDNode *N) {
4512 return isVEXTRACTIndex(N, 128);
4515 bool X86::isVEXTRACT256Index(SDNode *N) {
4516 return isVEXTRACTIndex(N, 256);
4519 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4520 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4521 /// Handles 128-bit and 256-bit.
4522 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4523 MVT VT = N->getSimpleValueType(0);
4525 assert((VT.getSizeInBits() >= 128) &&
4526 "Unsupported vector type for PSHUF/SHUFP");
4528 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4529 // independently on 128-bit lanes.
4530 unsigned NumElts = VT.getVectorNumElements();
4531 unsigned NumLanes = VT.getSizeInBits()/128;
4532 unsigned NumLaneElts = NumElts/NumLanes;
4534 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4535 "Only supports 2, 4 or 8 elements per lane");
4537 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4539 for (unsigned i = 0; i != NumElts; ++i) {
4540 int Elt = N->getMaskElt(i);
4541 if (Elt < 0) continue;
4542 Elt &= NumLaneElts - 1;
4543 unsigned ShAmt = (i << Shift) % 8;
4544 Mask |= Elt << ShAmt;
4550 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4551 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4552 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4553 MVT VT = N->getSimpleValueType(0);
4555 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4556 "Unsupported vector type for PSHUFHW");
4558 unsigned NumElts = VT.getVectorNumElements();
4561 for (unsigned l = 0; l != NumElts; l += 8) {
4562 // 8 nodes per lane, but we only care about the last 4.
4563 for (unsigned i = 0; i < 4; ++i) {
4564 int Elt = N->getMaskElt(l+i+4);
4565 if (Elt < 0) continue;
4566 Elt &= 0x3; // only 2-bits.
4567 Mask |= Elt << (i * 2);
4574 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4575 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4576 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4577 MVT VT = N->getSimpleValueType(0);
4579 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4580 "Unsupported vector type for PSHUFHW");
4582 unsigned NumElts = VT.getVectorNumElements();
4585 for (unsigned l = 0; l != NumElts; l += 8) {
4586 // 8 nodes per lane, but we only care about the first 4.
4587 for (unsigned i = 0; i < 4; ++i) {
4588 int Elt = N->getMaskElt(l+i);
4589 if (Elt < 0) continue;
4590 Elt &= 0x3; // only 2-bits
4591 Mask |= Elt << (i * 2);
4598 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4599 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4600 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4601 MVT VT = SVOp->getSimpleValueType(0);
4602 unsigned EltSize = VT.is512BitVector() ? 1 :
4603 VT.getVectorElementType().getSizeInBits() >> 3;
4605 unsigned NumElts = VT.getVectorNumElements();
4606 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4607 unsigned NumLaneElts = NumElts/NumLanes;
4611 for (i = 0; i != NumElts; ++i) {
4612 Val = SVOp->getMaskElt(i);
4616 if (Val >= (int)NumElts)
4617 Val -= NumElts - NumLaneElts;
4619 assert(Val - i > 0 && "PALIGNR imm should be positive");
4620 return (Val - i) * EltSize;
4623 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4624 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4625 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4626 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4629 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4631 MVT VecVT = N->getOperand(0).getSimpleValueType();
4632 MVT ElVT = VecVT.getVectorElementType();
4634 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4635 return Index / NumElemsPerChunk;
4638 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4639 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4640 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4641 llvm_unreachable("Illegal insert subvector for VINSERT");
4644 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4646 MVT VecVT = N->getSimpleValueType(0);
4647 MVT ElVT = VecVT.getVectorElementType();
4649 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4650 return Index / NumElemsPerChunk;
4653 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4654 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4655 /// and VINSERTI128 instructions.
4656 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4657 return getExtractVEXTRACTImmediate(N, 128);
4660 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4661 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4662 /// and VINSERTI64x4 instructions.
4663 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4664 return getExtractVEXTRACTImmediate(N, 256);
4667 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4668 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4669 /// and VINSERTI128 instructions.
4670 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4671 return getInsertVINSERTImmediate(N, 128);
4674 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4675 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4676 /// and VINSERTI64x4 instructions.
4677 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4678 return getInsertVINSERTImmediate(N, 256);
4681 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4683 bool X86::isZeroNode(SDValue Elt) {
4684 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4685 return CN->isNullValue();
4686 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4687 return CFP->getValueAPF().isPosZero();
4691 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4692 /// their permute mask.
4693 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4694 SelectionDAG &DAG) {
4695 MVT VT = SVOp->getSimpleValueType(0);
4696 unsigned NumElems = VT.getVectorNumElements();
4697 SmallVector<int, 8> MaskVec;
4699 for (unsigned i = 0; i != NumElems; ++i) {
4700 int Idx = SVOp->getMaskElt(i);
4702 if (Idx < (int)NumElems)
4707 MaskVec.push_back(Idx);
4709 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4710 SVOp->getOperand(0), &MaskVec[0]);
4713 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4714 /// match movhlps. The lower half elements should come from upper half of
4715 /// V1 (and in order), and the upper half elements should come from the upper
4716 /// half of V2 (and in order).
4717 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4718 if (!VT.is128BitVector())
4720 if (VT.getVectorNumElements() != 4)
4722 for (unsigned i = 0, e = 2; i != e; ++i)
4723 if (!isUndefOrEqual(Mask[i], i+2))
4725 for (unsigned i = 2; i != 4; ++i)
4726 if (!isUndefOrEqual(Mask[i], i+4))
4731 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4732 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4734 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4735 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4737 N = N->getOperand(0).getNode();
4738 if (!ISD::isNON_EXTLoad(N))
4741 *LD = cast<LoadSDNode>(N);
4745 // Test whether the given value is a vector value which will be legalized
4747 static bool WillBeConstantPoolLoad(SDNode *N) {
4748 if (N->getOpcode() != ISD::BUILD_VECTOR)
4751 // Check for any non-constant elements.
4752 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4753 switch (N->getOperand(i).getNode()->getOpcode()) {
4755 case ISD::ConstantFP:
4762 // Vectors of all-zeros and all-ones are materialized with special
4763 // instructions rather than being loaded.
4764 return !ISD::isBuildVectorAllZeros(N) &&
4765 !ISD::isBuildVectorAllOnes(N);
4768 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4769 /// match movlp{s|d}. The lower half elements should come from lower half of
4770 /// V1 (and in order), and the upper half elements should come from the upper
4771 /// half of V2 (and in order). And since V1 will become the source of the
4772 /// MOVLP, it must be either a vector load or a scalar load to vector.
4773 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4774 ArrayRef<int> Mask, MVT VT) {
4775 if (!VT.is128BitVector())
4778 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4780 // Is V2 is a vector load, don't do this transformation. We will try to use
4781 // load folding shufps op.
4782 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4785 unsigned NumElems = VT.getVectorNumElements();
4787 if (NumElems != 2 && NumElems != 4)
4789 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4790 if (!isUndefOrEqual(Mask[i], i))
4792 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4793 if (!isUndefOrEqual(Mask[i], i+NumElems))
4798 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4800 static bool isSplatVector(SDNode *N) {
4801 if (N->getOpcode() != ISD::BUILD_VECTOR)
4804 SDValue SplatValue = N->getOperand(0);
4805 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4806 if (N->getOperand(i) != SplatValue)
4811 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4812 /// to an zero vector.
4813 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4814 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4815 SDValue V1 = N->getOperand(0);
4816 SDValue V2 = N->getOperand(1);
4817 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4818 for (unsigned i = 0; i != NumElems; ++i) {
4819 int Idx = N->getMaskElt(i);
4820 if (Idx >= (int)NumElems) {
4821 unsigned Opc = V2.getOpcode();
4822 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4824 if (Opc != ISD::BUILD_VECTOR ||
4825 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4827 } else if (Idx >= 0) {
4828 unsigned Opc = V1.getOpcode();
4829 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4831 if (Opc != ISD::BUILD_VECTOR ||
4832 !X86::isZeroNode(V1.getOperand(Idx)))
4839 /// getZeroVector - Returns a vector of specified type with all zero elements.
4841 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4842 SelectionDAG &DAG, SDLoc dl) {
4843 assert(VT.isVector() && "Expected a vector type");
4845 // Always build SSE zero vectors as <4 x i32> bitcasted
4846 // to their dest type. This ensures they get CSE'd.
4848 if (VT.is128BitVector()) { // SSE
4849 if (Subtarget->hasSSE2()) { // SSE2
4850 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4851 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4853 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4854 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4856 } else if (VT.is256BitVector()) { // AVX
4857 if (Subtarget->hasInt256()) { // AVX2
4858 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4859 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4860 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4862 // 256-bit logic and arithmetic instructions in AVX are all
4863 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4864 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4865 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4866 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4868 } else if (VT.is512BitVector()) { // AVX-512
4869 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4870 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4871 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4872 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4873 } else if (VT.getScalarType() == MVT::i1) {
4874 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4875 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4876 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4877 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4879 llvm_unreachable("Unexpected vector type");
4881 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4884 /// getOnesVector - Returns a vector of specified type with all bits set.
4885 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4886 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4887 /// Then bitcast to their original type, ensuring they get CSE'd.
4888 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4890 assert(VT.isVector() && "Expected a vector type");
4892 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4894 if (VT.is256BitVector()) {
4895 if (HasInt256) { // AVX2
4896 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4897 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4899 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4900 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4902 } else if (VT.is128BitVector()) {
4903 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4905 llvm_unreachable("Unexpected vector type");
4907 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4910 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4911 /// that point to V2 points to its first element.
4912 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4913 for (unsigned i = 0; i != NumElems; ++i) {
4914 if (Mask[i] > (int)NumElems) {
4920 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4921 /// operation of specified width.
4922 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4924 unsigned NumElems = VT.getVectorNumElements();
4925 SmallVector<int, 8> Mask;
4926 Mask.push_back(NumElems);
4927 for (unsigned i = 1; i != NumElems; ++i)
4929 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4932 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4933 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4935 unsigned NumElems = VT.getVectorNumElements();
4936 SmallVector<int, 8> Mask;
4937 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4939 Mask.push_back(i + NumElems);
4941 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4944 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4945 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4947 unsigned NumElems = VT.getVectorNumElements();
4948 SmallVector<int, 8> Mask;
4949 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4950 Mask.push_back(i + Half);
4951 Mask.push_back(i + NumElems + Half);
4953 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4956 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4957 // a generic shuffle instruction because the target has no such instructions.
4958 // Generate shuffles which repeat i16 and i8 several times until they can be
4959 // represented by v4f32 and then be manipulated by target suported shuffles.
4960 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4961 MVT VT = V.getSimpleValueType();
4962 int NumElems = VT.getVectorNumElements();
4965 while (NumElems > 4) {
4966 if (EltNo < NumElems/2) {
4967 V = getUnpackl(DAG, dl, VT, V, V);
4969 V = getUnpackh(DAG, dl, VT, V, V);
4970 EltNo -= NumElems/2;
4977 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4978 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4979 MVT VT = V.getSimpleValueType();
4982 if (VT.is128BitVector()) {
4983 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4984 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4985 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4987 } else if (VT.is256BitVector()) {
4988 // To use VPERMILPS to splat scalars, the second half of indicies must
4989 // refer to the higher part, which is a duplication of the lower one,
4990 // because VPERMILPS can only handle in-lane permutations.
4991 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4992 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4994 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4995 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4998 llvm_unreachable("Vector size not supported");
5000 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5003 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5004 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5005 MVT SrcVT = SV->getSimpleValueType(0);
5006 SDValue V1 = SV->getOperand(0);
5009 int EltNo = SV->getSplatIndex();
5010 int NumElems = SrcVT.getVectorNumElements();
5011 bool Is256BitVec = SrcVT.is256BitVector();
5013 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5014 "Unknown how to promote splat for type");
5016 // Extract the 128-bit part containing the splat element and update
5017 // the splat element index when it refers to the higher register.
5019 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5020 if (EltNo >= NumElems/2)
5021 EltNo -= NumElems/2;
5024 // All i16 and i8 vector types can't be used directly by a generic shuffle
5025 // instruction because the target has no such instruction. Generate shuffles
5026 // which repeat i16 and i8 several times until they fit in i32, and then can
5027 // be manipulated by target suported shuffles.
5028 MVT EltVT = SrcVT.getVectorElementType();
5029 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5030 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5032 // Recreate the 256-bit vector and place the same 128-bit vector
5033 // into the low and high part. This is necessary because we want
5034 // to use VPERM* to shuffle the vectors
5036 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5039 return getLegalSplat(DAG, V1, EltNo);
5042 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5043 /// vector of zero or undef vector. This produces a shuffle where the low
5044 /// element of V2 is swizzled into the zero/undef vector, landing at element
5045 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5046 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5048 const X86Subtarget *Subtarget,
5049 SelectionDAG &DAG) {
5050 MVT VT = V2.getSimpleValueType();
5052 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5053 unsigned NumElems = VT.getVectorNumElements();
5054 SmallVector<int, 16> MaskVec;
5055 for (unsigned i = 0; i != NumElems; ++i)
5056 // If this is the insertion idx, put the low elt of V2 here.
5057 MaskVec.push_back(i == Idx ? NumElems : i);
5058 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5061 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5062 /// target specific opcode. Returns true if the Mask could be calculated.
5063 /// Sets IsUnary to true if only uses one source.
5064 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5065 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5066 unsigned NumElems = VT.getVectorNumElements();
5070 switch(N->getOpcode()) {
5072 ImmN = N->getOperand(N->getNumOperands()-1);
5073 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5075 case X86ISD::UNPCKH:
5076 DecodeUNPCKHMask(VT, Mask);
5078 case X86ISD::UNPCKL:
5079 DecodeUNPCKLMask(VT, Mask);
5081 case X86ISD::MOVHLPS:
5082 DecodeMOVHLPSMask(NumElems, Mask);
5084 case X86ISD::MOVLHPS:
5085 DecodeMOVLHPSMask(NumElems, Mask);
5087 case X86ISD::PALIGNR:
5088 ImmN = N->getOperand(N->getNumOperands()-1);
5089 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5091 case X86ISD::PSHUFD:
5092 case X86ISD::VPERMILP:
5093 ImmN = N->getOperand(N->getNumOperands()-1);
5094 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5097 case X86ISD::PSHUFHW:
5098 ImmN = N->getOperand(N->getNumOperands()-1);
5099 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5102 case X86ISD::PSHUFLW:
5103 ImmN = N->getOperand(N->getNumOperands()-1);
5104 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5107 case X86ISD::VPERMI:
5108 ImmN = N->getOperand(N->getNumOperands()-1);
5109 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5113 case X86ISD::MOVSD: {
5114 // The index 0 always comes from the first element of the second source,
5115 // this is why MOVSS and MOVSD are used in the first place. The other
5116 // elements come from the other positions of the first source vector
5117 Mask.push_back(NumElems);
5118 for (unsigned i = 1; i != NumElems; ++i) {
5123 case X86ISD::VPERM2X128:
5124 ImmN = N->getOperand(N->getNumOperands()-1);
5125 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5126 if (Mask.empty()) return false;
5128 case X86ISD::MOVDDUP:
5129 case X86ISD::MOVLHPD:
5130 case X86ISD::MOVLPD:
5131 case X86ISD::MOVLPS:
5132 case X86ISD::MOVSHDUP:
5133 case X86ISD::MOVSLDUP:
5134 // Not yet implemented
5136 default: llvm_unreachable("unknown target shuffle node");
5142 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5143 /// element of the result of the vector shuffle.
5144 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5147 return SDValue(); // Limit search depth.
5149 SDValue V = SDValue(N, 0);
5150 EVT VT = V.getValueType();
5151 unsigned Opcode = V.getOpcode();
5153 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5154 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5155 int Elt = SV->getMaskElt(Index);
5158 return DAG.getUNDEF(VT.getVectorElementType());
5160 unsigned NumElems = VT.getVectorNumElements();
5161 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5162 : SV->getOperand(1);
5163 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5166 // Recurse into target specific vector shuffles to find scalars.
5167 if (isTargetShuffle(Opcode)) {
5168 MVT ShufVT = V.getSimpleValueType();
5169 unsigned NumElems = ShufVT.getVectorNumElements();
5170 SmallVector<int, 16> ShuffleMask;
5173 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5176 int Elt = ShuffleMask[Index];
5178 return DAG.getUNDEF(ShufVT.getVectorElementType());
5180 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5182 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5186 // Actual nodes that may contain scalar elements
5187 if (Opcode == ISD::BITCAST) {
5188 V = V.getOperand(0);
5189 EVT SrcVT = V.getValueType();
5190 unsigned NumElems = VT.getVectorNumElements();
5192 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5196 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5197 return (Index == 0) ? V.getOperand(0)
5198 : DAG.getUNDEF(VT.getVectorElementType());
5200 if (V.getOpcode() == ISD::BUILD_VECTOR)
5201 return V.getOperand(Index);
5206 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5207 /// shuffle operation which come from a consecutively from a zero. The
5208 /// search can start in two different directions, from left or right.
5209 /// We count undefs as zeros until PreferredNum is reached.
5210 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5211 unsigned NumElems, bool ZerosFromLeft,
5213 unsigned PreferredNum = -1U) {
5214 unsigned NumZeros = 0;
5215 for (unsigned i = 0; i != NumElems; ++i) {
5216 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5217 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5221 if (X86::isZeroNode(Elt))
5223 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5224 NumZeros = std::min(NumZeros + 1, PreferredNum);
5232 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5233 /// correspond consecutively to elements from one of the vector operands,
5234 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5236 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5237 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5238 unsigned NumElems, unsigned &OpNum) {
5239 bool SeenV1 = false;
5240 bool SeenV2 = false;
5242 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5243 int Idx = SVOp->getMaskElt(i);
5244 // Ignore undef indicies
5248 if (Idx < (int)NumElems)
5253 // Only accept consecutive elements from the same vector
5254 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5258 OpNum = SeenV1 ? 0 : 1;
5262 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5263 /// logical left shift of a vector.
5264 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5265 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5267 SVOp->getSimpleValueType(0).getVectorNumElements();
5268 unsigned NumZeros = getNumOfConsecutiveZeros(
5269 SVOp, NumElems, false /* check zeros from right */, DAG,
5270 SVOp->getMaskElt(0));
5276 // Considering the elements in the mask that are not consecutive zeros,
5277 // check if they consecutively come from only one of the source vectors.
5279 // V1 = {X, A, B, C} 0
5281 // vector_shuffle V1, V2 <1, 2, 3, X>
5283 if (!isShuffleMaskConsecutive(SVOp,
5284 0, // Mask Start Index
5285 NumElems-NumZeros, // Mask End Index(exclusive)
5286 NumZeros, // Where to start looking in the src vector
5287 NumElems, // Number of elements in vector
5288 OpSrc)) // Which source operand ?
5293 ShVal = SVOp->getOperand(OpSrc);
5297 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5298 /// logical left shift of a vector.
5299 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5300 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5302 SVOp->getSimpleValueType(0).getVectorNumElements();
5303 unsigned NumZeros = getNumOfConsecutiveZeros(
5304 SVOp, NumElems, true /* check zeros from left */, DAG,
5305 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5311 // Considering the elements in the mask that are not consecutive zeros,
5312 // check if they consecutively come from only one of the source vectors.
5314 // 0 { A, B, X, X } = V2
5316 // vector_shuffle V1, V2 <X, X, 4, 5>
5318 if (!isShuffleMaskConsecutive(SVOp,
5319 NumZeros, // Mask Start Index
5320 NumElems, // Mask End Index(exclusive)
5321 0, // Where to start looking in the src vector
5322 NumElems, // Number of elements in vector
5323 OpSrc)) // Which source operand ?
5328 ShVal = SVOp->getOperand(OpSrc);
5332 /// isVectorShift - Returns true if the shuffle can be implemented as a
5333 /// logical left or right shift of a vector.
5334 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5335 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5336 // Although the logic below support any bitwidth size, there are no
5337 // shift instructions which handle more than 128-bit vectors.
5338 if (!SVOp->getSimpleValueType(0).is128BitVector())
5341 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5342 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5348 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5350 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5351 unsigned NumNonZero, unsigned NumZero,
5353 const X86Subtarget* Subtarget,
5354 const TargetLowering &TLI) {
5361 for (unsigned i = 0; i < 16; ++i) {
5362 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5363 if (ThisIsNonZero && First) {
5365 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5367 V = DAG.getUNDEF(MVT::v8i16);
5372 SDValue ThisElt, LastElt;
5373 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5374 if (LastIsNonZero) {
5375 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5376 MVT::i16, Op.getOperand(i-1));
5378 if (ThisIsNonZero) {
5379 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5380 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5381 ThisElt, DAG.getConstant(8, MVT::i8));
5383 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5387 if (ThisElt.getNode())
5388 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5389 DAG.getIntPtrConstant(i/2));
5393 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5396 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5398 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5399 unsigned NumNonZero, unsigned NumZero,
5401 const X86Subtarget* Subtarget,
5402 const TargetLowering &TLI) {
5409 for (unsigned i = 0; i < 8; ++i) {
5410 bool isNonZero = (NonZeros & (1 << i)) != 0;
5414 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5416 V = DAG.getUNDEF(MVT::v8i16);
5419 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5420 MVT::v8i16, V, Op.getOperand(i),
5421 DAG.getIntPtrConstant(i));
5428 /// getVShift - Return a vector logical shift node.
5430 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5431 unsigned NumBits, SelectionDAG &DAG,
5432 const TargetLowering &TLI, SDLoc dl) {
5433 assert(VT.is128BitVector() && "Unknown type for VShift");
5434 EVT ShVT = MVT::v2i64;
5435 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5436 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5437 return DAG.getNode(ISD::BITCAST, dl, VT,
5438 DAG.getNode(Opc, dl, ShVT, SrcOp,
5439 DAG.getConstant(NumBits,
5440 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5444 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5446 // Check if the scalar load can be widened into a vector load. And if
5447 // the address is "base + cst" see if the cst can be "absorbed" into
5448 // the shuffle mask.
5449 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5450 SDValue Ptr = LD->getBasePtr();
5451 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5453 EVT PVT = LD->getValueType(0);
5454 if (PVT != MVT::i32 && PVT != MVT::f32)
5459 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5460 FI = FINode->getIndex();
5462 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5463 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5464 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5465 Offset = Ptr.getConstantOperandVal(1);
5466 Ptr = Ptr.getOperand(0);
5471 // FIXME: 256-bit vector instructions don't require a strict alignment,
5472 // improve this code to support it better.
5473 unsigned RequiredAlign = VT.getSizeInBits()/8;
5474 SDValue Chain = LD->getChain();
5475 // Make sure the stack object alignment is at least 16 or 32.
5476 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5477 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5478 if (MFI->isFixedObjectIndex(FI)) {
5479 // Can't change the alignment. FIXME: It's possible to compute
5480 // the exact stack offset and reference FI + adjust offset instead.
5481 // If someone *really* cares about this. That's the way to implement it.
5484 MFI->setObjectAlignment(FI, RequiredAlign);
5488 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5489 // Ptr + (Offset & ~15).
5492 if ((Offset % RequiredAlign) & 3)
5494 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5496 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5497 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5499 int EltNo = (Offset - StartOffset) >> 2;
5500 unsigned NumElems = VT.getVectorNumElements();
5502 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5503 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5504 LD->getPointerInfo().getWithOffset(StartOffset),
5505 false, false, false, 0);
5507 SmallVector<int, 8> Mask;
5508 for (unsigned i = 0; i != NumElems; ++i)
5509 Mask.push_back(EltNo);
5511 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5517 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5518 /// vector of type 'VT', see if the elements can be replaced by a single large
5519 /// load which has the same value as a build_vector whose operands are 'elts'.
5521 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5523 /// FIXME: we'd also like to handle the case where the last elements are zero
5524 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5525 /// There's even a handy isZeroNode for that purpose.
5526 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5527 SDLoc &DL, SelectionDAG &DAG,
5528 bool isAfterLegalize) {
5529 EVT EltVT = VT.getVectorElementType();
5530 unsigned NumElems = Elts.size();
5532 LoadSDNode *LDBase = nullptr;
5533 unsigned LastLoadedElt = -1U;
5535 // For each element in the initializer, see if we've found a load or an undef.
5536 // If we don't find an initial load element, or later load elements are
5537 // non-consecutive, bail out.
5538 for (unsigned i = 0; i < NumElems; ++i) {
5539 SDValue Elt = Elts[i];
5541 if (!Elt.getNode() ||
5542 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5545 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5547 LDBase = cast<LoadSDNode>(Elt.getNode());
5551 if (Elt.getOpcode() == ISD::UNDEF)
5554 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5555 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5560 // If we have found an entire vector of loads and undefs, then return a large
5561 // load of the entire vector width starting at the base pointer. If we found
5562 // consecutive loads for the low half, generate a vzext_load node.
5563 if (LastLoadedElt == NumElems - 1) {
5565 if (isAfterLegalize &&
5566 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5569 SDValue NewLd = SDValue();
5571 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5572 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5573 LDBase->getPointerInfo(),
5574 LDBase->isVolatile(), LDBase->isNonTemporal(),
5575 LDBase->isInvariant(), 0);
5576 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5577 LDBase->getPointerInfo(),
5578 LDBase->isVolatile(), LDBase->isNonTemporal(),
5579 LDBase->isInvariant(), LDBase->getAlignment());
5581 if (LDBase->hasAnyUseOfValue(1)) {
5582 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5584 SDValue(NewLd.getNode(), 1));
5585 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5586 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5587 SDValue(NewLd.getNode(), 1));
5592 if (NumElems == 4 && LastLoadedElt == 1 &&
5593 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5594 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5595 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5597 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5598 LDBase->getPointerInfo(),
5599 LDBase->getAlignment(),
5600 false/*isVolatile*/, true/*ReadMem*/,
5603 // Make sure the newly-created LOAD is in the same position as LDBase in
5604 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5605 // update uses of LDBase's output chain to use the TokenFactor.
5606 if (LDBase->hasAnyUseOfValue(1)) {
5607 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5608 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5609 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5610 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5611 SDValue(ResNode.getNode(), 1));
5614 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5619 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5620 /// to generate a splat value for the following cases:
5621 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5622 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5623 /// a scalar load, or a constant.
5624 /// The VBROADCAST node is returned when a pattern is found,
5625 /// or SDValue() otherwise.
5626 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5627 SelectionDAG &DAG) {
5628 if (!Subtarget->hasFp256())
5631 MVT VT = Op.getSimpleValueType();
5634 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5635 "Unsupported vector type for broadcast.");
5640 switch (Op.getOpcode()) {
5642 // Unknown pattern found.
5645 case ISD::BUILD_VECTOR: {
5646 // The BUILD_VECTOR node must be a splat.
5647 if (!isSplatVector(Op.getNode()))
5650 Ld = Op.getOperand(0);
5651 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5652 Ld.getOpcode() == ISD::ConstantFP);
5654 // The suspected load node has several users. Make sure that all
5655 // of its users are from the BUILD_VECTOR node.
5656 // Constants may have multiple users.
5657 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5662 case ISD::VECTOR_SHUFFLE: {
5663 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5665 // Shuffles must have a splat mask where the first element is
5667 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5670 SDValue Sc = Op.getOperand(0);
5671 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5672 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5674 if (!Subtarget->hasInt256())
5677 // Use the register form of the broadcast instruction available on AVX2.
5678 if (VT.getSizeInBits() >= 256)
5679 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5680 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5683 Ld = Sc.getOperand(0);
5684 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5685 Ld.getOpcode() == ISD::ConstantFP);
5687 // The scalar_to_vector node and the suspected
5688 // load node must have exactly one user.
5689 // Constants may have multiple users.
5691 // AVX-512 has register version of the broadcast
5692 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5693 Ld.getValueType().getSizeInBits() >= 32;
5694 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5701 bool IsGE256 = (VT.getSizeInBits() >= 256);
5703 // Handle the broadcasting a single constant scalar from the constant pool
5704 // into a vector. On Sandybridge it is still better to load a constant vector
5705 // from the constant pool and not to broadcast it from a scalar.
5706 if (ConstSplatVal && Subtarget->hasInt256()) {
5707 EVT CVT = Ld.getValueType();
5708 assert(!CVT.isVector() && "Must not broadcast a vector type");
5709 unsigned ScalarSize = CVT.getSizeInBits();
5711 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5712 const Constant *C = nullptr;
5713 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5714 C = CI->getConstantIntValue();
5715 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5716 C = CF->getConstantFPValue();
5718 assert(C && "Invalid constant type");
5720 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5721 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5722 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5723 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5724 MachinePointerInfo::getConstantPool(),
5725 false, false, false, Alignment);
5727 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5731 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5732 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5734 // Handle AVX2 in-register broadcasts.
5735 if (!IsLoad && Subtarget->hasInt256() &&
5736 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5737 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5739 // The scalar source must be a normal load.
5743 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5744 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5746 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5747 // double since there is no vbroadcastsd xmm
5748 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5749 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5750 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5753 // Unsupported broadcast.
5757 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5758 /// underlying vector and index.
5760 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5762 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5764 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5765 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5768 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5770 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5772 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5773 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5776 // In this case the vector is the extract_subvector expression and the index
5777 // is 2, as specified by the shuffle.
5778 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5779 SDValue ShuffleVec = SVOp->getOperand(0);
5780 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5781 assert(ShuffleVecVT.getVectorElementType() ==
5782 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5784 int ShuffleIdx = SVOp->getMaskElt(Idx);
5785 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5786 ExtractedFromVec = ShuffleVec;
5792 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5793 MVT VT = Op.getSimpleValueType();
5795 // Skip if insert_vec_elt is not supported.
5796 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5797 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5801 unsigned NumElems = Op.getNumOperands();
5805 SmallVector<unsigned, 4> InsertIndices;
5806 SmallVector<int, 8> Mask(NumElems, -1);
5808 for (unsigned i = 0; i != NumElems; ++i) {
5809 unsigned Opc = Op.getOperand(i).getOpcode();
5811 if (Opc == ISD::UNDEF)
5814 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5815 // Quit if more than 1 elements need inserting.
5816 if (InsertIndices.size() > 1)
5819 InsertIndices.push_back(i);
5823 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5824 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5825 // Quit if non-constant index.
5826 if (!isa<ConstantSDNode>(ExtIdx))
5828 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5830 // Quit if extracted from vector of different type.
5831 if (ExtractedFromVec.getValueType() != VT)
5834 if (!VecIn1.getNode())
5835 VecIn1 = ExtractedFromVec;
5836 else if (VecIn1 != ExtractedFromVec) {
5837 if (!VecIn2.getNode())
5838 VecIn2 = ExtractedFromVec;
5839 else if (VecIn2 != ExtractedFromVec)
5840 // Quit if more than 2 vectors to shuffle
5844 if (ExtractedFromVec == VecIn1)
5846 else if (ExtractedFromVec == VecIn2)
5847 Mask[i] = Idx + NumElems;
5850 if (!VecIn1.getNode())
5853 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5854 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5855 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5856 unsigned Idx = InsertIndices[i];
5857 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5858 DAG.getIntPtrConstant(Idx));
5864 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5866 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5868 MVT VT = Op.getSimpleValueType();
5869 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5870 "Unexpected type in LowerBUILD_VECTORvXi1!");
5873 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5874 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5875 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5876 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5879 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5880 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5881 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5882 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5885 bool AllContants = true;
5886 uint64_t Immediate = 0;
5887 int NonConstIdx = -1;
5888 bool IsSplat = true;
5889 unsigned NumNonConsts = 0;
5890 unsigned NumConsts = 0;
5891 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5892 SDValue In = Op.getOperand(idx);
5893 if (In.getOpcode() == ISD::UNDEF)
5895 if (!isa<ConstantSDNode>(In)) {
5896 AllContants = false;
5902 if (cast<ConstantSDNode>(In)->getZExtValue())
5903 Immediate |= (1ULL << idx);
5905 if (In != Op.getOperand(0))
5910 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5911 DAG.getConstant(Immediate, MVT::i16));
5912 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5913 DAG.getIntPtrConstant(0));
5916 if (NumNonConsts == 1 && NonConstIdx != 0) {
5919 SDValue VecAsImm = DAG.getConstant(Immediate,
5920 MVT::getIntegerVT(VT.getSizeInBits()));
5921 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5924 DstVec = DAG.getUNDEF(VT);
5925 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5926 Op.getOperand(NonConstIdx),
5927 DAG.getIntPtrConstant(NonConstIdx));
5929 if (!IsSplat && (NonConstIdx != 0))
5930 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5931 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5934 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5935 DAG.getConstant(-1, SelectVT),
5936 DAG.getConstant(0, SelectVT));
5938 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5939 DAG.getConstant((Immediate | 1), SelectVT),
5940 DAG.getConstant(Immediate, SelectVT));
5941 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5945 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5948 MVT VT = Op.getSimpleValueType();
5949 MVT ExtVT = VT.getVectorElementType();
5950 unsigned NumElems = Op.getNumOperands();
5952 // Generate vectors for predicate vectors.
5953 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5954 return LowerBUILD_VECTORvXi1(Op, DAG);
5956 // Vectors containing all zeros can be matched by pxor and xorps later
5957 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5958 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5959 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5960 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5963 return getZeroVector(VT, Subtarget, DAG, dl);
5966 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5967 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5968 // vpcmpeqd on 256-bit vectors.
5969 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5970 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5973 if (!VT.is512BitVector())
5974 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5977 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5978 if (Broadcast.getNode())
5981 unsigned EVTBits = ExtVT.getSizeInBits();
5983 unsigned NumZero = 0;
5984 unsigned NumNonZero = 0;
5985 unsigned NonZeros = 0;
5986 bool IsAllConstants = true;
5987 SmallSet<SDValue, 8> Values;
5988 for (unsigned i = 0; i < NumElems; ++i) {
5989 SDValue Elt = Op.getOperand(i);
5990 if (Elt.getOpcode() == ISD::UNDEF)
5993 if (Elt.getOpcode() != ISD::Constant &&
5994 Elt.getOpcode() != ISD::ConstantFP)
5995 IsAllConstants = false;
5996 if (X86::isZeroNode(Elt))
5999 NonZeros |= (1 << i);
6004 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6005 if (NumNonZero == 0)
6006 return DAG.getUNDEF(VT);
6008 // Special case for single non-zero, non-undef, element.
6009 if (NumNonZero == 1) {
6010 unsigned Idx = countTrailingZeros(NonZeros);
6011 SDValue Item = Op.getOperand(Idx);
6013 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6014 // the value are obviously zero, truncate the value to i32 and do the
6015 // insertion that way. Only do this if the value is non-constant or if the
6016 // value is a constant being inserted into element 0. It is cheaper to do
6017 // a constant pool load than it is to do a movd + shuffle.
6018 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6019 (!IsAllConstants || Idx == 0)) {
6020 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6022 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6023 EVT VecVT = MVT::v4i32;
6024 unsigned VecElts = 4;
6026 // Truncate the value (which may itself be a constant) to i32, and
6027 // convert it to a vector with movd (S2V+shuffle to zero extend).
6028 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6029 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6030 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6032 // Now we have our 32-bit value zero extended in the low element of
6033 // a vector. If Idx != 0, swizzle it into place.
6035 SmallVector<int, 4> Mask;
6036 Mask.push_back(Idx);
6037 for (unsigned i = 1; i != VecElts; ++i)
6039 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6042 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6046 // If we have a constant or non-constant insertion into the low element of
6047 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6048 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6049 // depending on what the source datatype is.
6052 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6054 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6055 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6056 if (VT.is256BitVector() || VT.is512BitVector()) {
6057 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6058 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6059 Item, DAG.getIntPtrConstant(0));
6061 assert(VT.is128BitVector() && "Expected an SSE value type!");
6062 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6063 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6064 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6067 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6068 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6069 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6070 if (VT.is256BitVector()) {
6071 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6072 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6074 assert(VT.is128BitVector() && "Expected an SSE value type!");
6075 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6077 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6081 // Is it a vector logical left shift?
6082 if (NumElems == 2 && Idx == 1 &&
6083 X86::isZeroNode(Op.getOperand(0)) &&
6084 !X86::isZeroNode(Op.getOperand(1))) {
6085 unsigned NumBits = VT.getSizeInBits();
6086 return getVShift(true, VT,
6087 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6088 VT, Op.getOperand(1)),
6089 NumBits/2, DAG, *this, dl);
6092 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6095 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6096 // is a non-constant being inserted into an element other than the low one,
6097 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6098 // movd/movss) to move this into the low element, then shuffle it into
6100 if (EVTBits == 32) {
6101 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6103 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6104 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6105 SmallVector<int, 8> MaskVec;
6106 for (unsigned i = 0; i != NumElems; ++i)
6107 MaskVec.push_back(i == Idx ? 0 : 1);
6108 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6112 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6113 if (Values.size() == 1) {
6114 if (EVTBits == 32) {
6115 // Instead of a shuffle like this:
6116 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6117 // Check if it's possible to issue this instead.
6118 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6119 unsigned Idx = countTrailingZeros(NonZeros);
6120 SDValue Item = Op.getOperand(Idx);
6121 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6122 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6127 // A vector full of immediates; various special cases are already
6128 // handled, so this is best done with a single constant-pool load.
6132 // For AVX-length vectors, build the individual 128-bit pieces and use
6133 // shuffles to put them in place.
6134 if (VT.is256BitVector() || VT.is512BitVector()) {
6135 SmallVector<SDValue, 64> V;
6136 for (unsigned i = 0; i != NumElems; ++i)
6137 V.push_back(Op.getOperand(i));
6139 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6141 // Build both the lower and upper subvector.
6142 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6143 ArrayRef<SDValue>(&V[0], NumElems/2));
6144 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6145 ArrayRef<SDValue>(&V[NumElems / 2],
6148 // Recreate the wider vector with the lower and upper part.
6149 if (VT.is256BitVector())
6150 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6151 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6154 // Let legalizer expand 2-wide build_vectors.
6155 if (EVTBits == 64) {
6156 if (NumNonZero == 1) {
6157 // One half is zero or undef.
6158 unsigned Idx = countTrailingZeros(NonZeros);
6159 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6160 Op.getOperand(Idx));
6161 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6166 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6167 if (EVTBits == 8 && NumElems == 16) {
6168 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6170 if (V.getNode()) return V;
6173 if (EVTBits == 16 && NumElems == 8) {
6174 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6176 if (V.getNode()) return V;
6179 // If element VT is == 32 bits, turn it into a number of shuffles.
6180 SmallVector<SDValue, 8> V(NumElems);
6181 if (NumElems == 4 && NumZero > 0) {
6182 for (unsigned i = 0; i < 4; ++i) {
6183 bool isZero = !(NonZeros & (1 << i));
6185 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6187 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6190 for (unsigned i = 0; i < 2; ++i) {
6191 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6194 V[i] = V[i*2]; // Must be a zero vector.
6197 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6200 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6203 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6208 bool Reverse1 = (NonZeros & 0x3) == 2;
6209 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6213 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6214 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6216 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6219 if (Values.size() > 1 && VT.is128BitVector()) {
6220 // Check for a build vector of consecutive loads.
6221 for (unsigned i = 0; i < NumElems; ++i)
6222 V[i] = Op.getOperand(i);
6224 // Check for elements which are consecutive loads.
6225 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6229 // Check for a build vector from mostly shuffle plus few inserting.
6230 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6234 // For SSE 4.1, use insertps to put the high elements into the low element.
6235 if (getSubtarget()->hasSSE41()) {
6237 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6238 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6240 Result = DAG.getUNDEF(VT);
6242 for (unsigned i = 1; i < NumElems; ++i) {
6243 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6244 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6245 Op.getOperand(i), DAG.getIntPtrConstant(i));
6250 // Otherwise, expand into a number of unpckl*, start by extending each of
6251 // our (non-undef) elements to the full vector width with the element in the
6252 // bottom slot of the vector (which generates no code for SSE).
6253 for (unsigned i = 0; i < NumElems; ++i) {
6254 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6255 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6257 V[i] = DAG.getUNDEF(VT);
6260 // Next, we iteratively mix elements, e.g. for v4f32:
6261 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6262 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6263 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6264 unsigned EltStride = NumElems >> 1;
6265 while (EltStride != 0) {
6266 for (unsigned i = 0; i < EltStride; ++i) {
6267 // If V[i+EltStride] is undef and this is the first round of mixing,
6268 // then it is safe to just drop this shuffle: V[i] is already in the
6269 // right place, the one element (since it's the first round) being
6270 // inserted as undef can be dropped. This isn't safe for successive
6271 // rounds because they will permute elements within both vectors.
6272 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6273 EltStride == NumElems/2)
6276 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6285 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6286 // to create 256-bit vectors from two other 128-bit ones.
6287 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6289 MVT ResVT = Op.getSimpleValueType();
6291 assert((ResVT.is256BitVector() ||
6292 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6294 SDValue V1 = Op.getOperand(0);
6295 SDValue V2 = Op.getOperand(1);
6296 unsigned NumElems = ResVT.getVectorNumElements();
6297 if(ResVT.is256BitVector())
6298 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6300 if (Op.getNumOperands() == 4) {
6301 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6302 ResVT.getVectorNumElements()/2);
6303 SDValue V3 = Op.getOperand(2);
6304 SDValue V4 = Op.getOperand(3);
6305 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6306 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6308 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6311 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6312 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6313 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6314 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6315 Op.getNumOperands() == 4)));
6317 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6318 // from two other 128-bit ones.
6320 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6321 return LowerAVXCONCAT_VECTORS(Op, DAG);
6324 // Try to lower a shuffle node into a simple blend instruction.
6326 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6327 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6328 SDValue V1 = SVOp->getOperand(0);
6329 SDValue V2 = SVOp->getOperand(1);
6331 MVT VT = SVOp->getSimpleValueType(0);
6332 MVT EltVT = VT.getVectorElementType();
6333 unsigned NumElems = VT.getVectorNumElements();
6335 // There is no blend with immediate in AVX-512.
6336 if (VT.is512BitVector())
6339 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6341 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6344 // Check the mask for BLEND and build the value.
6345 unsigned MaskValue = 0;
6346 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6347 unsigned NumLanes = (NumElems-1)/8 + 1;
6348 unsigned NumElemsInLane = NumElems / NumLanes;
6350 // Blend for v16i16 should be symetric for the both lanes.
6351 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6353 int SndLaneEltIdx = (NumLanes == 2) ?
6354 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6355 int EltIdx = SVOp->getMaskElt(i);
6357 if ((EltIdx < 0 || EltIdx == (int)i) &&
6358 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6361 if (((unsigned)EltIdx == (i + NumElems)) &&
6362 (SndLaneEltIdx < 0 ||
6363 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6364 MaskValue |= (1<<i);
6369 // Convert i32 vectors to floating point if it is not AVX2.
6370 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6372 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6373 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6375 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6376 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6379 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6380 DAG.getConstant(MaskValue, MVT::i32));
6381 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6384 /// In vector type \p VT, return true if the element at index \p InputIdx
6385 /// falls on a different 128-bit lane than \p OutputIdx.
6386 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6387 unsigned OutputIdx) {
6388 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6389 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6392 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6393 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6394 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6395 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6397 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6398 SelectionDAG &DAG) {
6399 MVT VT = V1.getSimpleValueType();
6400 assert(VT.is128BitVector() || VT.is256BitVector());
6402 MVT EltVT = VT.getVectorElementType();
6403 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6404 unsigned NumElts = VT.getVectorNumElements();
6406 SmallVector<SDValue, 32> PshufbMask;
6407 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6408 int InputIdx = MaskVals[OutputIdx];
6409 unsigned InputByteIdx;
6411 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6412 InputByteIdx = 0x80;
6414 // Cross lane is not allowed.
6415 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6417 InputByteIdx = InputIdx * EltSizeInBytes;
6418 // Index is an byte offset within the 128-bit lane.
6419 InputByteIdx &= 0xf;
6422 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6423 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6424 if (InputByteIdx != 0x80)
6429 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6431 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6432 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6433 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6436 // v8i16 shuffles - Prefer shuffles in the following order:
6437 // 1. [all] pshuflw, pshufhw, optional move
6438 // 2. [ssse3] 1 x pshufb
6439 // 3. [ssse3] 2 x pshufb + 1 x por
6440 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6442 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6443 SelectionDAG &DAG) {
6444 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6445 SDValue V1 = SVOp->getOperand(0);
6446 SDValue V2 = SVOp->getOperand(1);
6448 SmallVector<int, 8> MaskVals;
6450 // Determine if more than 1 of the words in each of the low and high quadwords
6451 // of the result come from the same quadword of one of the two inputs. Undef
6452 // mask values count as coming from any quadword, for better codegen.
6454 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6455 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6456 unsigned LoQuad[] = { 0, 0, 0, 0 };
6457 unsigned HiQuad[] = { 0, 0, 0, 0 };
6458 // Indices of quads used.
6459 std::bitset<4> InputQuads;
6460 for (unsigned i = 0; i < 8; ++i) {
6461 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6462 int EltIdx = SVOp->getMaskElt(i);
6463 MaskVals.push_back(EltIdx);
6472 InputQuads.set(EltIdx / 4);
6475 int BestLoQuad = -1;
6476 unsigned MaxQuad = 1;
6477 for (unsigned i = 0; i < 4; ++i) {
6478 if (LoQuad[i] > MaxQuad) {
6480 MaxQuad = LoQuad[i];
6484 int BestHiQuad = -1;
6486 for (unsigned i = 0; i < 4; ++i) {
6487 if (HiQuad[i] > MaxQuad) {
6489 MaxQuad = HiQuad[i];
6493 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6494 // of the two input vectors, shuffle them into one input vector so only a
6495 // single pshufb instruction is necessary. If there are more than 2 input
6496 // quads, disable the next transformation since it does not help SSSE3.
6497 bool V1Used = InputQuads[0] || InputQuads[1];
6498 bool V2Used = InputQuads[2] || InputQuads[3];
6499 if (Subtarget->hasSSSE3()) {
6500 if (InputQuads.count() == 2 && V1Used && V2Used) {
6501 BestLoQuad = InputQuads[0] ? 0 : 1;
6502 BestHiQuad = InputQuads[2] ? 2 : 3;
6504 if (InputQuads.count() > 2) {
6510 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6511 // the shuffle mask. If a quad is scored as -1, that means that it contains
6512 // words from all 4 input quadwords.
6514 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6516 BestLoQuad < 0 ? 0 : BestLoQuad,
6517 BestHiQuad < 0 ? 1 : BestHiQuad
6519 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6520 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6521 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6522 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6524 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6525 // source words for the shuffle, to aid later transformations.
6526 bool AllWordsInNewV = true;
6527 bool InOrder[2] = { true, true };
6528 for (unsigned i = 0; i != 8; ++i) {
6529 int idx = MaskVals[i];
6531 InOrder[i/4] = false;
6532 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6534 AllWordsInNewV = false;
6538 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6539 if (AllWordsInNewV) {
6540 for (int i = 0; i != 8; ++i) {
6541 int idx = MaskVals[i];
6544 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6545 if ((idx != i) && idx < 4)
6547 if ((idx != i) && idx > 3)
6556 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6557 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6558 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6559 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6560 unsigned TargetMask = 0;
6561 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6562 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6563 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6564 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6565 getShufflePSHUFLWImmediate(SVOp);
6566 V1 = NewV.getOperand(0);
6567 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6571 // Promote splats to a larger type which usually leads to more efficient code.
6572 // FIXME: Is this true if pshufb is available?
6573 if (SVOp->isSplat())
6574 return PromoteSplat(SVOp, DAG);
6576 // If we have SSSE3, and all words of the result are from 1 input vector,
6577 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6578 // is present, fall back to case 4.
6579 if (Subtarget->hasSSSE3()) {
6580 SmallVector<SDValue,16> pshufbMask;
6582 // If we have elements from both input vectors, set the high bit of the
6583 // shuffle mask element to zero out elements that come from V2 in the V1
6584 // mask, and elements that come from V1 in the V2 mask, so that the two
6585 // results can be OR'd together.
6586 bool TwoInputs = V1Used && V2Used;
6587 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6589 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6591 // Calculate the shuffle mask for the second input, shuffle it, and
6592 // OR it with the first shuffled input.
6593 CommuteVectorShuffleMask(MaskVals, 8);
6594 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6595 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6596 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6599 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6600 // and update MaskVals with new element order.
6601 std::bitset<8> InOrder;
6602 if (BestLoQuad >= 0) {
6603 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6604 for (int i = 0; i != 4; ++i) {
6605 int idx = MaskVals[i];
6608 } else if ((idx / 4) == BestLoQuad) {
6613 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6616 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6617 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6618 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6620 getShufflePSHUFLWImmediate(SVOp), DAG);
6624 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6625 // and update MaskVals with the new element order.
6626 if (BestHiQuad >= 0) {
6627 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6628 for (unsigned i = 4; i != 8; ++i) {
6629 int idx = MaskVals[i];
6632 } else if ((idx / 4) == BestHiQuad) {
6633 MaskV[i] = (idx & 3) + 4;
6637 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6640 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6641 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6642 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6644 getShufflePSHUFHWImmediate(SVOp), DAG);
6648 // In case BestHi & BestLo were both -1, which means each quadword has a word
6649 // from each of the four input quadwords, calculate the InOrder bitvector now
6650 // before falling through to the insert/extract cleanup.
6651 if (BestLoQuad == -1 && BestHiQuad == -1) {
6653 for (int i = 0; i != 8; ++i)
6654 if (MaskVals[i] < 0 || MaskVals[i] == i)
6658 // The other elements are put in the right place using pextrw and pinsrw.
6659 for (unsigned i = 0; i != 8; ++i) {
6662 int EltIdx = MaskVals[i];
6665 SDValue ExtOp = (EltIdx < 8) ?
6666 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6667 DAG.getIntPtrConstant(EltIdx)) :
6668 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6669 DAG.getIntPtrConstant(EltIdx - 8));
6670 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6671 DAG.getIntPtrConstant(i));
6676 /// \brief v16i16 shuffles
6678 /// FIXME: We only support generation of a single pshufb currently. We can
6679 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6680 /// well (e.g 2 x pshufb + 1 x por).
6682 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6683 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6684 SDValue V1 = SVOp->getOperand(0);
6685 SDValue V2 = SVOp->getOperand(1);
6688 if (V2.getOpcode() != ISD::UNDEF)
6691 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6692 return getPSHUFB(MaskVals, V1, dl, DAG);
6695 // v16i8 shuffles - Prefer shuffles in the following order:
6696 // 1. [ssse3] 1 x pshufb
6697 // 2. [ssse3] 2 x pshufb + 1 x por
6698 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6699 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6700 const X86Subtarget* Subtarget,
6701 SelectionDAG &DAG) {
6702 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6703 SDValue V1 = SVOp->getOperand(0);
6704 SDValue V2 = SVOp->getOperand(1);
6706 ArrayRef<int> MaskVals = SVOp->getMask();
6708 // Promote splats to a larger type which usually leads to more efficient code.
6709 // FIXME: Is this true if pshufb is available?
6710 if (SVOp->isSplat())
6711 return PromoteSplat(SVOp, DAG);
6713 // If we have SSSE3, case 1 is generated when all result bytes come from
6714 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6715 // present, fall back to case 3.
6717 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6718 if (Subtarget->hasSSSE3()) {
6719 SmallVector<SDValue,16> pshufbMask;
6721 // If all result elements are from one input vector, then only translate
6722 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6724 // Otherwise, we have elements from both input vectors, and must zero out
6725 // elements that come from V2 in the first mask, and V1 in the second mask
6726 // so that we can OR them together.
6727 for (unsigned i = 0; i != 16; ++i) {
6728 int EltIdx = MaskVals[i];
6729 if (EltIdx < 0 || EltIdx >= 16)
6731 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6733 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6734 DAG.getNode(ISD::BUILD_VECTOR, dl,
6735 MVT::v16i8, pshufbMask));
6737 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6738 // the 2nd operand if it's undefined or zero.
6739 if (V2.getOpcode() == ISD::UNDEF ||
6740 ISD::isBuildVectorAllZeros(V2.getNode()))
6743 // Calculate the shuffle mask for the second input, shuffle it, and
6744 // OR it with the first shuffled input.
6746 for (unsigned i = 0; i != 16; ++i) {
6747 int EltIdx = MaskVals[i];
6748 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6749 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6751 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6752 DAG.getNode(ISD::BUILD_VECTOR, dl,
6753 MVT::v16i8, pshufbMask));
6754 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6757 // No SSSE3 - Calculate in place words and then fix all out of place words
6758 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6759 // the 16 different words that comprise the two doublequadword input vectors.
6760 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6761 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6763 for (int i = 0; i != 8; ++i) {
6764 int Elt0 = MaskVals[i*2];
6765 int Elt1 = MaskVals[i*2+1];
6767 // This word of the result is all undef, skip it.
6768 if (Elt0 < 0 && Elt1 < 0)
6771 // This word of the result is already in the correct place, skip it.
6772 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6775 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6776 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6779 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6780 // using a single extract together, load it and store it.
6781 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6782 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6783 DAG.getIntPtrConstant(Elt1 / 2));
6784 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6785 DAG.getIntPtrConstant(i));
6789 // If Elt1 is defined, extract it from the appropriate source. If the
6790 // source byte is not also odd, shift the extracted word left 8 bits
6791 // otherwise clear the bottom 8 bits if we need to do an or.
6793 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6794 DAG.getIntPtrConstant(Elt1 / 2));
6795 if ((Elt1 & 1) == 0)
6796 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6798 TLI.getShiftAmountTy(InsElt.getValueType())));
6800 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6801 DAG.getConstant(0xFF00, MVT::i16));
6803 // If Elt0 is defined, extract it from the appropriate source. If the
6804 // source byte is not also even, shift the extracted word right 8 bits. If
6805 // Elt1 was also defined, OR the extracted values together before
6806 // inserting them in the result.
6808 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6809 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6810 if ((Elt0 & 1) != 0)
6811 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6813 TLI.getShiftAmountTy(InsElt0.getValueType())));
6815 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6816 DAG.getConstant(0x00FF, MVT::i16));
6817 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6820 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6821 DAG.getIntPtrConstant(i));
6823 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6826 // v32i8 shuffles - Translate to VPSHUFB if possible.
6828 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6829 const X86Subtarget *Subtarget,
6830 SelectionDAG &DAG) {
6831 MVT VT = SVOp->getSimpleValueType(0);
6832 SDValue V1 = SVOp->getOperand(0);
6833 SDValue V2 = SVOp->getOperand(1);
6835 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6837 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6838 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6839 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6841 // VPSHUFB may be generated if
6842 // (1) one of input vector is undefined or zeroinitializer.
6843 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6844 // And (2) the mask indexes don't cross the 128-bit lane.
6845 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6846 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6849 if (V1IsAllZero && !V2IsAllZero) {
6850 CommuteVectorShuffleMask(MaskVals, 32);
6853 return getPSHUFB(MaskVals, V1, dl, DAG);
6856 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6857 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6858 /// done when every pair / quad of shuffle mask elements point to elements in
6859 /// the right sequence. e.g.
6860 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6862 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6863 SelectionDAG &DAG) {
6864 MVT VT = SVOp->getSimpleValueType(0);
6866 unsigned NumElems = VT.getVectorNumElements();
6869 switch (VT.SimpleTy) {
6870 default: llvm_unreachable("Unexpected!");
6871 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6872 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6873 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6874 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6875 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6876 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6879 SmallVector<int, 8> MaskVec;
6880 for (unsigned i = 0; i != NumElems; i += Scale) {
6882 for (unsigned j = 0; j != Scale; ++j) {
6883 int EltIdx = SVOp->getMaskElt(i+j);
6887 StartIdx = (EltIdx / Scale);
6888 if (EltIdx != (int)(StartIdx*Scale + j))
6891 MaskVec.push_back(StartIdx);
6894 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6895 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6896 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6899 /// getVZextMovL - Return a zero-extending vector move low node.
6901 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6902 SDValue SrcOp, SelectionDAG &DAG,
6903 const X86Subtarget *Subtarget, SDLoc dl) {
6904 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6905 LoadSDNode *LD = nullptr;
6906 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6907 LD = dyn_cast<LoadSDNode>(SrcOp);
6909 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6911 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6912 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6913 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6914 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6915 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6917 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6918 return DAG.getNode(ISD::BITCAST, dl, VT,
6919 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6920 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6928 return DAG.getNode(ISD::BITCAST, dl, VT,
6929 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6930 DAG.getNode(ISD::BITCAST, dl,
6934 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6935 /// which could not be matched by any known target speficic shuffle
6937 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6939 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6940 if (NewOp.getNode())
6943 MVT VT = SVOp->getSimpleValueType(0);
6945 unsigned NumElems = VT.getVectorNumElements();
6946 unsigned NumLaneElems = NumElems / 2;
6949 MVT EltVT = VT.getVectorElementType();
6950 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6953 SmallVector<int, 16> Mask;
6954 for (unsigned l = 0; l < 2; ++l) {
6955 // Build a shuffle mask for the output, discovering on the fly which
6956 // input vectors to use as shuffle operands (recorded in InputUsed).
6957 // If building a suitable shuffle vector proves too hard, then bail
6958 // out with UseBuildVector set.
6959 bool UseBuildVector = false;
6960 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6961 unsigned LaneStart = l * NumLaneElems;
6962 for (unsigned i = 0; i != NumLaneElems; ++i) {
6963 // The mask element. This indexes into the input.
6964 int Idx = SVOp->getMaskElt(i+LaneStart);
6966 // the mask element does not index into any input vector.
6971 // The input vector this mask element indexes into.
6972 int Input = Idx / NumLaneElems;
6974 // Turn the index into an offset from the start of the input vector.
6975 Idx -= Input * NumLaneElems;
6977 // Find or create a shuffle vector operand to hold this input.
6979 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6980 if (InputUsed[OpNo] == Input)
6981 // This input vector is already an operand.
6983 if (InputUsed[OpNo] < 0) {
6984 // Create a new operand for this input vector.
6985 InputUsed[OpNo] = Input;
6990 if (OpNo >= array_lengthof(InputUsed)) {
6991 // More than two input vectors used! Give up on trying to create a
6992 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6993 UseBuildVector = true;
6997 // Add the mask index for the new shuffle vector.
6998 Mask.push_back(Idx + OpNo * NumLaneElems);
7001 if (UseBuildVector) {
7002 SmallVector<SDValue, 16> SVOps;
7003 for (unsigned i = 0; i != NumLaneElems; ++i) {
7004 // The mask element. This indexes into the input.
7005 int Idx = SVOp->getMaskElt(i+LaneStart);
7007 SVOps.push_back(DAG.getUNDEF(EltVT));
7011 // The input vector this mask element indexes into.
7012 int Input = Idx / NumElems;
7014 // Turn the index into an offset from the start of the input vector.
7015 Idx -= Input * NumElems;
7017 // Extract the vector element by hand.
7018 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7019 SVOp->getOperand(Input),
7020 DAG.getIntPtrConstant(Idx)));
7023 // Construct the output using a BUILD_VECTOR.
7024 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7025 } else if (InputUsed[0] < 0) {
7026 // No input vectors were used! The result is undefined.
7027 Output[l] = DAG.getUNDEF(NVT);
7029 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7030 (InputUsed[0] % 2) * NumLaneElems,
7032 // If only one input was used, use an undefined vector for the other.
7033 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7034 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7035 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7036 // At least one input vector was used. Create a new shuffle vector.
7037 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7043 // Concatenate the result back
7044 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7047 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7048 /// 4 elements, and match them with several different shuffle types.
7050 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7051 SDValue V1 = SVOp->getOperand(0);
7052 SDValue V2 = SVOp->getOperand(1);
7054 MVT VT = SVOp->getSimpleValueType(0);
7056 assert(VT.is128BitVector() && "Unsupported vector size");
7058 std::pair<int, int> Locs[4];
7059 int Mask1[] = { -1, -1, -1, -1 };
7060 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7064 for (unsigned i = 0; i != 4; ++i) {
7065 int Idx = PermMask[i];
7067 Locs[i] = std::make_pair(-1, -1);
7069 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7071 Locs[i] = std::make_pair(0, NumLo);
7075 Locs[i] = std::make_pair(1, NumHi);
7077 Mask1[2+NumHi] = Idx;
7083 if (NumLo <= 2 && NumHi <= 2) {
7084 // If no more than two elements come from either vector. This can be
7085 // implemented with two shuffles. First shuffle gather the elements.
7086 // The second shuffle, which takes the first shuffle as both of its
7087 // vector operands, put the elements into the right order.
7088 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7090 int Mask2[] = { -1, -1, -1, -1 };
7092 for (unsigned i = 0; i != 4; ++i)
7093 if (Locs[i].first != -1) {
7094 unsigned Idx = (i < 2) ? 0 : 4;
7095 Idx += Locs[i].first * 2 + Locs[i].second;
7099 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7102 if (NumLo == 3 || NumHi == 3) {
7103 // Otherwise, we must have three elements from one vector, call it X, and
7104 // one element from the other, call it Y. First, use a shufps to build an
7105 // intermediate vector with the one element from Y and the element from X
7106 // that will be in the same half in the final destination (the indexes don't
7107 // matter). Then, use a shufps to build the final vector, taking the half
7108 // containing the element from Y from the intermediate, and the other half
7111 // Normalize it so the 3 elements come from V1.
7112 CommuteVectorShuffleMask(PermMask, 4);
7116 // Find the element from V2.
7118 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7119 int Val = PermMask[HiIndex];
7126 Mask1[0] = PermMask[HiIndex];
7128 Mask1[2] = PermMask[HiIndex^1];
7130 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7133 Mask1[0] = PermMask[0];
7134 Mask1[1] = PermMask[1];
7135 Mask1[2] = HiIndex & 1 ? 6 : 4;
7136 Mask1[3] = HiIndex & 1 ? 4 : 6;
7137 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7140 Mask1[0] = HiIndex & 1 ? 2 : 0;
7141 Mask1[1] = HiIndex & 1 ? 0 : 2;
7142 Mask1[2] = PermMask[2];
7143 Mask1[3] = PermMask[3];
7148 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7151 // Break it into (shuffle shuffle_hi, shuffle_lo).
7152 int LoMask[] = { -1, -1, -1, -1 };
7153 int HiMask[] = { -1, -1, -1, -1 };
7155 int *MaskPtr = LoMask;
7156 unsigned MaskIdx = 0;
7159 for (unsigned i = 0; i != 4; ++i) {
7166 int Idx = PermMask[i];
7168 Locs[i] = std::make_pair(-1, -1);
7169 } else if (Idx < 4) {
7170 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7171 MaskPtr[LoIdx] = Idx;
7174 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7175 MaskPtr[HiIdx] = Idx;
7180 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7181 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7182 int MaskOps[] = { -1, -1, -1, -1 };
7183 for (unsigned i = 0; i != 4; ++i)
7184 if (Locs[i].first != -1)
7185 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7186 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7189 static bool MayFoldVectorLoad(SDValue V) {
7190 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7191 V = V.getOperand(0);
7193 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7194 V = V.getOperand(0);
7195 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7196 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7197 // BUILD_VECTOR (load), undef
7198 V = V.getOperand(0);
7200 return MayFoldLoad(V);
7204 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7205 MVT VT = Op.getSimpleValueType();
7207 // Canonizalize to v2f64.
7208 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7209 return DAG.getNode(ISD::BITCAST, dl, VT,
7210 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7215 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7217 SDValue V1 = Op.getOperand(0);
7218 SDValue V2 = Op.getOperand(1);
7219 MVT VT = Op.getSimpleValueType();
7221 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7223 if (HasSSE2 && VT == MVT::v2f64)
7224 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7226 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7227 return DAG.getNode(ISD::BITCAST, dl, VT,
7228 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7229 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7230 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7234 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7235 SDValue V1 = Op.getOperand(0);
7236 SDValue V2 = Op.getOperand(1);
7237 MVT VT = Op.getSimpleValueType();
7239 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7240 "unsupported shuffle type");
7242 if (V2.getOpcode() == ISD::UNDEF)
7246 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7250 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7251 SDValue V1 = Op.getOperand(0);
7252 SDValue V2 = Op.getOperand(1);
7253 MVT VT = Op.getSimpleValueType();
7254 unsigned NumElems = VT.getVectorNumElements();
7256 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7257 // operand of these instructions is only memory, so check if there's a
7258 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7260 bool CanFoldLoad = false;
7262 // Trivial case, when V2 comes from a load.
7263 if (MayFoldVectorLoad(V2))
7266 // When V1 is a load, it can be folded later into a store in isel, example:
7267 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7269 // (MOVLPSmr addr:$src1, VR128:$src2)
7270 // So, recognize this potential and also use MOVLPS or MOVLPD
7271 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7274 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7276 if (HasSSE2 && NumElems == 2)
7277 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7280 // If we don't care about the second element, proceed to use movss.
7281 if (SVOp->getMaskElt(1) != -1)
7282 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7285 // movl and movlp will both match v2i64, but v2i64 is never matched by
7286 // movl earlier because we make it strict to avoid messing with the movlp load
7287 // folding logic (see the code above getMOVLP call). Match it here then,
7288 // this is horrible, but will stay like this until we move all shuffle
7289 // matching to x86 specific nodes. Note that for the 1st condition all
7290 // types are matched with movsd.
7292 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7293 // as to remove this logic from here, as much as possible
7294 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7295 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7296 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7299 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7301 // Invert the operand order and use SHUFPS to match it.
7302 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7303 getShuffleSHUFImmediate(SVOp), DAG);
7306 // It is only safe to call this function if isINSERTPSMask is true for
7307 // this shufflevector mask.
7308 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7309 SelectionDAG &DAG) {
7310 // Generate an insertps instruction when inserting an f32 from memory onto a
7311 // v4f32 or when copying a member from one v4f32 to another.
7312 // We also use it for transferring i32 from one register to another,
7313 // since it simply copies the same bits.
7314 // If we're transfering an i32 from memory to a specific element in a
7315 // register, we output a generic DAG that will match the PINSRD
7317 // TODO: Optimize for AVX cases too (VINSERTPS)
7318 MVT VT = SVOp->getSimpleValueType(0);
7319 MVT EVT = VT.getVectorElementType();
7320 SDValue V1 = SVOp->getOperand(0);
7321 SDValue V2 = SVOp->getOperand(1);
7322 auto Mask = SVOp->getMask();
7323 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7324 "unsupported vector type for insertps/pinsrd");
7326 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7327 [](const int &i) { return i < 4; });
7335 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7336 [](const int &i) { return i < 4; }) -
7341 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7342 [](const int &i) { return i >= 4; }) -
7346 if (MayFoldLoad(From)) {
7347 // Trivial case, when From comes from a load and is only used by the
7348 // shuffle. Make it use insertps from the vector that we need from that
7350 SDValue Addr = From.getOperand(1);
7352 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7353 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7354 Addr.getSimpleValueType()));
7356 LoadSDNode *Load = cast<LoadSDNode>(From);
7358 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7359 DAG.getMachineFunction().getMachineMemOperand(
7360 Load->getMemOperand(), 0, EVT.getStoreSize()));
7362 if (EVT == MVT::f32) {
7363 // Create this as a scalar to vector to match the instruction pattern.
7364 SDValue LoadScalarToVector =
7365 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7366 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7367 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7369 } else { // EVT == MVT::i32
7370 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7371 // instruction, to match the PINSRD instruction, which loads an i32 to a
7372 // certain vector element.
7373 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7374 DAG.getConstant(DestIndex, MVT::i32));
7378 // Vector-element-to-vector
7379 unsigned SrcIndex = Mask[DestIndex] % 4;
7380 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7381 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7384 // Reduce a vector shuffle to zext.
7385 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7386 SelectionDAG &DAG) {
7387 // PMOVZX is only available from SSE41.
7388 if (!Subtarget->hasSSE41())
7391 MVT VT = Op.getSimpleValueType();
7393 // Only AVX2 support 256-bit vector integer extending.
7394 if (!Subtarget->hasInt256() && VT.is256BitVector())
7397 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7399 SDValue V1 = Op.getOperand(0);
7400 SDValue V2 = Op.getOperand(1);
7401 unsigned NumElems = VT.getVectorNumElements();
7403 // Extending is an unary operation and the element type of the source vector
7404 // won't be equal to or larger than i64.
7405 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7406 VT.getVectorElementType() == MVT::i64)
7409 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7410 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7411 while ((1U << Shift) < NumElems) {
7412 if (SVOp->getMaskElt(1U << Shift) == 1)
7415 // The maximal ratio is 8, i.e. from i8 to i64.
7420 // Check the shuffle mask.
7421 unsigned Mask = (1U << Shift) - 1;
7422 for (unsigned i = 0; i != NumElems; ++i) {
7423 int EltIdx = SVOp->getMaskElt(i);
7424 if ((i & Mask) != 0 && EltIdx != -1)
7426 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7430 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7431 MVT NeVT = MVT::getIntegerVT(NBits);
7432 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7434 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7437 // Simplify the operand as it's prepared to be fed into shuffle.
7438 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7439 if (V1.getOpcode() == ISD::BITCAST &&
7440 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7441 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7442 V1.getOperand(0).getOperand(0)
7443 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7444 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7445 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7446 ConstantSDNode *CIdx =
7447 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7448 // If it's foldable, i.e. normal load with single use, we will let code
7449 // selection to fold it. Otherwise, we will short the conversion sequence.
7450 if (CIdx && CIdx->getZExtValue() == 0 &&
7451 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7452 MVT FullVT = V.getSimpleValueType();
7453 MVT V1VT = V1.getSimpleValueType();
7454 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7455 // The "ext_vec_elt" node is wider than the result node.
7456 // In this case we should extract subvector from V.
7457 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7458 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7459 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7460 FullVT.getVectorNumElements()/Ratio);
7461 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7462 DAG.getIntPtrConstant(0));
7464 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7468 return DAG.getNode(ISD::BITCAST, DL, VT,
7469 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7473 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7474 SelectionDAG &DAG) {
7475 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7476 MVT VT = Op.getSimpleValueType();
7478 SDValue V1 = Op.getOperand(0);
7479 SDValue V2 = Op.getOperand(1);
7481 if (isZeroShuffle(SVOp))
7482 return getZeroVector(VT, Subtarget, DAG, dl);
7484 // Handle splat operations
7485 if (SVOp->isSplat()) {
7486 // Use vbroadcast whenever the splat comes from a foldable load
7487 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7488 if (Broadcast.getNode())
7492 // Check integer expanding shuffles.
7493 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7494 if (NewOp.getNode())
7497 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7499 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7500 VT == MVT::v16i16 || VT == MVT::v32i8) {
7501 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7502 if (NewOp.getNode())
7503 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7504 } else if ((VT == MVT::v4i32 ||
7505 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7506 // FIXME: Figure out a cleaner way to do this.
7507 // Try to make use of movq to zero out the top part.
7508 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7509 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7510 if (NewOp.getNode()) {
7511 MVT NewVT = NewOp.getSimpleValueType();
7512 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7513 NewVT, true, false))
7514 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7515 DAG, Subtarget, dl);
7517 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7518 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7519 if (NewOp.getNode()) {
7520 MVT NewVT = NewOp.getSimpleValueType();
7521 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7522 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7523 DAG, Subtarget, dl);
7531 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7532 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7533 SDValue V1 = Op.getOperand(0);
7534 SDValue V2 = Op.getOperand(1);
7535 MVT VT = Op.getSimpleValueType();
7537 unsigned NumElems = VT.getVectorNumElements();
7538 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7539 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7540 bool V1IsSplat = false;
7541 bool V2IsSplat = false;
7542 bool HasSSE2 = Subtarget->hasSSE2();
7543 bool HasFp256 = Subtarget->hasFp256();
7544 bool HasInt256 = Subtarget->hasInt256();
7545 MachineFunction &MF = DAG.getMachineFunction();
7546 bool OptForSize = MF.getFunction()->getAttributes().
7547 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7549 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7551 if (V1IsUndef && V2IsUndef)
7552 return DAG.getUNDEF(VT);
7554 // When we create a shuffle node we put the UNDEF node to second operand,
7555 // but in some cases the first operand may be transformed to UNDEF.
7556 // In this case we should just commute the node.
7558 return CommuteVectorShuffle(SVOp, DAG);
7560 // Vector shuffle lowering takes 3 steps:
7562 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7563 // narrowing and commutation of operands should be handled.
7564 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7566 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7567 // so the shuffle can be broken into other shuffles and the legalizer can
7568 // try the lowering again.
7570 // The general idea is that no vector_shuffle operation should be left to
7571 // be matched during isel, all of them must be converted to a target specific
7574 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7575 // narrowing and commutation of operands should be handled. The actual code
7576 // doesn't include all of those, work in progress...
7577 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7578 if (NewOp.getNode())
7581 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7583 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7584 // unpckh_undef). Only use pshufd if speed is more important than size.
7585 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7586 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7587 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7588 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7590 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7591 V2IsUndef && MayFoldVectorLoad(V1))
7592 return getMOVDDup(Op, dl, V1, DAG);
7594 if (isMOVHLPS_v_undef_Mask(M, VT))
7595 return getMOVHighToLow(Op, dl, DAG);
7597 // Use to match splats
7598 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7599 (VT == MVT::v2f64 || VT == MVT::v2i64))
7600 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7602 if (isPSHUFDMask(M, VT)) {
7603 // The actual implementation will match the mask in the if above and then
7604 // during isel it can match several different instructions, not only pshufd
7605 // as its name says, sad but true, emulate the behavior for now...
7606 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7607 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7609 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7611 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7612 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7614 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7615 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7618 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7622 if (isPALIGNRMask(M, VT, Subtarget))
7623 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7624 getShufflePALIGNRImmediate(SVOp),
7627 // Check if this can be converted into a logical shift.
7628 bool isLeft = false;
7631 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7632 if (isShift && ShVal.hasOneUse()) {
7633 // If the shifted value has multiple uses, it may be cheaper to use
7634 // v_set0 + movlhps or movhlps, etc.
7635 MVT EltVT = VT.getVectorElementType();
7636 ShAmt *= EltVT.getSizeInBits();
7637 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7640 if (isMOVLMask(M, VT)) {
7641 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7642 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7643 if (!isMOVLPMask(M, VT)) {
7644 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7645 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7647 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7648 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7652 // FIXME: fold these into legal mask.
7653 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7654 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7656 if (isMOVHLPSMask(M, VT))
7657 return getMOVHighToLow(Op, dl, DAG);
7659 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7660 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7662 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7663 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7665 if (isMOVLPMask(M, VT))
7666 return getMOVLP(Op, dl, DAG, HasSSE2);
7668 if (ShouldXformToMOVHLPS(M, VT) ||
7669 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7670 return CommuteVectorShuffle(SVOp, DAG);
7673 // No better options. Use a vshldq / vsrldq.
7674 MVT EltVT = VT.getVectorElementType();
7675 ShAmt *= EltVT.getSizeInBits();
7676 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7679 bool Commuted = false;
7680 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7681 // 1,1,1,1 -> v8i16 though.
7682 V1IsSplat = isSplatVector(V1.getNode());
7683 V2IsSplat = isSplatVector(V2.getNode());
7685 // Canonicalize the splat or undef, if present, to be on the RHS.
7686 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7687 CommuteVectorShuffleMask(M, NumElems);
7689 std::swap(V1IsSplat, V2IsSplat);
7693 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7694 // Shuffling low element of v1 into undef, just return v1.
7697 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7698 // the instruction selector will not match, so get a canonical MOVL with
7699 // swapped operands to undo the commute.
7700 return getMOVL(DAG, dl, VT, V2, V1);
7703 if (isUNPCKLMask(M, VT, HasInt256))
7704 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7706 if (isUNPCKHMask(M, VT, HasInt256))
7707 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7710 // Normalize mask so all entries that point to V2 points to its first
7711 // element then try to match unpck{h|l} again. If match, return a
7712 // new vector_shuffle with the corrected mask.p
7713 SmallVector<int, 8> NewMask(M.begin(), M.end());
7714 NormalizeMask(NewMask, NumElems);
7715 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7716 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7717 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7718 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7722 // Commute is back and try unpck* again.
7723 // FIXME: this seems wrong.
7724 CommuteVectorShuffleMask(M, NumElems);
7726 std::swap(V1IsSplat, V2IsSplat);
7728 if (isUNPCKLMask(M, VT, HasInt256))
7729 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7731 if (isUNPCKHMask(M, VT, HasInt256))
7732 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7735 // Normalize the node to match x86 shuffle ops if needed
7736 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7737 return CommuteVectorShuffle(SVOp, DAG);
7739 // The checks below are all present in isShuffleMaskLegal, but they are
7740 // inlined here right now to enable us to directly emit target specific
7741 // nodes, and remove one by one until they don't return Op anymore.
7743 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7744 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7745 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7746 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7749 if (isPSHUFHWMask(M, VT, HasInt256))
7750 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7751 getShufflePSHUFHWImmediate(SVOp),
7754 if (isPSHUFLWMask(M, VT, HasInt256))
7755 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7756 getShufflePSHUFLWImmediate(SVOp),
7759 if (isSHUFPMask(M, VT))
7760 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7761 getShuffleSHUFImmediate(SVOp), DAG);
7763 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7764 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7765 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7766 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7768 //===--------------------------------------------------------------------===//
7769 // Generate target specific nodes for 128 or 256-bit shuffles only
7770 // supported in the AVX instruction set.
7773 // Handle VMOVDDUPY permutations
7774 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7775 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7777 // Handle VPERMILPS/D* permutations
7778 if (isVPERMILPMask(M, VT)) {
7779 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7780 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7781 getShuffleSHUFImmediate(SVOp), DAG);
7782 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7783 getShuffleSHUFImmediate(SVOp), DAG);
7787 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7788 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7789 Idx*(NumElems/2), DAG, dl);
7791 // Handle VPERM2F128/VPERM2I128 permutations
7792 if (isVPERM2X128Mask(M, VT, HasFp256))
7793 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7794 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7796 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7797 if (BlendOp.getNode())
7800 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7801 return getINSERTPS(SVOp, dl, DAG);
7804 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7805 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7807 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7808 VT.is512BitVector()) {
7809 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7810 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7811 SmallVector<SDValue, 16> permclMask;
7812 for (unsigned i = 0; i != NumElems; ++i) {
7813 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7816 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7818 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7819 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7820 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7821 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7822 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7825 //===--------------------------------------------------------------------===//
7826 // Since no target specific shuffle was selected for this generic one,
7827 // lower it into other known shuffles. FIXME: this isn't true yet, but
7828 // this is the plan.
7831 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7832 if (VT == MVT::v8i16) {
7833 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7834 if (NewOp.getNode())
7838 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7839 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7840 if (NewOp.getNode())
7844 if (VT == MVT::v16i8) {
7845 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7846 if (NewOp.getNode())
7850 if (VT == MVT::v32i8) {
7851 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7852 if (NewOp.getNode())
7856 // Handle all 128-bit wide vectors with 4 elements, and match them with
7857 // several different shuffle types.
7858 if (NumElems == 4 && VT.is128BitVector())
7859 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7861 // Handle general 256-bit shuffles
7862 if (VT.is256BitVector())
7863 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7868 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7869 MVT VT = Op.getSimpleValueType();
7872 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7875 if (VT.getSizeInBits() == 8) {
7876 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7877 Op.getOperand(0), Op.getOperand(1));
7878 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7879 DAG.getValueType(VT));
7880 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7883 if (VT.getSizeInBits() == 16) {
7884 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7885 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7887 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7888 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7889 DAG.getNode(ISD::BITCAST, dl,
7893 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7894 Op.getOperand(0), Op.getOperand(1));
7895 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7896 DAG.getValueType(VT));
7897 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7900 if (VT == MVT::f32) {
7901 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7902 // the result back to FR32 register. It's only worth matching if the
7903 // result has a single use which is a store or a bitcast to i32. And in
7904 // the case of a store, it's not worth it if the index is a constant 0,
7905 // because a MOVSSmr can be used instead, which is smaller and faster.
7906 if (!Op.hasOneUse())
7908 SDNode *User = *Op.getNode()->use_begin();
7909 if ((User->getOpcode() != ISD::STORE ||
7910 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7911 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7912 (User->getOpcode() != ISD::BITCAST ||
7913 User->getValueType(0) != MVT::i32))
7915 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7916 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7919 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7922 if (VT == MVT::i32 || VT == MVT::i64) {
7923 // ExtractPS/pextrq works with constant index.
7924 if (isa<ConstantSDNode>(Op.getOperand(1)))
7930 /// Extract one bit from mask vector, like v16i1 or v8i1.
7931 /// AVX-512 feature.
7933 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7934 SDValue Vec = Op.getOperand(0);
7936 MVT VecVT = Vec.getSimpleValueType();
7937 SDValue Idx = Op.getOperand(1);
7938 MVT EltVT = Op.getSimpleValueType();
7940 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7942 // variable index can't be handled in mask registers,
7943 // extend vector to VR512
7944 if (!isa<ConstantSDNode>(Idx)) {
7945 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7946 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7947 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7948 ExtVT.getVectorElementType(), Ext, Idx);
7949 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7952 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7953 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7954 unsigned MaxSift = rc->getSize()*8 - 1;
7955 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7956 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7957 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7958 DAG.getConstant(MaxSift, MVT::i8));
7959 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7960 DAG.getIntPtrConstant(0));
7964 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7965 SelectionDAG &DAG) const {
7967 SDValue Vec = Op.getOperand(0);
7968 MVT VecVT = Vec.getSimpleValueType();
7969 SDValue Idx = Op.getOperand(1);
7971 if (Op.getSimpleValueType() == MVT::i1)
7972 return ExtractBitFromMaskVector(Op, DAG);
7974 if (!isa<ConstantSDNode>(Idx)) {
7975 if (VecVT.is512BitVector() ||
7976 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7977 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7980 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7981 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7982 MaskEltVT.getSizeInBits());
7984 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7985 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7986 getZeroVector(MaskVT, Subtarget, DAG, dl),
7987 Idx, DAG.getConstant(0, getPointerTy()));
7988 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7989 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7990 Perm, DAG.getConstant(0, getPointerTy()));
7995 // If this is a 256-bit vector result, first extract the 128-bit vector and
7996 // then extract the element from the 128-bit vector.
7997 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7999 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8000 // Get the 128-bit vector.
8001 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8002 MVT EltVT = VecVT.getVectorElementType();
8004 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8006 //if (IdxVal >= NumElems/2)
8007 // IdxVal -= NumElems/2;
8008 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8009 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8010 DAG.getConstant(IdxVal, MVT::i32));
8013 assert(VecVT.is128BitVector() && "Unexpected vector length");
8015 if (Subtarget->hasSSE41()) {
8016 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8021 MVT VT = Op.getSimpleValueType();
8022 // TODO: handle v16i8.
8023 if (VT.getSizeInBits() == 16) {
8024 SDValue Vec = Op.getOperand(0);
8025 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8027 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8028 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8029 DAG.getNode(ISD::BITCAST, dl,
8032 // Transform it so it match pextrw which produces a 32-bit result.
8033 MVT EltVT = MVT::i32;
8034 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8035 Op.getOperand(0), Op.getOperand(1));
8036 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8037 DAG.getValueType(VT));
8038 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8041 if (VT.getSizeInBits() == 32) {
8042 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8046 // SHUFPS the element to the lowest double word, then movss.
8047 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8048 MVT VVT = Op.getOperand(0).getSimpleValueType();
8049 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8050 DAG.getUNDEF(VVT), Mask);
8051 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8052 DAG.getIntPtrConstant(0));
8055 if (VT.getSizeInBits() == 64) {
8056 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8057 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8058 // to match extract_elt for f64.
8059 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8063 // UNPCKHPD the element to the lowest double word, then movsd.
8064 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8065 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8066 int Mask[2] = { 1, -1 };
8067 MVT VVT = Op.getOperand(0).getSimpleValueType();
8068 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8069 DAG.getUNDEF(VVT), Mask);
8070 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8071 DAG.getIntPtrConstant(0));
8077 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8078 MVT VT = Op.getSimpleValueType();
8079 MVT EltVT = VT.getVectorElementType();
8082 SDValue N0 = Op.getOperand(0);
8083 SDValue N1 = Op.getOperand(1);
8084 SDValue N2 = Op.getOperand(2);
8086 if (!VT.is128BitVector())
8089 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8090 isa<ConstantSDNode>(N2)) {
8092 if (VT == MVT::v8i16)
8093 Opc = X86ISD::PINSRW;
8094 else if (VT == MVT::v16i8)
8095 Opc = X86ISD::PINSRB;
8097 Opc = X86ISD::PINSRB;
8099 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8101 if (N1.getValueType() != MVT::i32)
8102 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8103 if (N2.getValueType() != MVT::i32)
8104 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8105 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8108 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8109 // Bits [7:6] of the constant are the source select. This will always be
8110 // zero here. The DAG Combiner may combine an extract_elt index into these
8111 // bits. For example (insert (extract, 3), 2) could be matched by putting
8112 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8113 // Bits [5:4] of the constant are the destination select. This is the
8114 // value of the incoming immediate.
8115 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8116 // combine either bitwise AND or insert of float 0.0 to set these bits.
8117 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8118 // Create this as a scalar to vector..
8119 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8120 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8123 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8124 // PINSR* works with constant index.
8130 /// Insert one bit to mask vector, like v16i1 or v8i1.
8131 /// AVX-512 feature.
8133 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8135 SDValue Vec = Op.getOperand(0);
8136 SDValue Elt = Op.getOperand(1);
8137 SDValue Idx = Op.getOperand(2);
8138 MVT VecVT = Vec.getSimpleValueType();
8140 if (!isa<ConstantSDNode>(Idx)) {
8141 // Non constant index. Extend source and destination,
8142 // insert element and then truncate the result.
8143 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8144 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8145 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8146 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8147 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8148 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8151 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8152 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8153 if (Vec.getOpcode() == ISD::UNDEF)
8154 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8155 DAG.getConstant(IdxVal, MVT::i8));
8156 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8157 unsigned MaxSift = rc->getSize()*8 - 1;
8158 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8159 DAG.getConstant(MaxSift, MVT::i8));
8160 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8161 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8162 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8165 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8166 MVT VT = Op.getSimpleValueType();
8167 MVT EltVT = VT.getVectorElementType();
8169 if (EltVT == MVT::i1)
8170 return InsertBitToMaskVector(Op, DAG);
8173 SDValue N0 = Op.getOperand(0);
8174 SDValue N1 = Op.getOperand(1);
8175 SDValue N2 = Op.getOperand(2);
8177 // If this is a 256-bit vector result, first extract the 128-bit vector,
8178 // insert the element into the extracted half and then place it back.
8179 if (VT.is256BitVector() || VT.is512BitVector()) {
8180 if (!isa<ConstantSDNode>(N2))
8183 // Get the desired 128-bit vector half.
8184 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8185 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8187 // Insert the element into the desired half.
8188 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8189 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8191 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8192 DAG.getConstant(IdxIn128, MVT::i32));
8194 // Insert the changed part back to the 256-bit vector
8195 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8198 if (Subtarget->hasSSE41())
8199 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8201 if (EltVT == MVT::i8)
8204 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8205 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8206 // as its second argument.
8207 if (N1.getValueType() != MVT::i32)
8208 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8209 if (N2.getValueType() != MVT::i32)
8210 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8211 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8216 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8218 MVT OpVT = Op.getSimpleValueType();
8220 // If this is a 256-bit vector result, first insert into a 128-bit
8221 // vector and then insert into the 256-bit vector.
8222 if (!OpVT.is128BitVector()) {
8223 // Insert into a 128-bit vector.
8224 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8225 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8226 OpVT.getVectorNumElements() / SizeFactor);
8228 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8230 // Insert the 128-bit vector.
8231 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8234 if (OpVT == MVT::v1i64 &&
8235 Op.getOperand(0).getValueType() == MVT::i64)
8236 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8238 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8239 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8240 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8241 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8244 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8245 // a simple subregister reference or explicit instructions to grab
8246 // upper bits of a vector.
8247 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8248 SelectionDAG &DAG) {
8250 SDValue In = Op.getOperand(0);
8251 SDValue Idx = Op.getOperand(1);
8252 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8253 MVT ResVT = Op.getSimpleValueType();
8254 MVT InVT = In.getSimpleValueType();
8256 if (Subtarget->hasFp256()) {
8257 if (ResVT.is128BitVector() &&
8258 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8259 isa<ConstantSDNode>(Idx)) {
8260 return Extract128BitVector(In, IdxVal, DAG, dl);
8262 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8263 isa<ConstantSDNode>(Idx)) {
8264 return Extract256BitVector(In, IdxVal, DAG, dl);
8270 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8271 // simple superregister reference or explicit instructions to insert
8272 // the upper bits of a vector.
8273 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8274 SelectionDAG &DAG) {
8275 if (Subtarget->hasFp256()) {
8276 SDLoc dl(Op.getNode());
8277 SDValue Vec = Op.getNode()->getOperand(0);
8278 SDValue SubVec = Op.getNode()->getOperand(1);
8279 SDValue Idx = Op.getNode()->getOperand(2);
8281 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8282 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8283 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8284 isa<ConstantSDNode>(Idx)) {
8285 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8286 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8289 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8290 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8291 isa<ConstantSDNode>(Idx)) {
8292 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8293 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8299 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8300 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8301 // one of the above mentioned nodes. It has to be wrapped because otherwise
8302 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8303 // be used to form addressing mode. These wrapped nodes will be selected
8306 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8307 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8309 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8311 unsigned char OpFlag = 0;
8312 unsigned WrapperKind = X86ISD::Wrapper;
8313 CodeModel::Model M = getTargetMachine().getCodeModel();
8315 if (Subtarget->isPICStyleRIPRel() &&
8316 (M == CodeModel::Small || M == CodeModel::Kernel))
8317 WrapperKind = X86ISD::WrapperRIP;
8318 else if (Subtarget->isPICStyleGOT())
8319 OpFlag = X86II::MO_GOTOFF;
8320 else if (Subtarget->isPICStyleStubPIC())
8321 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8323 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8325 CP->getOffset(), OpFlag);
8327 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8328 // With PIC, the address is actually $g + Offset.
8330 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8331 DAG.getNode(X86ISD::GlobalBaseReg,
8332 SDLoc(), getPointerTy()),
8339 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8340 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8342 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8344 unsigned char OpFlag = 0;
8345 unsigned WrapperKind = X86ISD::Wrapper;
8346 CodeModel::Model M = getTargetMachine().getCodeModel();
8348 if (Subtarget->isPICStyleRIPRel() &&
8349 (M == CodeModel::Small || M == CodeModel::Kernel))
8350 WrapperKind = X86ISD::WrapperRIP;
8351 else if (Subtarget->isPICStyleGOT())
8352 OpFlag = X86II::MO_GOTOFF;
8353 else if (Subtarget->isPICStyleStubPIC())
8354 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8356 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8359 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8361 // With PIC, the address is actually $g + Offset.
8363 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8364 DAG.getNode(X86ISD::GlobalBaseReg,
8365 SDLoc(), getPointerTy()),
8372 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8373 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8375 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8377 unsigned char OpFlag = 0;
8378 unsigned WrapperKind = X86ISD::Wrapper;
8379 CodeModel::Model M = getTargetMachine().getCodeModel();
8381 if (Subtarget->isPICStyleRIPRel() &&
8382 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8383 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8384 OpFlag = X86II::MO_GOTPCREL;
8385 WrapperKind = X86ISD::WrapperRIP;
8386 } else if (Subtarget->isPICStyleGOT()) {
8387 OpFlag = X86II::MO_GOT;
8388 } else if (Subtarget->isPICStyleStubPIC()) {
8389 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8390 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8391 OpFlag = X86II::MO_DARWIN_NONLAZY;
8394 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8397 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8399 // With PIC, the address is actually $g + Offset.
8400 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8401 !Subtarget->is64Bit()) {
8402 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8403 DAG.getNode(X86ISD::GlobalBaseReg,
8404 SDLoc(), getPointerTy()),
8408 // For symbols that require a load from a stub to get the address, emit the
8410 if (isGlobalStubReference(OpFlag))
8411 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8412 MachinePointerInfo::getGOT(), false, false, false, 0);
8418 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8419 // Create the TargetBlockAddressAddress node.
8420 unsigned char OpFlags =
8421 Subtarget->ClassifyBlockAddressReference();
8422 CodeModel::Model M = getTargetMachine().getCodeModel();
8423 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8424 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8426 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8429 if (Subtarget->isPICStyleRIPRel() &&
8430 (M == CodeModel::Small || M == CodeModel::Kernel))
8431 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8433 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8435 // With PIC, the address is actually $g + Offset.
8436 if (isGlobalRelativeToPICBase(OpFlags)) {
8437 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8438 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8446 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8447 int64_t Offset, SelectionDAG &DAG) const {
8448 // Create the TargetGlobalAddress node, folding in the constant
8449 // offset if it is legal.
8450 unsigned char OpFlags =
8451 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8452 CodeModel::Model M = getTargetMachine().getCodeModel();
8454 if (OpFlags == X86II::MO_NO_FLAG &&
8455 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8456 // A direct static reference to a global.
8457 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8460 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8463 if (Subtarget->isPICStyleRIPRel() &&
8464 (M == CodeModel::Small || M == CodeModel::Kernel))
8465 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8467 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8469 // With PIC, the address is actually $g + Offset.
8470 if (isGlobalRelativeToPICBase(OpFlags)) {
8471 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8472 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8476 // For globals that require a load from a stub to get the address, emit the
8478 if (isGlobalStubReference(OpFlags))
8479 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8480 MachinePointerInfo::getGOT(), false, false, false, 0);
8482 // If there was a non-zero offset that we didn't fold, create an explicit
8485 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8486 DAG.getConstant(Offset, getPointerTy()));
8492 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8493 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8494 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8495 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8499 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8500 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8501 unsigned char OperandFlags, bool LocalDynamic = false) {
8502 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8503 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8505 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8506 GA->getValueType(0),
8510 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8514 SDValue Ops[] = { Chain, TGA, *InFlag };
8515 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8517 SDValue Ops[] = { Chain, TGA };
8518 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8521 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8522 MFI->setAdjustsStack(true);
8524 SDValue Flag = Chain.getValue(1);
8525 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8528 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8530 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8533 SDLoc dl(GA); // ? function entry point might be better
8534 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8535 DAG.getNode(X86ISD::GlobalBaseReg,
8536 SDLoc(), PtrVT), InFlag);
8537 InFlag = Chain.getValue(1);
8539 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8542 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8544 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8546 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8547 X86::RAX, X86II::MO_TLSGD);
8550 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8556 // Get the start address of the TLS block for this module.
8557 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8558 .getInfo<X86MachineFunctionInfo>();
8559 MFI->incNumLocalDynamicTLSAccesses();
8563 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8564 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8567 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8568 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8569 InFlag = Chain.getValue(1);
8570 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8571 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8574 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8578 unsigned char OperandFlags = X86II::MO_DTPOFF;
8579 unsigned WrapperKind = X86ISD::Wrapper;
8580 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8581 GA->getValueType(0),
8582 GA->getOffset(), OperandFlags);
8583 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8585 // Add x@dtpoff with the base.
8586 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8589 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8590 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8591 const EVT PtrVT, TLSModel::Model model,
8592 bool is64Bit, bool isPIC) {
8595 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8596 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8597 is64Bit ? 257 : 256));
8599 SDValue ThreadPointer =
8600 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8601 MachinePointerInfo(Ptr), false, false, false, 0);
8603 unsigned char OperandFlags = 0;
8604 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8606 unsigned WrapperKind = X86ISD::Wrapper;
8607 if (model == TLSModel::LocalExec) {
8608 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8609 } else if (model == TLSModel::InitialExec) {
8611 OperandFlags = X86II::MO_GOTTPOFF;
8612 WrapperKind = X86ISD::WrapperRIP;
8614 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8617 llvm_unreachable("Unexpected model");
8620 // emit "addl x@ntpoff,%eax" (local exec)
8621 // or "addl x@indntpoff,%eax" (initial exec)
8622 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8624 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8625 GA->getOffset(), OperandFlags);
8626 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8628 if (model == TLSModel::InitialExec) {
8629 if (isPIC && !is64Bit) {
8630 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8631 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8635 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8636 MachinePointerInfo::getGOT(), false, false, false, 0);
8639 // The address of the thread local variable is the add of the thread
8640 // pointer with the offset of the variable.
8641 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8645 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8647 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8648 const GlobalValue *GV = GA->getGlobal();
8650 if (Subtarget->isTargetELF()) {
8651 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8654 case TLSModel::GeneralDynamic:
8655 if (Subtarget->is64Bit())
8656 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8657 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8658 case TLSModel::LocalDynamic:
8659 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8660 Subtarget->is64Bit());
8661 case TLSModel::InitialExec:
8662 case TLSModel::LocalExec:
8663 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8664 Subtarget->is64Bit(),
8665 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8667 llvm_unreachable("Unknown TLS model.");
8670 if (Subtarget->isTargetDarwin()) {
8671 // Darwin only has one model of TLS. Lower to that.
8672 unsigned char OpFlag = 0;
8673 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8674 X86ISD::WrapperRIP : X86ISD::Wrapper;
8676 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8678 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8679 !Subtarget->is64Bit();
8681 OpFlag = X86II::MO_TLVP_PIC_BASE;
8683 OpFlag = X86II::MO_TLVP;
8685 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8686 GA->getValueType(0),
8687 GA->getOffset(), OpFlag);
8688 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8690 // With PIC32, the address is actually $g + Offset.
8692 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8693 DAG.getNode(X86ISD::GlobalBaseReg,
8694 SDLoc(), getPointerTy()),
8697 // Lowering the machine isd will make sure everything is in the right
8699 SDValue Chain = DAG.getEntryNode();
8700 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8701 SDValue Args[] = { Chain, Offset };
8702 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8704 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8705 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8706 MFI->setAdjustsStack(true);
8708 // And our return value (tls address) is in the standard call return value
8710 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8711 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8715 if (Subtarget->isTargetKnownWindowsMSVC() ||
8716 Subtarget->isTargetWindowsGNU()) {
8717 // Just use the implicit TLS architecture
8718 // Need to generate someting similar to:
8719 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8721 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8722 // mov rcx, qword [rdx+rcx*8]
8723 // mov eax, .tls$:tlsvar
8724 // [rax+rcx] contains the address
8725 // Windows 64bit: gs:0x58
8726 // Windows 32bit: fs:__tls_array
8728 // If GV is an alias then use the aliasee for determining
8729 // thread-localness.
8730 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8731 GV = GA->getAliasedGlobal();
8733 SDValue Chain = DAG.getEntryNode();
8735 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8736 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8737 // use its literal value of 0x2C.
8738 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8739 ? Type::getInt8PtrTy(*DAG.getContext(),
8741 : Type::getInt32PtrTy(*DAG.getContext(),
8745 Subtarget->is64Bit()
8746 ? DAG.getIntPtrConstant(0x58)
8747 : (Subtarget->isTargetWindowsGNU()
8748 ? DAG.getIntPtrConstant(0x2C)
8749 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8751 SDValue ThreadPointer =
8752 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8753 MachinePointerInfo(Ptr), false, false, false, 0);
8755 // Load the _tls_index variable
8756 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8757 if (Subtarget->is64Bit())
8758 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8759 IDX, MachinePointerInfo(), MVT::i32,
8762 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8763 false, false, false, 0);
8765 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8767 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8769 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8770 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8771 false, false, false, 0);
8773 // Get the offset of start of .tls section
8774 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8775 GA->getValueType(0),
8776 GA->getOffset(), X86II::MO_SECREL);
8777 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8779 // The address of the thread local variable is the add of the thread
8780 // pointer with the offset of the variable.
8781 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8784 llvm_unreachable("TLS not implemented for this target.");
8787 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8788 /// and take a 2 x i32 value to shift plus a shift amount.
8789 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8790 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8791 MVT VT = Op.getSimpleValueType();
8792 unsigned VTBits = VT.getSizeInBits();
8794 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8795 SDValue ShOpLo = Op.getOperand(0);
8796 SDValue ShOpHi = Op.getOperand(1);
8797 SDValue ShAmt = Op.getOperand(2);
8798 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8799 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8801 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8802 DAG.getConstant(VTBits - 1, MVT::i8));
8803 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8804 DAG.getConstant(VTBits - 1, MVT::i8))
8805 : DAG.getConstant(0, VT);
8808 if (Op.getOpcode() == ISD::SHL_PARTS) {
8809 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8810 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8812 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8813 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8816 // If the shift amount is larger or equal than the width of a part we can't
8817 // rely on the results of shld/shrd. Insert a test and select the appropriate
8818 // values for large shift amounts.
8819 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8820 DAG.getConstant(VTBits, MVT::i8));
8821 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8822 AndNode, DAG.getConstant(0, MVT::i8));
8825 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8826 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8827 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8829 if (Op.getOpcode() == ISD::SHL_PARTS) {
8830 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8831 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8833 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8834 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8837 SDValue Ops[2] = { Lo, Hi };
8838 return DAG.getMergeValues(Ops, dl);
8841 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8842 SelectionDAG &DAG) const {
8843 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8845 if (SrcVT.isVector())
8848 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8849 "Unknown SINT_TO_FP to lower!");
8851 // These are really Legal; return the operand so the caller accepts it as
8853 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8855 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8856 Subtarget->is64Bit()) {
8861 unsigned Size = SrcVT.getSizeInBits()/8;
8862 MachineFunction &MF = DAG.getMachineFunction();
8863 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8864 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8865 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8867 MachinePointerInfo::getFixedStack(SSFI),
8869 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8872 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8874 SelectionDAG &DAG) const {
8878 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8880 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8882 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8884 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8886 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8887 MachineMemOperand *MMO;
8889 int SSFI = FI->getIndex();
8891 DAG.getMachineFunction()
8892 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8893 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8895 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8896 StackSlot = StackSlot.getOperand(1);
8898 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8899 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8901 Tys, Ops, SrcVT, MMO);
8904 Chain = Result.getValue(1);
8905 SDValue InFlag = Result.getValue(2);
8907 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8908 // shouldn't be necessary except that RFP cannot be live across
8909 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8910 MachineFunction &MF = DAG.getMachineFunction();
8911 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8912 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8913 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8914 Tys = DAG.getVTList(MVT::Other);
8916 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8918 MachineMemOperand *MMO =
8919 DAG.getMachineFunction()
8920 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8921 MachineMemOperand::MOStore, SSFISize, SSFISize);
8923 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8924 Ops, Op.getValueType(), MMO);
8925 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8926 MachinePointerInfo::getFixedStack(SSFI),
8927 false, false, false, 0);
8933 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8934 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8935 SelectionDAG &DAG) const {
8936 // This algorithm is not obvious. Here it is what we're trying to output:
8939 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8940 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8944 pshufd $0x4e, %xmm0, %xmm1
8950 LLVMContext *Context = DAG.getContext();
8952 // Build some magic constants.
8953 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8954 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8955 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8957 SmallVector<Constant*,2> CV1;
8959 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8960 APInt(64, 0x4330000000000000ULL))));
8962 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8963 APInt(64, 0x4530000000000000ULL))));
8964 Constant *C1 = ConstantVector::get(CV1);
8965 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8967 // Load the 64-bit value into an XMM register.
8968 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8970 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8971 MachinePointerInfo::getConstantPool(),
8972 false, false, false, 16);
8973 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8974 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8977 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8978 MachinePointerInfo::getConstantPool(),
8979 false, false, false, 16);
8980 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8981 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8984 if (Subtarget->hasSSE3()) {
8985 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8986 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8988 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8989 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8991 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8992 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8996 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8997 DAG.getIntPtrConstant(0));
9000 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9001 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9002 SelectionDAG &DAG) const {
9004 // FP constant to bias correct the final result.
9005 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9008 // Load the 32-bit value into an XMM register.
9009 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9012 // Zero out the upper parts of the register.
9013 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9015 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9016 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9017 DAG.getIntPtrConstant(0));
9019 // Or the load with the bias.
9020 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9021 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9022 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9024 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9025 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9026 MVT::v2f64, Bias)));
9027 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9028 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9029 DAG.getIntPtrConstant(0));
9031 // Subtract the bias.
9032 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9034 // Handle final rounding.
9035 EVT DestVT = Op.getValueType();
9037 if (DestVT.bitsLT(MVT::f64))
9038 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9039 DAG.getIntPtrConstant(0));
9040 if (DestVT.bitsGT(MVT::f64))
9041 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9043 // Handle final rounding.
9047 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9048 SelectionDAG &DAG) const {
9049 SDValue N0 = Op.getOperand(0);
9050 MVT SVT = N0.getSimpleValueType();
9053 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9054 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9055 "Custom UINT_TO_FP is not supported!");
9057 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9058 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9059 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9062 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9063 SelectionDAG &DAG) const {
9064 SDValue N0 = Op.getOperand(0);
9067 if (Op.getValueType().isVector())
9068 return lowerUINT_TO_FP_vec(Op, DAG);
9070 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9071 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9072 // the optimization here.
9073 if (DAG.SignBitIsZero(N0))
9074 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9076 MVT SrcVT = N0.getSimpleValueType();
9077 MVT DstVT = Op.getSimpleValueType();
9078 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9079 return LowerUINT_TO_FP_i64(Op, DAG);
9080 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9081 return LowerUINT_TO_FP_i32(Op, DAG);
9082 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9085 // Make a 64-bit buffer, and use it to build an FILD.
9086 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9087 if (SrcVT == MVT::i32) {
9088 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9089 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9090 getPointerTy(), StackSlot, WordOff);
9091 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9092 StackSlot, MachinePointerInfo(),
9094 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9095 OffsetSlot, MachinePointerInfo(),
9097 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9101 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9102 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9103 StackSlot, MachinePointerInfo(),
9105 // For i64 source, we need to add the appropriate power of 2 if the input
9106 // was negative. This is the same as the optimization in
9107 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9108 // we must be careful to do the computation in x87 extended precision, not
9109 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9110 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9111 MachineMemOperand *MMO =
9112 DAG.getMachineFunction()
9113 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9114 MachineMemOperand::MOLoad, 8, 8);
9116 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9117 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9118 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9121 APInt FF(32, 0x5F800000ULL);
9123 // Check whether the sign bit is set.
9124 SDValue SignSet = DAG.getSetCC(dl,
9125 getSetCCResultType(*DAG.getContext(), MVT::i64),
9126 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9129 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9130 SDValue FudgePtr = DAG.getConstantPool(
9131 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9134 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9135 SDValue Zero = DAG.getIntPtrConstant(0);
9136 SDValue Four = DAG.getIntPtrConstant(4);
9137 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9139 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9141 // Load the value out, extending it from f32 to f80.
9142 // FIXME: Avoid the extend by constructing the right constant pool?
9143 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9144 FudgePtr, MachinePointerInfo::getConstantPool(),
9145 MVT::f32, false, false, 4);
9146 // Extend everything to 80 bits to force it to be done on x87.
9147 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9148 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9151 std::pair<SDValue,SDValue>
9152 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9153 bool IsSigned, bool IsReplace) const {
9156 EVT DstTy = Op.getValueType();
9158 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9159 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9163 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9164 DstTy.getSimpleVT() >= MVT::i16 &&
9165 "Unknown FP_TO_INT to lower!");
9167 // These are really Legal.
9168 if (DstTy == MVT::i32 &&
9169 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9170 return std::make_pair(SDValue(), SDValue());
9171 if (Subtarget->is64Bit() &&
9172 DstTy == MVT::i64 &&
9173 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9174 return std::make_pair(SDValue(), SDValue());
9176 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9177 // stack slot, or into the FTOL runtime function.
9178 MachineFunction &MF = DAG.getMachineFunction();
9179 unsigned MemSize = DstTy.getSizeInBits()/8;
9180 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9181 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9184 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9185 Opc = X86ISD::WIN_FTOL;
9187 switch (DstTy.getSimpleVT().SimpleTy) {
9188 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9189 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9190 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9191 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9194 SDValue Chain = DAG.getEntryNode();
9195 SDValue Value = Op.getOperand(0);
9196 EVT TheVT = Op.getOperand(0).getValueType();
9197 // FIXME This causes a redundant load/store if the SSE-class value is already
9198 // in memory, such as if it is on the callstack.
9199 if (isScalarFPTypeInSSEReg(TheVT)) {
9200 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9201 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9202 MachinePointerInfo::getFixedStack(SSFI),
9204 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9206 Chain, StackSlot, DAG.getValueType(TheVT)
9209 MachineMemOperand *MMO =
9210 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9211 MachineMemOperand::MOLoad, MemSize, MemSize);
9212 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9213 Chain = Value.getValue(1);
9214 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9215 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9218 MachineMemOperand *MMO =
9219 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9220 MachineMemOperand::MOStore, MemSize, MemSize);
9222 if (Opc != X86ISD::WIN_FTOL) {
9223 // Build the FP_TO_INT*_IN_MEM
9224 SDValue Ops[] = { Chain, Value, StackSlot };
9225 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9227 return std::make_pair(FIST, StackSlot);
9229 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9230 DAG.getVTList(MVT::Other, MVT::Glue),
9232 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9233 MVT::i32, ftol.getValue(1));
9234 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9235 MVT::i32, eax.getValue(2));
9236 SDValue Ops[] = { eax, edx };
9237 SDValue pair = IsReplace
9238 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9239 : DAG.getMergeValues(Ops, DL);
9240 return std::make_pair(pair, SDValue());
9244 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9245 const X86Subtarget *Subtarget) {
9246 MVT VT = Op->getSimpleValueType(0);
9247 SDValue In = Op->getOperand(0);
9248 MVT InVT = In.getSimpleValueType();
9251 // Optimize vectors in AVX mode:
9254 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9255 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9256 // Concat upper and lower parts.
9259 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9260 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9261 // Concat upper and lower parts.
9264 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9265 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9266 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9269 if (Subtarget->hasInt256())
9270 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9272 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9273 SDValue Undef = DAG.getUNDEF(InVT);
9274 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9275 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9276 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9278 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9279 VT.getVectorNumElements()/2);
9281 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9282 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9284 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9287 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9288 SelectionDAG &DAG) {
9289 MVT VT = Op->getSimpleValueType(0);
9290 SDValue In = Op->getOperand(0);
9291 MVT InVT = In.getSimpleValueType();
9293 unsigned int NumElts = VT.getVectorNumElements();
9294 if (NumElts != 8 && NumElts != 16)
9297 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9298 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9300 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9301 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9302 // Now we have only mask extension
9303 assert(InVT.getVectorElementType() == MVT::i1);
9304 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9305 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9306 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9307 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9308 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9309 MachinePointerInfo::getConstantPool(),
9310 false, false, false, Alignment);
9312 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9313 if (VT.is512BitVector())
9315 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9318 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9319 SelectionDAG &DAG) {
9320 if (Subtarget->hasFp256()) {
9321 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9329 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9330 SelectionDAG &DAG) {
9332 MVT VT = Op.getSimpleValueType();
9333 SDValue In = Op.getOperand(0);
9334 MVT SVT = In.getSimpleValueType();
9336 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9337 return LowerZERO_EXTEND_AVX512(Op, DAG);
9339 if (Subtarget->hasFp256()) {
9340 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9345 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9346 VT.getVectorNumElements() != SVT.getVectorNumElements());
9350 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9352 MVT VT = Op.getSimpleValueType();
9353 SDValue In = Op.getOperand(0);
9354 MVT InVT = In.getSimpleValueType();
9356 if (VT == MVT::i1) {
9357 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9358 "Invalid scalar TRUNCATE operation");
9359 if (InVT == MVT::i32)
9361 if (InVT.getSizeInBits() == 64)
9362 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9363 else if (InVT.getSizeInBits() < 32)
9364 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9365 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9367 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9368 "Invalid TRUNCATE operation");
9370 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9371 if (VT.getVectorElementType().getSizeInBits() >=8)
9372 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9374 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9375 unsigned NumElts = InVT.getVectorNumElements();
9376 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9377 if (InVT.getSizeInBits() < 512) {
9378 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9379 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9383 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9384 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9385 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9386 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9387 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9388 MachinePointerInfo::getConstantPool(),
9389 false, false, false, Alignment);
9390 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9391 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9392 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9395 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9396 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9397 if (Subtarget->hasInt256()) {
9398 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9399 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9400 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9402 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9403 DAG.getIntPtrConstant(0));
9406 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9407 DAG.getIntPtrConstant(0));
9408 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9409 DAG.getIntPtrConstant(2));
9410 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9411 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9412 static const int ShufMask[] = {0, 2, 4, 6};
9413 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9416 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9417 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9418 if (Subtarget->hasInt256()) {
9419 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9421 SmallVector<SDValue,32> pshufbMask;
9422 for (unsigned i = 0; i < 2; ++i) {
9423 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9424 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9425 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9426 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9427 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9428 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9429 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9430 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9431 for (unsigned j = 0; j < 8; ++j)
9432 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9434 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9435 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9436 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9438 static const int ShufMask[] = {0, 2, -1, -1};
9439 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9441 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9442 DAG.getIntPtrConstant(0));
9443 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9446 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9447 DAG.getIntPtrConstant(0));
9449 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9450 DAG.getIntPtrConstant(4));
9452 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9453 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9456 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9457 -1, -1, -1, -1, -1, -1, -1, -1};
9459 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9460 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9461 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9463 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9464 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9466 // The MOVLHPS Mask:
9467 static const int ShufMask2[] = {0, 1, 4, 5};
9468 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9469 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9472 // Handle truncation of V256 to V128 using shuffles.
9473 if (!VT.is128BitVector() || !InVT.is256BitVector())
9476 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9478 unsigned NumElems = VT.getVectorNumElements();
9479 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9481 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9482 // Prepare truncation shuffle mask
9483 for (unsigned i = 0; i != NumElems; ++i)
9485 SDValue V = DAG.getVectorShuffle(NVT, DL,
9486 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9487 DAG.getUNDEF(NVT), &MaskVec[0]);
9488 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9489 DAG.getIntPtrConstant(0));
9492 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9493 SelectionDAG &DAG) const {
9494 assert(!Op.getSimpleValueType().isVector());
9496 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9497 /*IsSigned=*/ true, /*IsReplace=*/ false);
9498 SDValue FIST = Vals.first, StackSlot = Vals.second;
9499 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9500 if (!FIST.getNode()) return Op;
9502 if (StackSlot.getNode())
9504 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9505 FIST, StackSlot, MachinePointerInfo(),
9506 false, false, false, 0);
9508 // The node is the result.
9512 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9513 SelectionDAG &DAG) const {
9514 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9515 /*IsSigned=*/ false, /*IsReplace=*/ false);
9516 SDValue FIST = Vals.first, StackSlot = Vals.second;
9517 assert(FIST.getNode() && "Unexpected failure");
9519 if (StackSlot.getNode())
9521 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9522 FIST, StackSlot, MachinePointerInfo(),
9523 false, false, false, 0);
9525 // The node is the result.
9529 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9531 MVT VT = Op.getSimpleValueType();
9532 SDValue In = Op.getOperand(0);
9533 MVT SVT = In.getSimpleValueType();
9535 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9537 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9538 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9539 In, DAG.getUNDEF(SVT)));
9542 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9543 LLVMContext *Context = DAG.getContext();
9545 MVT VT = Op.getSimpleValueType();
9547 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9548 if (VT.isVector()) {
9549 EltVT = VT.getVectorElementType();
9550 NumElts = VT.getVectorNumElements();
9553 if (EltVT == MVT::f64)
9554 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9555 APInt(64, ~(1ULL << 63))));
9557 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9558 APInt(32, ~(1U << 31))));
9559 C = ConstantVector::getSplat(NumElts, C);
9560 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9561 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9562 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9563 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9564 MachinePointerInfo::getConstantPool(),
9565 false, false, false, Alignment);
9566 if (VT.isVector()) {
9567 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9568 return DAG.getNode(ISD::BITCAST, dl, VT,
9569 DAG.getNode(ISD::AND, dl, ANDVT,
9570 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9572 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9574 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9577 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9578 LLVMContext *Context = DAG.getContext();
9580 MVT VT = Op.getSimpleValueType();
9582 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9583 if (VT.isVector()) {
9584 EltVT = VT.getVectorElementType();
9585 NumElts = VT.getVectorNumElements();
9588 if (EltVT == MVT::f64)
9589 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9590 APInt(64, 1ULL << 63)));
9592 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9593 APInt(32, 1U << 31)));
9594 C = ConstantVector::getSplat(NumElts, C);
9595 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9596 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9597 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9598 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9599 MachinePointerInfo::getConstantPool(),
9600 false, false, false, Alignment);
9601 if (VT.isVector()) {
9602 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9603 return DAG.getNode(ISD::BITCAST, dl, VT,
9604 DAG.getNode(ISD::XOR, dl, XORVT,
9605 DAG.getNode(ISD::BITCAST, dl, XORVT,
9607 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9610 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9613 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9614 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9615 LLVMContext *Context = DAG.getContext();
9616 SDValue Op0 = Op.getOperand(0);
9617 SDValue Op1 = Op.getOperand(1);
9619 MVT VT = Op.getSimpleValueType();
9620 MVT SrcVT = Op1.getSimpleValueType();
9622 // If second operand is smaller, extend it first.
9623 if (SrcVT.bitsLT(VT)) {
9624 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9627 // And if it is bigger, shrink it first.
9628 if (SrcVT.bitsGT(VT)) {
9629 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9633 // At this point the operands and the result should have the same
9634 // type, and that won't be f80 since that is not custom lowered.
9636 // First get the sign bit of second operand.
9637 SmallVector<Constant*,4> CV;
9638 if (SrcVT == MVT::f64) {
9639 const fltSemantics &Sem = APFloat::IEEEdouble;
9640 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9641 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9643 const fltSemantics &Sem = APFloat::IEEEsingle;
9644 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9645 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9646 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9647 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9649 Constant *C = ConstantVector::get(CV);
9650 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9651 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9652 MachinePointerInfo::getConstantPool(),
9653 false, false, false, 16);
9654 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9656 // Shift sign bit right or left if the two operands have different types.
9657 if (SrcVT.bitsGT(VT)) {
9658 // Op0 is MVT::f32, Op1 is MVT::f64.
9659 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9660 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9661 DAG.getConstant(32, MVT::i32));
9662 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9663 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9664 DAG.getIntPtrConstant(0));
9667 // Clear first operand sign bit.
9669 if (VT == MVT::f64) {
9670 const fltSemantics &Sem = APFloat::IEEEdouble;
9671 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9672 APInt(64, ~(1ULL << 63)))));
9673 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9675 const fltSemantics &Sem = APFloat::IEEEsingle;
9676 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9677 APInt(32, ~(1U << 31)))));
9678 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9679 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9680 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9682 C = ConstantVector::get(CV);
9683 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9684 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9685 MachinePointerInfo::getConstantPool(),
9686 false, false, false, 16);
9687 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9689 // Or the value with the sign bit.
9690 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9693 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9694 SDValue N0 = Op.getOperand(0);
9696 MVT VT = Op.getSimpleValueType();
9698 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9699 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9700 DAG.getConstant(1, VT));
9701 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9704 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9706 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9707 SelectionDAG &DAG) {
9708 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9710 if (!Subtarget->hasSSE41())
9713 if (!Op->hasOneUse())
9716 SDNode *N = Op.getNode();
9719 SmallVector<SDValue, 8> Opnds;
9720 DenseMap<SDValue, unsigned> VecInMap;
9721 SmallVector<SDValue, 8> VecIns;
9722 EVT VT = MVT::Other;
9724 // Recognize a special case where a vector is casted into wide integer to
9726 Opnds.push_back(N->getOperand(0));
9727 Opnds.push_back(N->getOperand(1));
9729 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9730 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9731 // BFS traverse all OR'd operands.
9732 if (I->getOpcode() == ISD::OR) {
9733 Opnds.push_back(I->getOperand(0));
9734 Opnds.push_back(I->getOperand(1));
9735 // Re-evaluate the number of nodes to be traversed.
9736 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9740 // Quit if a non-EXTRACT_VECTOR_ELT
9741 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9744 // Quit if without a constant index.
9745 SDValue Idx = I->getOperand(1);
9746 if (!isa<ConstantSDNode>(Idx))
9749 SDValue ExtractedFromVec = I->getOperand(0);
9750 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9751 if (M == VecInMap.end()) {
9752 VT = ExtractedFromVec.getValueType();
9753 // Quit if not 128/256-bit vector.
9754 if (!VT.is128BitVector() && !VT.is256BitVector())
9756 // Quit if not the same type.
9757 if (VecInMap.begin() != VecInMap.end() &&
9758 VT != VecInMap.begin()->first.getValueType())
9760 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9761 VecIns.push_back(ExtractedFromVec);
9763 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9766 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9767 "Not extracted from 128-/256-bit vector.");
9769 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9771 for (DenseMap<SDValue, unsigned>::const_iterator
9772 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9773 // Quit if not all elements are used.
9774 if (I->second != FullMask)
9778 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9780 // Cast all vectors into TestVT for PTEST.
9781 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9782 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9784 // If more than one full vectors are evaluated, OR them first before PTEST.
9785 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9786 // Each iteration will OR 2 nodes and append the result until there is only
9787 // 1 node left, i.e. the final OR'd value of all vectors.
9788 SDValue LHS = VecIns[Slot];
9789 SDValue RHS = VecIns[Slot + 1];
9790 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9793 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9794 VecIns.back(), VecIns.back());
9797 /// \brief return true if \c Op has a use that doesn't just read flags.
9798 static bool hasNonFlagsUse(SDValue Op) {
9799 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9802 unsigned UOpNo = UI.getOperandNo();
9803 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9804 // Look pass truncate.
9805 UOpNo = User->use_begin().getOperandNo();
9806 User = *User->use_begin();
9809 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9810 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9816 /// Emit nodes that will be selected as "test Op0,Op0", or something
9818 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9819 SelectionDAG &DAG) const {
9820 if (Op.getValueType() == MVT::i1)
9821 // KORTEST instruction should be selected
9822 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9823 DAG.getConstant(0, Op.getValueType()));
9825 // CF and OF aren't always set the way we want. Determine which
9826 // of these we need.
9827 bool NeedCF = false;
9828 bool NeedOF = false;
9831 case X86::COND_A: case X86::COND_AE:
9832 case X86::COND_B: case X86::COND_BE:
9835 case X86::COND_G: case X86::COND_GE:
9836 case X86::COND_L: case X86::COND_LE:
9837 case X86::COND_O: case X86::COND_NO:
9841 // See if we can use the EFLAGS value from the operand instead of
9842 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9843 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9844 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9845 // Emit a CMP with 0, which is the TEST pattern.
9846 //if (Op.getValueType() == MVT::i1)
9847 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9848 // DAG.getConstant(0, MVT::i1));
9849 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9850 DAG.getConstant(0, Op.getValueType()));
9852 unsigned Opcode = 0;
9853 unsigned NumOperands = 0;
9855 // Truncate operations may prevent the merge of the SETCC instruction
9856 // and the arithmetic instruction before it. Attempt to truncate the operands
9857 // of the arithmetic instruction and use a reduced bit-width instruction.
9858 bool NeedTruncation = false;
9859 SDValue ArithOp = Op;
9860 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9861 SDValue Arith = Op->getOperand(0);
9862 // Both the trunc and the arithmetic op need to have one user each.
9863 if (Arith->hasOneUse())
9864 switch (Arith.getOpcode()) {
9871 NeedTruncation = true;
9877 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9878 // which may be the result of a CAST. We use the variable 'Op', which is the
9879 // non-casted variable when we check for possible users.
9880 switch (ArithOp.getOpcode()) {
9882 // Due to an isel shortcoming, be conservative if this add is likely to be
9883 // selected as part of a load-modify-store instruction. When the root node
9884 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9885 // uses of other nodes in the match, such as the ADD in this case. This
9886 // leads to the ADD being left around and reselected, with the result being
9887 // two adds in the output. Alas, even if none our users are stores, that
9888 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9889 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9890 // climbing the DAG back to the root, and it doesn't seem to be worth the
9892 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9893 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9894 if (UI->getOpcode() != ISD::CopyToReg &&
9895 UI->getOpcode() != ISD::SETCC &&
9896 UI->getOpcode() != ISD::STORE)
9899 if (ConstantSDNode *C =
9900 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9901 // An add of one will be selected as an INC.
9902 if (C->getAPIntValue() == 1) {
9903 Opcode = X86ISD::INC;
9908 // An add of negative one (subtract of one) will be selected as a DEC.
9909 if (C->getAPIntValue().isAllOnesValue()) {
9910 Opcode = X86ISD::DEC;
9916 // Otherwise use a regular EFLAGS-setting add.
9917 Opcode = X86ISD::ADD;
9922 // If we have a constant logical shift that's only used in a comparison
9923 // against zero turn it into an equivalent AND. This allows turning it into
9924 // a TEST instruction later.
9925 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9926 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9927 EVT VT = Op.getValueType();
9928 unsigned BitWidth = VT.getSizeInBits();
9929 unsigned ShAmt = Op->getConstantOperandVal(1);
9930 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9932 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9933 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9934 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9935 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9937 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9938 DAG.getConstant(Mask, VT));
9939 DAG.ReplaceAllUsesWith(Op, New);
9945 // If the primary and result isn't used, don't bother using X86ISD::AND,
9946 // because a TEST instruction will be better.
9947 if (!hasNonFlagsUse(Op))
9953 // Due to the ISEL shortcoming noted above, be conservative if this op is
9954 // likely to be selected as part of a load-modify-store instruction.
9955 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9956 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9957 if (UI->getOpcode() == ISD::STORE)
9960 // Otherwise use a regular EFLAGS-setting instruction.
9961 switch (ArithOp.getOpcode()) {
9962 default: llvm_unreachable("unexpected operator!");
9963 case ISD::SUB: Opcode = X86ISD::SUB; break;
9964 case ISD::XOR: Opcode = X86ISD::XOR; break;
9965 case ISD::AND: Opcode = X86ISD::AND; break;
9967 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9968 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9969 if (EFLAGS.getNode())
9972 Opcode = X86ISD::OR;
9986 return SDValue(Op.getNode(), 1);
9992 // If we found that truncation is beneficial, perform the truncation and
9994 if (NeedTruncation) {
9995 EVT VT = Op.getValueType();
9996 SDValue WideVal = Op->getOperand(0);
9997 EVT WideVT = WideVal.getValueType();
9998 unsigned ConvertedOp = 0;
9999 // Use a target machine opcode to prevent further DAGCombine
10000 // optimizations that may separate the arithmetic operations
10001 // from the setcc node.
10002 switch (WideVal.getOpcode()) {
10004 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10005 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10006 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10007 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10008 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10012 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10013 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10014 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10015 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10016 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10022 // Emit a CMP with 0, which is the TEST pattern.
10023 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10024 DAG.getConstant(0, Op.getValueType()));
10026 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10027 SmallVector<SDValue, 4> Ops;
10028 for (unsigned i = 0; i != NumOperands; ++i)
10029 Ops.push_back(Op.getOperand(i));
10031 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10032 DAG.ReplaceAllUsesWith(Op, New);
10033 return SDValue(New.getNode(), 1);
10036 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10038 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10039 SDLoc dl, SelectionDAG &DAG) const {
10040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10041 if (C->getAPIntValue() == 0)
10042 return EmitTest(Op0, X86CC, dl, DAG);
10044 if (Op0.getValueType() == MVT::i1)
10045 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10048 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10049 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10050 // Do the comparison at i32 if it's smaller, besides the Atom case.
10051 // This avoids subregister aliasing issues. Keep the smaller reference
10052 // if we're optimizing for size, however, as that'll allow better folding
10053 // of memory operations.
10054 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10055 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10056 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10057 !Subtarget->isAtom()) {
10058 unsigned ExtendOp =
10059 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10060 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10061 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10063 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10064 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10065 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10067 return SDValue(Sub.getNode(), 1);
10069 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10072 /// Convert a comparison if required by the subtarget.
10073 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10074 SelectionDAG &DAG) const {
10075 // If the subtarget does not support the FUCOMI instruction, floating-point
10076 // comparisons have to be converted.
10077 if (Subtarget->hasCMov() ||
10078 Cmp.getOpcode() != X86ISD::CMP ||
10079 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10080 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10083 // The instruction selector will select an FUCOM instruction instead of
10084 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10085 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10086 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10088 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10089 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10090 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10091 DAG.getConstant(8, MVT::i8));
10092 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10093 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10096 static bool isAllOnes(SDValue V) {
10097 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10098 return C && C->isAllOnesValue();
10101 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10102 /// if it's possible.
10103 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10104 SDLoc dl, SelectionDAG &DAG) const {
10105 SDValue Op0 = And.getOperand(0);
10106 SDValue Op1 = And.getOperand(1);
10107 if (Op0.getOpcode() == ISD::TRUNCATE)
10108 Op0 = Op0.getOperand(0);
10109 if (Op1.getOpcode() == ISD::TRUNCATE)
10110 Op1 = Op1.getOperand(0);
10113 if (Op1.getOpcode() == ISD::SHL)
10114 std::swap(Op0, Op1);
10115 if (Op0.getOpcode() == ISD::SHL) {
10116 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10117 if (And00C->getZExtValue() == 1) {
10118 // If we looked past a truncate, check that it's only truncating away
10120 unsigned BitWidth = Op0.getValueSizeInBits();
10121 unsigned AndBitWidth = And.getValueSizeInBits();
10122 if (BitWidth > AndBitWidth) {
10124 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10125 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10129 RHS = Op0.getOperand(1);
10131 } else if (Op1.getOpcode() == ISD::Constant) {
10132 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10133 uint64_t AndRHSVal = AndRHS->getZExtValue();
10134 SDValue AndLHS = Op0;
10136 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10137 LHS = AndLHS.getOperand(0);
10138 RHS = AndLHS.getOperand(1);
10141 // Use BT if the immediate can't be encoded in a TEST instruction.
10142 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10144 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10148 if (LHS.getNode()) {
10149 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10150 // instruction. Since the shift amount is in-range-or-undefined, we know
10151 // that doing a bittest on the i32 value is ok. We extend to i32 because
10152 // the encoding for the i16 version is larger than the i32 version.
10153 // Also promote i16 to i32 for performance / code size reason.
10154 if (LHS.getValueType() == MVT::i8 ||
10155 LHS.getValueType() == MVT::i16)
10156 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10158 // If the operand types disagree, extend the shift amount to match. Since
10159 // BT ignores high bits (like shifts) we can use anyextend.
10160 if (LHS.getValueType() != RHS.getValueType())
10161 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10163 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10164 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10165 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10166 DAG.getConstant(Cond, MVT::i8), BT);
10172 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10174 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10179 // SSE Condition code mapping:
10188 switch (SetCCOpcode) {
10189 default: llvm_unreachable("Unexpected SETCC condition");
10191 case ISD::SETEQ: SSECC = 0; break;
10193 case ISD::SETGT: Swap = true; // Fallthrough
10195 case ISD::SETOLT: SSECC = 1; break;
10197 case ISD::SETGE: Swap = true; // Fallthrough
10199 case ISD::SETOLE: SSECC = 2; break;
10200 case ISD::SETUO: SSECC = 3; break;
10202 case ISD::SETNE: SSECC = 4; break;
10203 case ISD::SETULE: Swap = true; // Fallthrough
10204 case ISD::SETUGE: SSECC = 5; break;
10205 case ISD::SETULT: Swap = true; // Fallthrough
10206 case ISD::SETUGT: SSECC = 6; break;
10207 case ISD::SETO: SSECC = 7; break;
10209 case ISD::SETONE: SSECC = 8; break;
10212 std::swap(Op0, Op1);
10217 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10218 // ones, and then concatenate the result back.
10219 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10220 MVT VT = Op.getSimpleValueType();
10222 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10223 "Unsupported value type for operation");
10225 unsigned NumElems = VT.getVectorNumElements();
10227 SDValue CC = Op.getOperand(2);
10229 // Extract the LHS vectors
10230 SDValue LHS = Op.getOperand(0);
10231 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10232 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10234 // Extract the RHS vectors
10235 SDValue RHS = Op.getOperand(1);
10236 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10237 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10239 // Issue the operation on the smaller types and concatenate the result back
10240 MVT EltVT = VT.getVectorElementType();
10241 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10242 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10243 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10244 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10247 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10248 const X86Subtarget *Subtarget) {
10249 SDValue Op0 = Op.getOperand(0);
10250 SDValue Op1 = Op.getOperand(1);
10251 SDValue CC = Op.getOperand(2);
10252 MVT VT = Op.getSimpleValueType();
10255 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10256 Op.getValueType().getScalarType() == MVT::i1 &&
10257 "Cannot set masked compare for this operation");
10259 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10261 bool Unsigned = false;
10264 switch (SetCCOpcode) {
10265 default: llvm_unreachable("Unexpected SETCC condition");
10266 case ISD::SETNE: SSECC = 4; break;
10267 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10268 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10269 case ISD::SETLT: Swap = true; //fall-through
10270 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10271 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10272 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10273 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10274 case ISD::SETULE: Unsigned = true; //fall-through
10275 case ISD::SETLE: SSECC = 2; break;
10279 std::swap(Op0, Op1);
10281 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10282 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10283 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10284 DAG.getConstant(SSECC, MVT::i8));
10287 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10288 /// operand \p Op1. If non-trivial (for example because it's not constant)
10289 /// return an empty value.
10290 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10292 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10296 MVT VT = Op1.getSimpleValueType();
10297 MVT EVT = VT.getVectorElementType();
10298 unsigned n = VT.getVectorNumElements();
10299 SmallVector<SDValue, 8> ULTOp1;
10301 for (unsigned i = 0; i < n; ++i) {
10302 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10303 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10306 // Avoid underflow.
10307 APInt Val = Elt->getAPIntValue();
10311 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10314 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10317 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10318 SelectionDAG &DAG) {
10319 SDValue Op0 = Op.getOperand(0);
10320 SDValue Op1 = Op.getOperand(1);
10321 SDValue CC = Op.getOperand(2);
10322 MVT VT = Op.getSimpleValueType();
10323 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10324 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10329 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10330 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10333 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10334 unsigned Opc = X86ISD::CMPP;
10335 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10336 assert(VT.getVectorNumElements() <= 16);
10337 Opc = X86ISD::CMPM;
10339 // In the two special cases we can't handle, emit two comparisons.
10342 unsigned CombineOpc;
10343 if (SetCCOpcode == ISD::SETUEQ) {
10344 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10346 assert(SetCCOpcode == ISD::SETONE);
10347 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10350 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10351 DAG.getConstant(CC0, MVT::i8));
10352 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10353 DAG.getConstant(CC1, MVT::i8));
10354 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10356 // Handle all other FP comparisons here.
10357 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10358 DAG.getConstant(SSECC, MVT::i8));
10361 // Break 256-bit integer vector compare into smaller ones.
10362 if (VT.is256BitVector() && !Subtarget->hasInt256())
10363 return Lower256IntVSETCC(Op, DAG);
10365 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10366 EVT OpVT = Op1.getValueType();
10367 if (Subtarget->hasAVX512()) {
10368 if (Op1.getValueType().is512BitVector() ||
10369 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10370 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10372 // In AVX-512 architecture setcc returns mask with i1 elements,
10373 // But there is no compare instruction for i8 and i16 elements.
10374 // We are not talking about 512-bit operands in this case, these
10375 // types are illegal.
10377 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10378 OpVT.getVectorElementType().getSizeInBits() >= 8))
10379 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10380 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10383 // We are handling one of the integer comparisons here. Since SSE only has
10384 // GT and EQ comparisons for integer, swapping operands and multiple
10385 // operations may be required for some comparisons.
10387 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10388 bool Subus = false;
10390 switch (SetCCOpcode) {
10391 default: llvm_unreachable("Unexpected SETCC condition");
10392 case ISD::SETNE: Invert = true;
10393 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10394 case ISD::SETLT: Swap = true;
10395 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10396 case ISD::SETGE: Swap = true;
10397 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10398 Invert = true; break;
10399 case ISD::SETULT: Swap = true;
10400 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10401 FlipSigns = true; break;
10402 case ISD::SETUGE: Swap = true;
10403 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10404 FlipSigns = true; Invert = true; break;
10407 // Special case: Use min/max operations for SETULE/SETUGE
10408 MVT VET = VT.getVectorElementType();
10410 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10411 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10414 switch (SetCCOpcode) {
10416 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10417 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10420 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10423 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10424 if (!MinMax && hasSubus) {
10425 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10427 // t = psubus Op0, Op1
10428 // pcmpeq t, <0..0>
10429 switch (SetCCOpcode) {
10431 case ISD::SETULT: {
10432 // If the comparison is against a constant we can turn this into a
10433 // setule. With psubus, setule does not require a swap. This is
10434 // beneficial because the constant in the register is no longer
10435 // destructed as the destination so it can be hoisted out of a loop.
10436 // Only do this pre-AVX since vpcmp* is no longer destructive.
10437 if (Subtarget->hasAVX())
10439 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10440 if (ULEOp1.getNode()) {
10442 Subus = true; Invert = false; Swap = false;
10446 // Psubus is better than flip-sign because it requires no inversion.
10447 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10448 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10452 Opc = X86ISD::SUBUS;
10458 std::swap(Op0, Op1);
10460 // Check that the operation in question is available (most are plain SSE2,
10461 // but PCMPGTQ and PCMPEQQ have different requirements).
10462 if (VT == MVT::v2i64) {
10463 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10464 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10466 // First cast everything to the right type.
10467 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10468 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10470 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10471 // bits of the inputs before performing those operations. The lower
10472 // compare is always unsigned.
10475 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10477 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10478 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10479 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10480 Sign, Zero, Sign, Zero);
10482 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10483 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10485 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10486 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10487 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10489 // Create masks for only the low parts/high parts of the 64 bit integers.
10490 static const int MaskHi[] = { 1, 1, 3, 3 };
10491 static const int MaskLo[] = { 0, 0, 2, 2 };
10492 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10493 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10494 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10496 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10497 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10500 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10502 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10505 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10506 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10507 // pcmpeqd + pshufd + pand.
10508 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10510 // First cast everything to the right type.
10511 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10512 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10515 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10517 // Make sure the lower and upper halves are both all-ones.
10518 static const int Mask[] = { 1, 0, 3, 2 };
10519 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10520 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10523 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10525 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10529 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10530 // bits of the inputs before performing those operations.
10532 EVT EltVT = VT.getVectorElementType();
10533 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10534 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10535 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10538 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10540 // If the logical-not of the result is required, perform that now.
10542 Result = DAG.getNOT(dl, Result, VT);
10545 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10548 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10549 getZeroVector(VT, Subtarget, DAG, dl));
10554 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10556 MVT VT = Op.getSimpleValueType();
10558 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10560 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10561 && "SetCC type must be 8-bit or 1-bit integer");
10562 SDValue Op0 = Op.getOperand(0);
10563 SDValue Op1 = Op.getOperand(1);
10565 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10567 // Optimize to BT if possible.
10568 // Lower (X & (1 << N)) == 0 to BT(X, N).
10569 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10570 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10571 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10572 Op1.getOpcode() == ISD::Constant &&
10573 cast<ConstantSDNode>(Op1)->isNullValue() &&
10574 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10575 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10576 if (NewSetCC.getNode())
10580 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10582 if (Op1.getOpcode() == ISD::Constant &&
10583 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10584 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10585 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10587 // If the input is a setcc, then reuse the input setcc or use a new one with
10588 // the inverted condition.
10589 if (Op0.getOpcode() == X86ISD::SETCC) {
10590 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10591 bool Invert = (CC == ISD::SETNE) ^
10592 cast<ConstantSDNode>(Op1)->isNullValue();
10596 CCode = X86::GetOppositeBranchCondition(CCode);
10597 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10598 DAG.getConstant(CCode, MVT::i8),
10599 Op0.getOperand(1));
10601 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10605 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10606 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10607 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10609 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10610 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10613 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10614 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10615 if (X86CC == X86::COND_INVALID)
10618 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10619 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10620 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10621 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10623 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10627 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10628 static bool isX86LogicalCmp(SDValue Op) {
10629 unsigned Opc = Op.getNode()->getOpcode();
10630 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10631 Opc == X86ISD::SAHF)
10633 if (Op.getResNo() == 1 &&
10634 (Opc == X86ISD::ADD ||
10635 Opc == X86ISD::SUB ||
10636 Opc == X86ISD::ADC ||
10637 Opc == X86ISD::SBB ||
10638 Opc == X86ISD::SMUL ||
10639 Opc == X86ISD::UMUL ||
10640 Opc == X86ISD::INC ||
10641 Opc == X86ISD::DEC ||
10642 Opc == X86ISD::OR ||
10643 Opc == X86ISD::XOR ||
10644 Opc == X86ISD::AND))
10647 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10653 static bool isZero(SDValue V) {
10654 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10655 return C && C->isNullValue();
10658 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10659 if (V.getOpcode() != ISD::TRUNCATE)
10662 SDValue VOp0 = V.getOperand(0);
10663 unsigned InBits = VOp0.getValueSizeInBits();
10664 unsigned Bits = V.getValueSizeInBits();
10665 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10668 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10669 bool addTest = true;
10670 SDValue Cond = Op.getOperand(0);
10671 SDValue Op1 = Op.getOperand(1);
10672 SDValue Op2 = Op.getOperand(2);
10674 EVT VT = Op1.getValueType();
10677 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10678 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10679 // sequence later on.
10680 if (Cond.getOpcode() == ISD::SETCC &&
10681 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10682 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10683 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10684 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10685 int SSECC = translateX86FSETCC(
10686 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10689 if (Subtarget->hasAVX512()) {
10690 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10691 DAG.getConstant(SSECC, MVT::i8));
10692 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10694 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10695 DAG.getConstant(SSECC, MVT::i8));
10696 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10697 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10698 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10702 if (Cond.getOpcode() == ISD::SETCC) {
10703 SDValue NewCond = LowerSETCC(Cond, DAG);
10704 if (NewCond.getNode())
10708 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10709 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10710 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10711 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10712 if (Cond.getOpcode() == X86ISD::SETCC &&
10713 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10714 isZero(Cond.getOperand(1).getOperand(1))) {
10715 SDValue Cmp = Cond.getOperand(1);
10717 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10719 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10720 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10721 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10723 SDValue CmpOp0 = Cmp.getOperand(0);
10724 // Apply further optimizations for special cases
10725 // (select (x != 0), -1, 0) -> neg & sbb
10726 // (select (x == 0), 0, -1) -> neg & sbb
10727 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10728 if (YC->isNullValue() &&
10729 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10730 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10731 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10732 DAG.getConstant(0, CmpOp0.getValueType()),
10734 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10735 DAG.getConstant(X86::COND_B, MVT::i8),
10736 SDValue(Neg.getNode(), 1));
10740 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10741 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10742 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10744 SDValue Res = // Res = 0 or -1.
10745 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10746 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10748 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10749 Res = DAG.getNOT(DL, Res, Res.getValueType());
10751 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10752 if (!N2C || !N2C->isNullValue())
10753 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10758 // Look past (and (setcc_carry (cmp ...)), 1).
10759 if (Cond.getOpcode() == ISD::AND &&
10760 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10761 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10762 if (C && C->getAPIntValue() == 1)
10763 Cond = Cond.getOperand(0);
10766 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10767 // setting operand in place of the X86ISD::SETCC.
10768 unsigned CondOpcode = Cond.getOpcode();
10769 if (CondOpcode == X86ISD::SETCC ||
10770 CondOpcode == X86ISD::SETCC_CARRY) {
10771 CC = Cond.getOperand(0);
10773 SDValue Cmp = Cond.getOperand(1);
10774 unsigned Opc = Cmp.getOpcode();
10775 MVT VT = Op.getSimpleValueType();
10777 bool IllegalFPCMov = false;
10778 if (VT.isFloatingPoint() && !VT.isVector() &&
10779 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10780 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10782 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10783 Opc == X86ISD::BT) { // FIXME
10787 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10788 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10789 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10790 Cond.getOperand(0).getValueType() != MVT::i8)) {
10791 SDValue LHS = Cond.getOperand(0);
10792 SDValue RHS = Cond.getOperand(1);
10793 unsigned X86Opcode;
10796 switch (CondOpcode) {
10797 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10798 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10799 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10800 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10801 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10802 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10803 default: llvm_unreachable("unexpected overflowing operator");
10805 if (CondOpcode == ISD::UMULO)
10806 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10809 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10811 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10813 if (CondOpcode == ISD::UMULO)
10814 Cond = X86Op.getValue(2);
10816 Cond = X86Op.getValue(1);
10818 CC = DAG.getConstant(X86Cond, MVT::i8);
10823 // Look pass the truncate if the high bits are known zero.
10824 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10825 Cond = Cond.getOperand(0);
10827 // We know the result of AND is compared against zero. Try to match
10829 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10830 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10831 if (NewSetCC.getNode()) {
10832 CC = NewSetCC.getOperand(0);
10833 Cond = NewSetCC.getOperand(1);
10840 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10841 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10844 // a < b ? -1 : 0 -> RES = ~setcc_carry
10845 // a < b ? 0 : -1 -> RES = setcc_carry
10846 // a >= b ? -1 : 0 -> RES = setcc_carry
10847 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10848 if (Cond.getOpcode() == X86ISD::SUB) {
10849 Cond = ConvertCmpIfNecessary(Cond, DAG);
10850 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10852 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10853 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10854 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10855 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10856 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10857 return DAG.getNOT(DL, Res, Res.getValueType());
10862 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10863 // widen the cmov and push the truncate through. This avoids introducing a new
10864 // branch during isel and doesn't add any extensions.
10865 if (Op.getValueType() == MVT::i8 &&
10866 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10867 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10868 if (T1.getValueType() == T2.getValueType() &&
10869 // Blacklist CopyFromReg to avoid partial register stalls.
10870 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10871 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10872 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10873 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10877 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10878 // condition is true.
10879 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10880 SDValue Ops[] = { Op2, Op1, CC, Cond };
10881 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10884 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10885 MVT VT = Op->getSimpleValueType(0);
10886 SDValue In = Op->getOperand(0);
10887 MVT InVT = In.getSimpleValueType();
10890 unsigned int NumElts = VT.getVectorNumElements();
10891 if (NumElts != 8 && NumElts != 16)
10894 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10895 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10898 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10900 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10901 Constant *C = ConstantInt::get(*DAG.getContext(),
10902 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10904 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10905 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10906 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10907 MachinePointerInfo::getConstantPool(),
10908 false, false, false, Alignment);
10909 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10910 if (VT.is512BitVector())
10912 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10915 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10916 SelectionDAG &DAG) {
10917 MVT VT = Op->getSimpleValueType(0);
10918 SDValue In = Op->getOperand(0);
10919 MVT InVT = In.getSimpleValueType();
10922 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10923 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10925 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10926 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10927 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10930 if (Subtarget->hasInt256())
10931 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10933 // Optimize vectors in AVX mode
10934 // Sign extend v8i16 to v8i32 and
10937 // Divide input vector into two parts
10938 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10939 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10940 // concat the vectors to original VT
10942 unsigned NumElems = InVT.getVectorNumElements();
10943 SDValue Undef = DAG.getUNDEF(InVT);
10945 SmallVector<int,8> ShufMask1(NumElems, -1);
10946 for (unsigned i = 0; i != NumElems/2; ++i)
10949 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10951 SmallVector<int,8> ShufMask2(NumElems, -1);
10952 for (unsigned i = 0; i != NumElems/2; ++i)
10953 ShufMask2[i] = i + NumElems/2;
10955 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10957 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10958 VT.getVectorNumElements()/2);
10960 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10961 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10963 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10966 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10967 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10968 // from the AND / OR.
10969 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10970 Opc = Op.getOpcode();
10971 if (Opc != ISD::OR && Opc != ISD::AND)
10973 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10974 Op.getOperand(0).hasOneUse() &&
10975 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10976 Op.getOperand(1).hasOneUse());
10979 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10980 // 1 and that the SETCC node has a single use.
10981 static bool isXor1OfSetCC(SDValue Op) {
10982 if (Op.getOpcode() != ISD::XOR)
10984 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10985 if (N1C && N1C->getAPIntValue() == 1) {
10986 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10987 Op.getOperand(0).hasOneUse();
10992 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10993 bool addTest = true;
10994 SDValue Chain = Op.getOperand(0);
10995 SDValue Cond = Op.getOperand(1);
10996 SDValue Dest = Op.getOperand(2);
10999 bool Inverted = false;
11001 if (Cond.getOpcode() == ISD::SETCC) {
11002 // Check for setcc([su]{add,sub,mul}o == 0).
11003 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11004 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11005 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11006 Cond.getOperand(0).getResNo() == 1 &&
11007 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11008 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11009 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11010 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11011 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11012 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11014 Cond = Cond.getOperand(0);
11016 SDValue NewCond = LowerSETCC(Cond, DAG);
11017 if (NewCond.getNode())
11022 // FIXME: LowerXALUO doesn't handle these!!
11023 else if (Cond.getOpcode() == X86ISD::ADD ||
11024 Cond.getOpcode() == X86ISD::SUB ||
11025 Cond.getOpcode() == X86ISD::SMUL ||
11026 Cond.getOpcode() == X86ISD::UMUL)
11027 Cond = LowerXALUO(Cond, DAG);
11030 // Look pass (and (setcc_carry (cmp ...)), 1).
11031 if (Cond.getOpcode() == ISD::AND &&
11032 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11033 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11034 if (C && C->getAPIntValue() == 1)
11035 Cond = Cond.getOperand(0);
11038 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11039 // setting operand in place of the X86ISD::SETCC.
11040 unsigned CondOpcode = Cond.getOpcode();
11041 if (CondOpcode == X86ISD::SETCC ||
11042 CondOpcode == X86ISD::SETCC_CARRY) {
11043 CC = Cond.getOperand(0);
11045 SDValue Cmp = Cond.getOperand(1);
11046 unsigned Opc = Cmp.getOpcode();
11047 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11048 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11052 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11056 // These can only come from an arithmetic instruction with overflow,
11057 // e.g. SADDO, UADDO.
11058 Cond = Cond.getNode()->getOperand(1);
11064 CondOpcode = Cond.getOpcode();
11065 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11066 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11067 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11068 Cond.getOperand(0).getValueType() != MVT::i8)) {
11069 SDValue LHS = Cond.getOperand(0);
11070 SDValue RHS = Cond.getOperand(1);
11071 unsigned X86Opcode;
11074 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11075 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11077 switch (CondOpcode) {
11078 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11080 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11082 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11085 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11086 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11090 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11093 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11094 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11095 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11096 default: llvm_unreachable("unexpected overflowing operator");
11099 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11100 if (CondOpcode == ISD::UMULO)
11101 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11104 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11106 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11108 if (CondOpcode == ISD::UMULO)
11109 Cond = X86Op.getValue(2);
11111 Cond = X86Op.getValue(1);
11113 CC = DAG.getConstant(X86Cond, MVT::i8);
11117 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11118 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11119 if (CondOpc == ISD::OR) {
11120 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11121 // two branches instead of an explicit OR instruction with a
11123 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11124 isX86LogicalCmp(Cmp)) {
11125 CC = Cond.getOperand(0).getOperand(0);
11126 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11127 Chain, Dest, CC, Cmp);
11128 CC = Cond.getOperand(1).getOperand(0);
11132 } else { // ISD::AND
11133 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11134 // two branches instead of an explicit AND instruction with a
11135 // separate test. However, we only do this if this block doesn't
11136 // have a fall-through edge, because this requires an explicit
11137 // jmp when the condition is false.
11138 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11139 isX86LogicalCmp(Cmp) &&
11140 Op.getNode()->hasOneUse()) {
11141 X86::CondCode CCode =
11142 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11143 CCode = X86::GetOppositeBranchCondition(CCode);
11144 CC = DAG.getConstant(CCode, MVT::i8);
11145 SDNode *User = *Op.getNode()->use_begin();
11146 // Look for an unconditional branch following this conditional branch.
11147 // We need this because we need to reverse the successors in order
11148 // to implement FCMP_OEQ.
11149 if (User->getOpcode() == ISD::BR) {
11150 SDValue FalseBB = User->getOperand(1);
11152 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11153 assert(NewBR == User);
11157 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11158 Chain, Dest, CC, Cmp);
11159 X86::CondCode CCode =
11160 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11161 CCode = X86::GetOppositeBranchCondition(CCode);
11162 CC = DAG.getConstant(CCode, MVT::i8);
11168 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11169 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11170 // It should be transformed during dag combiner except when the condition
11171 // is set by a arithmetics with overflow node.
11172 X86::CondCode CCode =
11173 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11174 CCode = X86::GetOppositeBranchCondition(CCode);
11175 CC = DAG.getConstant(CCode, MVT::i8);
11176 Cond = Cond.getOperand(0).getOperand(1);
11178 } else if (Cond.getOpcode() == ISD::SETCC &&
11179 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11180 // For FCMP_OEQ, we can emit
11181 // two branches instead of an explicit AND instruction with a
11182 // separate test. However, we only do this if this block doesn't
11183 // have a fall-through edge, because this requires an explicit
11184 // jmp when the condition is false.
11185 if (Op.getNode()->hasOneUse()) {
11186 SDNode *User = *Op.getNode()->use_begin();
11187 // Look for an unconditional branch following this conditional branch.
11188 // We need this because we need to reverse the successors in order
11189 // to implement FCMP_OEQ.
11190 if (User->getOpcode() == ISD::BR) {
11191 SDValue FalseBB = User->getOperand(1);
11193 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11194 assert(NewBR == User);
11198 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11199 Cond.getOperand(0), Cond.getOperand(1));
11200 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11201 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11202 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11203 Chain, Dest, CC, Cmp);
11204 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11209 } else if (Cond.getOpcode() == ISD::SETCC &&
11210 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11211 // For FCMP_UNE, we can emit
11212 // two branches instead of an explicit AND instruction with a
11213 // separate test. However, we only do this if this block doesn't
11214 // have a fall-through edge, because this requires an explicit
11215 // jmp when the condition is false.
11216 if (Op.getNode()->hasOneUse()) {
11217 SDNode *User = *Op.getNode()->use_begin();
11218 // Look for an unconditional branch following this conditional branch.
11219 // We need this because we need to reverse the successors in order
11220 // to implement FCMP_UNE.
11221 if (User->getOpcode() == ISD::BR) {
11222 SDValue FalseBB = User->getOperand(1);
11224 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11225 assert(NewBR == User);
11228 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11229 Cond.getOperand(0), Cond.getOperand(1));
11230 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11231 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11232 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11233 Chain, Dest, CC, Cmp);
11234 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11244 // Look pass the truncate if the high bits are known zero.
11245 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11246 Cond = Cond.getOperand(0);
11248 // We know the result of AND is compared against zero. Try to match
11250 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11251 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11252 if (NewSetCC.getNode()) {
11253 CC = NewSetCC.getOperand(0);
11254 Cond = NewSetCC.getOperand(1);
11261 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11262 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11264 Cond = ConvertCmpIfNecessary(Cond, DAG);
11265 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11266 Chain, Dest, CC, Cond);
11269 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11270 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11271 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11272 // that the guard pages used by the OS virtual memory manager are allocated in
11273 // correct sequence.
11275 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11276 SelectionDAG &DAG) const {
11277 MachineFunction &MF = DAG.getMachineFunction();
11278 bool SplitStack = MF.shouldSplitStack();
11279 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11284 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11285 SDNode* Node = Op.getNode();
11287 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11288 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11289 " not tell us which reg is the stack pointer!");
11290 EVT VT = Node->getValueType(0);
11291 SDValue Tmp1 = SDValue(Node, 0);
11292 SDValue Tmp2 = SDValue(Node, 1);
11293 SDValue Tmp3 = Node->getOperand(2);
11294 SDValue Chain = Tmp1.getOperand(0);
11296 // Chain the dynamic stack allocation so that it doesn't modify the stack
11297 // pointer when other instructions are using the stack.
11298 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11301 SDValue Size = Tmp2.getOperand(1);
11302 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11303 Chain = SP.getValue(1);
11304 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11305 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11306 unsigned StackAlign = TFI.getStackAlignment();
11307 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11308 if (Align > StackAlign)
11309 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11310 DAG.getConstant(-(uint64_t)Align, VT));
11311 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11313 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11314 DAG.getIntPtrConstant(0, true), SDValue(),
11317 SDValue Ops[2] = { Tmp1, Tmp2 };
11318 return DAG.getMergeValues(Ops, dl);
11322 SDValue Chain = Op.getOperand(0);
11323 SDValue Size = Op.getOperand(1);
11324 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11325 EVT VT = Op.getNode()->getValueType(0);
11327 bool Is64Bit = Subtarget->is64Bit();
11328 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11331 MachineRegisterInfo &MRI = MF.getRegInfo();
11334 // The 64 bit implementation of segmented stacks needs to clobber both r10
11335 // r11. This makes it impossible to use it along with nested parameters.
11336 const Function *F = MF.getFunction();
11338 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11340 if (I->hasNestAttr())
11341 report_fatal_error("Cannot use segmented stacks with functions that "
11342 "have nested arguments.");
11345 const TargetRegisterClass *AddrRegClass =
11346 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11347 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11348 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11349 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11350 DAG.getRegister(Vreg, SPTy));
11351 SDValue Ops1[2] = { Value, Chain };
11352 return DAG.getMergeValues(Ops1, dl);
11355 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11357 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11358 Flag = Chain.getValue(1);
11359 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11361 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11363 const X86RegisterInfo *RegInfo =
11364 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11365 unsigned SPReg = RegInfo->getStackRegister();
11366 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11367 Chain = SP.getValue(1);
11370 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11371 DAG.getConstant(-(uint64_t)Align, VT));
11372 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11375 SDValue Ops1[2] = { SP, Chain };
11376 return DAG.getMergeValues(Ops1, dl);
11380 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11381 MachineFunction &MF = DAG.getMachineFunction();
11382 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11384 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11387 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11388 // vastart just stores the address of the VarArgsFrameIndex slot into the
11389 // memory location argument.
11390 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11392 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11393 MachinePointerInfo(SV), false, false, 0);
11397 // gp_offset (0 - 6 * 8)
11398 // fp_offset (48 - 48 + 8 * 16)
11399 // overflow_arg_area (point to parameters coming in memory).
11401 SmallVector<SDValue, 8> MemOps;
11402 SDValue FIN = Op.getOperand(1);
11404 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11405 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11407 FIN, MachinePointerInfo(SV), false, false, 0);
11408 MemOps.push_back(Store);
11411 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11412 FIN, DAG.getIntPtrConstant(4));
11413 Store = DAG.getStore(Op.getOperand(0), DL,
11414 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11416 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11417 MemOps.push_back(Store);
11419 // Store ptr to overflow_arg_area
11420 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11421 FIN, DAG.getIntPtrConstant(4));
11422 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11424 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11425 MachinePointerInfo(SV, 8),
11427 MemOps.push_back(Store);
11429 // Store ptr to reg_save_area.
11430 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11431 FIN, DAG.getIntPtrConstant(8));
11432 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11434 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11435 MachinePointerInfo(SV, 16), false, false, 0);
11436 MemOps.push_back(Store);
11437 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11440 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11441 assert(Subtarget->is64Bit() &&
11442 "LowerVAARG only handles 64-bit va_arg!");
11443 assert((Subtarget->isTargetLinux() ||
11444 Subtarget->isTargetDarwin()) &&
11445 "Unhandled target in LowerVAARG");
11446 assert(Op.getNode()->getNumOperands() == 4);
11447 SDValue Chain = Op.getOperand(0);
11448 SDValue SrcPtr = Op.getOperand(1);
11449 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11450 unsigned Align = Op.getConstantOperandVal(3);
11453 EVT ArgVT = Op.getNode()->getValueType(0);
11454 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11455 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11458 // Decide which area this value should be read from.
11459 // TODO: Implement the AMD64 ABI in its entirety. This simple
11460 // selection mechanism works only for the basic types.
11461 if (ArgVT == MVT::f80) {
11462 llvm_unreachable("va_arg for f80 not yet implemented");
11463 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11464 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11465 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11466 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11468 llvm_unreachable("Unhandled argument type in LowerVAARG");
11471 if (ArgMode == 2) {
11472 // Sanity Check: Make sure using fp_offset makes sense.
11473 assert(!getTargetMachine().Options.UseSoftFloat &&
11474 !(DAG.getMachineFunction()
11475 .getFunction()->getAttributes()
11476 .hasAttribute(AttributeSet::FunctionIndex,
11477 Attribute::NoImplicitFloat)) &&
11478 Subtarget->hasSSE1());
11481 // Insert VAARG_64 node into the DAG
11482 // VAARG_64 returns two values: Variable Argument Address, Chain
11483 SmallVector<SDValue, 11> InstOps;
11484 InstOps.push_back(Chain);
11485 InstOps.push_back(SrcPtr);
11486 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11487 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11488 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11489 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11490 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11491 VTs, InstOps, MVT::i64,
11492 MachinePointerInfo(SV),
11494 /*Volatile=*/false,
11496 /*WriteMem=*/true);
11497 Chain = VAARG.getValue(1);
11499 // Load the next argument and return it
11500 return DAG.getLoad(ArgVT, dl,
11503 MachinePointerInfo(),
11504 false, false, false, 0);
11507 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11508 SelectionDAG &DAG) {
11509 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11510 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11511 SDValue Chain = Op.getOperand(0);
11512 SDValue DstPtr = Op.getOperand(1);
11513 SDValue SrcPtr = Op.getOperand(2);
11514 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11515 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11518 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11519 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11521 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11524 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11525 // amount is a constant. Takes immediate version of shift as input.
11526 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11527 SDValue SrcOp, uint64_t ShiftAmt,
11528 SelectionDAG &DAG) {
11529 MVT ElementType = VT.getVectorElementType();
11531 // Check for ShiftAmt >= element width
11532 if (ShiftAmt >= ElementType.getSizeInBits()) {
11533 if (Opc == X86ISD::VSRAI)
11534 ShiftAmt = ElementType.getSizeInBits() - 1;
11536 return DAG.getConstant(0, VT);
11539 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11540 && "Unknown target vector shift-by-constant node");
11542 // Fold this packed vector shift into a build vector if SrcOp is a
11543 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11544 if (VT == SrcOp.getSimpleValueType() &&
11545 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11546 SmallVector<SDValue, 8> Elts;
11547 unsigned NumElts = SrcOp->getNumOperands();
11548 ConstantSDNode *ND;
11551 default: llvm_unreachable(nullptr);
11552 case X86ISD::VSHLI:
11553 for (unsigned i=0; i!=NumElts; ++i) {
11554 SDValue CurrentOp = SrcOp->getOperand(i);
11555 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11556 Elts.push_back(CurrentOp);
11559 ND = cast<ConstantSDNode>(CurrentOp);
11560 const APInt &C = ND->getAPIntValue();
11561 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11564 case X86ISD::VSRLI:
11565 for (unsigned i=0; i!=NumElts; ++i) {
11566 SDValue CurrentOp = SrcOp->getOperand(i);
11567 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11568 Elts.push_back(CurrentOp);
11571 ND = cast<ConstantSDNode>(CurrentOp);
11572 const APInt &C = ND->getAPIntValue();
11573 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11576 case X86ISD::VSRAI:
11577 for (unsigned i=0; i!=NumElts; ++i) {
11578 SDValue CurrentOp = SrcOp->getOperand(i);
11579 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11580 Elts.push_back(CurrentOp);
11583 ND = cast<ConstantSDNode>(CurrentOp);
11584 const APInt &C = ND->getAPIntValue();
11585 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11590 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11593 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11596 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11597 // may or may not be a constant. Takes immediate version of shift as input.
11598 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11599 SDValue SrcOp, SDValue ShAmt,
11600 SelectionDAG &DAG) {
11601 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11603 // Catch shift-by-constant.
11604 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11605 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11606 CShAmt->getZExtValue(), DAG);
11608 // Change opcode to non-immediate version
11610 default: llvm_unreachable("Unknown target vector shift node");
11611 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11612 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11613 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11616 // Need to build a vector containing shift amount
11617 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11620 ShOps[1] = DAG.getConstant(0, MVT::i32);
11621 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11622 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11624 // The return type has to be a 128-bit type with the same element
11625 // type as the input type.
11626 MVT EltVT = VT.getVectorElementType();
11627 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11629 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11630 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11633 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11635 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11637 default: return SDValue(); // Don't custom lower most intrinsics.
11638 // Comparison intrinsics.
11639 case Intrinsic::x86_sse_comieq_ss:
11640 case Intrinsic::x86_sse_comilt_ss:
11641 case Intrinsic::x86_sse_comile_ss:
11642 case Intrinsic::x86_sse_comigt_ss:
11643 case Intrinsic::x86_sse_comige_ss:
11644 case Intrinsic::x86_sse_comineq_ss:
11645 case Intrinsic::x86_sse_ucomieq_ss:
11646 case Intrinsic::x86_sse_ucomilt_ss:
11647 case Intrinsic::x86_sse_ucomile_ss:
11648 case Intrinsic::x86_sse_ucomigt_ss:
11649 case Intrinsic::x86_sse_ucomige_ss:
11650 case Intrinsic::x86_sse_ucomineq_ss:
11651 case Intrinsic::x86_sse2_comieq_sd:
11652 case Intrinsic::x86_sse2_comilt_sd:
11653 case Intrinsic::x86_sse2_comile_sd:
11654 case Intrinsic::x86_sse2_comigt_sd:
11655 case Intrinsic::x86_sse2_comige_sd:
11656 case Intrinsic::x86_sse2_comineq_sd:
11657 case Intrinsic::x86_sse2_ucomieq_sd:
11658 case Intrinsic::x86_sse2_ucomilt_sd:
11659 case Intrinsic::x86_sse2_ucomile_sd:
11660 case Intrinsic::x86_sse2_ucomigt_sd:
11661 case Intrinsic::x86_sse2_ucomige_sd:
11662 case Intrinsic::x86_sse2_ucomineq_sd: {
11666 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11667 case Intrinsic::x86_sse_comieq_ss:
11668 case Intrinsic::x86_sse2_comieq_sd:
11669 Opc = X86ISD::COMI;
11672 case Intrinsic::x86_sse_comilt_ss:
11673 case Intrinsic::x86_sse2_comilt_sd:
11674 Opc = X86ISD::COMI;
11677 case Intrinsic::x86_sse_comile_ss:
11678 case Intrinsic::x86_sse2_comile_sd:
11679 Opc = X86ISD::COMI;
11682 case Intrinsic::x86_sse_comigt_ss:
11683 case Intrinsic::x86_sse2_comigt_sd:
11684 Opc = X86ISD::COMI;
11687 case Intrinsic::x86_sse_comige_ss:
11688 case Intrinsic::x86_sse2_comige_sd:
11689 Opc = X86ISD::COMI;
11692 case Intrinsic::x86_sse_comineq_ss:
11693 case Intrinsic::x86_sse2_comineq_sd:
11694 Opc = X86ISD::COMI;
11697 case Intrinsic::x86_sse_ucomieq_ss:
11698 case Intrinsic::x86_sse2_ucomieq_sd:
11699 Opc = X86ISD::UCOMI;
11702 case Intrinsic::x86_sse_ucomilt_ss:
11703 case Intrinsic::x86_sse2_ucomilt_sd:
11704 Opc = X86ISD::UCOMI;
11707 case Intrinsic::x86_sse_ucomile_ss:
11708 case Intrinsic::x86_sse2_ucomile_sd:
11709 Opc = X86ISD::UCOMI;
11712 case Intrinsic::x86_sse_ucomigt_ss:
11713 case Intrinsic::x86_sse2_ucomigt_sd:
11714 Opc = X86ISD::UCOMI;
11717 case Intrinsic::x86_sse_ucomige_ss:
11718 case Intrinsic::x86_sse2_ucomige_sd:
11719 Opc = X86ISD::UCOMI;
11722 case Intrinsic::x86_sse_ucomineq_ss:
11723 case Intrinsic::x86_sse2_ucomineq_sd:
11724 Opc = X86ISD::UCOMI;
11729 SDValue LHS = Op.getOperand(1);
11730 SDValue RHS = Op.getOperand(2);
11731 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11732 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11733 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11734 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11735 DAG.getConstant(X86CC, MVT::i8), Cond);
11736 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11739 // Arithmetic intrinsics.
11740 case Intrinsic::x86_sse2_pmulu_dq:
11741 case Intrinsic::x86_avx2_pmulu_dq:
11742 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11743 Op.getOperand(1), Op.getOperand(2));
11745 case Intrinsic::x86_sse41_pmuldq:
11746 case Intrinsic::x86_avx2_pmul_dq:
11747 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11748 Op.getOperand(1), Op.getOperand(2));
11750 case Intrinsic::x86_sse2_pmulhu_w:
11751 case Intrinsic::x86_avx2_pmulhu_w:
11752 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11753 Op.getOperand(1), Op.getOperand(2));
11755 case Intrinsic::x86_sse2_pmulh_w:
11756 case Intrinsic::x86_avx2_pmulh_w:
11757 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11758 Op.getOperand(1), Op.getOperand(2));
11760 // SSE2/AVX2 sub with unsigned saturation intrinsics
11761 case Intrinsic::x86_sse2_psubus_b:
11762 case Intrinsic::x86_sse2_psubus_w:
11763 case Intrinsic::x86_avx2_psubus_b:
11764 case Intrinsic::x86_avx2_psubus_w:
11765 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11766 Op.getOperand(1), Op.getOperand(2));
11768 // SSE3/AVX horizontal add/sub intrinsics
11769 case Intrinsic::x86_sse3_hadd_ps:
11770 case Intrinsic::x86_sse3_hadd_pd:
11771 case Intrinsic::x86_avx_hadd_ps_256:
11772 case Intrinsic::x86_avx_hadd_pd_256:
11773 case Intrinsic::x86_sse3_hsub_ps:
11774 case Intrinsic::x86_sse3_hsub_pd:
11775 case Intrinsic::x86_avx_hsub_ps_256:
11776 case Intrinsic::x86_avx_hsub_pd_256:
11777 case Intrinsic::x86_ssse3_phadd_w_128:
11778 case Intrinsic::x86_ssse3_phadd_d_128:
11779 case Intrinsic::x86_avx2_phadd_w:
11780 case Intrinsic::x86_avx2_phadd_d:
11781 case Intrinsic::x86_ssse3_phsub_w_128:
11782 case Intrinsic::x86_ssse3_phsub_d_128:
11783 case Intrinsic::x86_avx2_phsub_w:
11784 case Intrinsic::x86_avx2_phsub_d: {
11787 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11788 case Intrinsic::x86_sse3_hadd_ps:
11789 case Intrinsic::x86_sse3_hadd_pd:
11790 case Intrinsic::x86_avx_hadd_ps_256:
11791 case Intrinsic::x86_avx_hadd_pd_256:
11792 Opcode = X86ISD::FHADD;
11794 case Intrinsic::x86_sse3_hsub_ps:
11795 case Intrinsic::x86_sse3_hsub_pd:
11796 case Intrinsic::x86_avx_hsub_ps_256:
11797 case Intrinsic::x86_avx_hsub_pd_256:
11798 Opcode = X86ISD::FHSUB;
11800 case Intrinsic::x86_ssse3_phadd_w_128:
11801 case Intrinsic::x86_ssse3_phadd_d_128:
11802 case Intrinsic::x86_avx2_phadd_w:
11803 case Intrinsic::x86_avx2_phadd_d:
11804 Opcode = X86ISD::HADD;
11806 case Intrinsic::x86_ssse3_phsub_w_128:
11807 case Intrinsic::x86_ssse3_phsub_d_128:
11808 case Intrinsic::x86_avx2_phsub_w:
11809 case Intrinsic::x86_avx2_phsub_d:
11810 Opcode = X86ISD::HSUB;
11813 return DAG.getNode(Opcode, dl, Op.getValueType(),
11814 Op.getOperand(1), Op.getOperand(2));
11817 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11818 case Intrinsic::x86_sse2_pmaxu_b:
11819 case Intrinsic::x86_sse41_pmaxuw:
11820 case Intrinsic::x86_sse41_pmaxud:
11821 case Intrinsic::x86_avx2_pmaxu_b:
11822 case Intrinsic::x86_avx2_pmaxu_w:
11823 case Intrinsic::x86_avx2_pmaxu_d:
11824 case Intrinsic::x86_sse2_pminu_b:
11825 case Intrinsic::x86_sse41_pminuw:
11826 case Intrinsic::x86_sse41_pminud:
11827 case Intrinsic::x86_avx2_pminu_b:
11828 case Intrinsic::x86_avx2_pminu_w:
11829 case Intrinsic::x86_avx2_pminu_d:
11830 case Intrinsic::x86_sse41_pmaxsb:
11831 case Intrinsic::x86_sse2_pmaxs_w:
11832 case Intrinsic::x86_sse41_pmaxsd:
11833 case Intrinsic::x86_avx2_pmaxs_b:
11834 case Intrinsic::x86_avx2_pmaxs_w:
11835 case Intrinsic::x86_avx2_pmaxs_d:
11836 case Intrinsic::x86_sse41_pminsb:
11837 case Intrinsic::x86_sse2_pmins_w:
11838 case Intrinsic::x86_sse41_pminsd:
11839 case Intrinsic::x86_avx2_pmins_b:
11840 case Intrinsic::x86_avx2_pmins_w:
11841 case Intrinsic::x86_avx2_pmins_d: {
11844 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11845 case Intrinsic::x86_sse2_pmaxu_b:
11846 case Intrinsic::x86_sse41_pmaxuw:
11847 case Intrinsic::x86_sse41_pmaxud:
11848 case Intrinsic::x86_avx2_pmaxu_b:
11849 case Intrinsic::x86_avx2_pmaxu_w:
11850 case Intrinsic::x86_avx2_pmaxu_d:
11851 Opcode = X86ISD::UMAX;
11853 case Intrinsic::x86_sse2_pminu_b:
11854 case Intrinsic::x86_sse41_pminuw:
11855 case Intrinsic::x86_sse41_pminud:
11856 case Intrinsic::x86_avx2_pminu_b:
11857 case Intrinsic::x86_avx2_pminu_w:
11858 case Intrinsic::x86_avx2_pminu_d:
11859 Opcode = X86ISD::UMIN;
11861 case Intrinsic::x86_sse41_pmaxsb:
11862 case Intrinsic::x86_sse2_pmaxs_w:
11863 case Intrinsic::x86_sse41_pmaxsd:
11864 case Intrinsic::x86_avx2_pmaxs_b:
11865 case Intrinsic::x86_avx2_pmaxs_w:
11866 case Intrinsic::x86_avx2_pmaxs_d:
11867 Opcode = X86ISD::SMAX;
11869 case Intrinsic::x86_sse41_pminsb:
11870 case Intrinsic::x86_sse2_pmins_w:
11871 case Intrinsic::x86_sse41_pminsd:
11872 case Intrinsic::x86_avx2_pmins_b:
11873 case Intrinsic::x86_avx2_pmins_w:
11874 case Intrinsic::x86_avx2_pmins_d:
11875 Opcode = X86ISD::SMIN;
11878 return DAG.getNode(Opcode, dl, Op.getValueType(),
11879 Op.getOperand(1), Op.getOperand(2));
11882 // SSE/SSE2/AVX floating point max/min intrinsics.
11883 case Intrinsic::x86_sse_max_ps:
11884 case Intrinsic::x86_sse2_max_pd:
11885 case Intrinsic::x86_avx_max_ps_256:
11886 case Intrinsic::x86_avx_max_pd_256:
11887 case Intrinsic::x86_sse_min_ps:
11888 case Intrinsic::x86_sse2_min_pd:
11889 case Intrinsic::x86_avx_min_ps_256:
11890 case Intrinsic::x86_avx_min_pd_256: {
11893 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11894 case Intrinsic::x86_sse_max_ps:
11895 case Intrinsic::x86_sse2_max_pd:
11896 case Intrinsic::x86_avx_max_ps_256:
11897 case Intrinsic::x86_avx_max_pd_256:
11898 Opcode = X86ISD::FMAX;
11900 case Intrinsic::x86_sse_min_ps:
11901 case Intrinsic::x86_sse2_min_pd:
11902 case Intrinsic::x86_avx_min_ps_256:
11903 case Intrinsic::x86_avx_min_pd_256:
11904 Opcode = X86ISD::FMIN;
11907 return DAG.getNode(Opcode, dl, Op.getValueType(),
11908 Op.getOperand(1), Op.getOperand(2));
11911 // AVX2 variable shift intrinsics
11912 case Intrinsic::x86_avx2_psllv_d:
11913 case Intrinsic::x86_avx2_psllv_q:
11914 case Intrinsic::x86_avx2_psllv_d_256:
11915 case Intrinsic::x86_avx2_psllv_q_256:
11916 case Intrinsic::x86_avx2_psrlv_d:
11917 case Intrinsic::x86_avx2_psrlv_q:
11918 case Intrinsic::x86_avx2_psrlv_d_256:
11919 case Intrinsic::x86_avx2_psrlv_q_256:
11920 case Intrinsic::x86_avx2_psrav_d:
11921 case Intrinsic::x86_avx2_psrav_d_256: {
11924 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11925 case Intrinsic::x86_avx2_psllv_d:
11926 case Intrinsic::x86_avx2_psllv_q:
11927 case Intrinsic::x86_avx2_psllv_d_256:
11928 case Intrinsic::x86_avx2_psllv_q_256:
11931 case Intrinsic::x86_avx2_psrlv_d:
11932 case Intrinsic::x86_avx2_psrlv_q:
11933 case Intrinsic::x86_avx2_psrlv_d_256:
11934 case Intrinsic::x86_avx2_psrlv_q_256:
11937 case Intrinsic::x86_avx2_psrav_d:
11938 case Intrinsic::x86_avx2_psrav_d_256:
11942 return DAG.getNode(Opcode, dl, Op.getValueType(),
11943 Op.getOperand(1), Op.getOperand(2));
11946 case Intrinsic::x86_ssse3_pshuf_b_128:
11947 case Intrinsic::x86_avx2_pshuf_b:
11948 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11949 Op.getOperand(1), Op.getOperand(2));
11951 case Intrinsic::x86_ssse3_psign_b_128:
11952 case Intrinsic::x86_ssse3_psign_w_128:
11953 case Intrinsic::x86_ssse3_psign_d_128:
11954 case Intrinsic::x86_avx2_psign_b:
11955 case Intrinsic::x86_avx2_psign_w:
11956 case Intrinsic::x86_avx2_psign_d:
11957 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11958 Op.getOperand(1), Op.getOperand(2));
11960 case Intrinsic::x86_sse41_insertps:
11961 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11962 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11964 case Intrinsic::x86_avx_vperm2f128_ps_256:
11965 case Intrinsic::x86_avx_vperm2f128_pd_256:
11966 case Intrinsic::x86_avx_vperm2f128_si_256:
11967 case Intrinsic::x86_avx2_vperm2i128:
11968 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11969 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11971 case Intrinsic::x86_avx2_permd:
11972 case Intrinsic::x86_avx2_permps:
11973 // Operands intentionally swapped. Mask is last operand to intrinsic,
11974 // but second operand for node/instruction.
11975 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11976 Op.getOperand(2), Op.getOperand(1));
11978 case Intrinsic::x86_sse_sqrt_ps:
11979 case Intrinsic::x86_sse2_sqrt_pd:
11980 case Intrinsic::x86_avx_sqrt_ps_256:
11981 case Intrinsic::x86_avx_sqrt_pd_256:
11982 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11984 // ptest and testp intrinsics. The intrinsic these come from are designed to
11985 // return an integer value, not just an instruction so lower it to the ptest
11986 // or testp pattern and a setcc for the result.
11987 case Intrinsic::x86_sse41_ptestz:
11988 case Intrinsic::x86_sse41_ptestc:
11989 case Intrinsic::x86_sse41_ptestnzc:
11990 case Intrinsic::x86_avx_ptestz_256:
11991 case Intrinsic::x86_avx_ptestc_256:
11992 case Intrinsic::x86_avx_ptestnzc_256:
11993 case Intrinsic::x86_avx_vtestz_ps:
11994 case Intrinsic::x86_avx_vtestc_ps:
11995 case Intrinsic::x86_avx_vtestnzc_ps:
11996 case Intrinsic::x86_avx_vtestz_pd:
11997 case Intrinsic::x86_avx_vtestc_pd:
11998 case Intrinsic::x86_avx_vtestnzc_pd:
11999 case Intrinsic::x86_avx_vtestz_ps_256:
12000 case Intrinsic::x86_avx_vtestc_ps_256:
12001 case Intrinsic::x86_avx_vtestnzc_ps_256:
12002 case Intrinsic::x86_avx_vtestz_pd_256:
12003 case Intrinsic::x86_avx_vtestc_pd_256:
12004 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12005 bool IsTestPacked = false;
12008 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12009 case Intrinsic::x86_avx_vtestz_ps:
12010 case Intrinsic::x86_avx_vtestz_pd:
12011 case Intrinsic::x86_avx_vtestz_ps_256:
12012 case Intrinsic::x86_avx_vtestz_pd_256:
12013 IsTestPacked = true; // Fallthrough
12014 case Intrinsic::x86_sse41_ptestz:
12015 case Intrinsic::x86_avx_ptestz_256:
12017 X86CC = X86::COND_E;
12019 case Intrinsic::x86_avx_vtestc_ps:
12020 case Intrinsic::x86_avx_vtestc_pd:
12021 case Intrinsic::x86_avx_vtestc_ps_256:
12022 case Intrinsic::x86_avx_vtestc_pd_256:
12023 IsTestPacked = true; // Fallthrough
12024 case Intrinsic::x86_sse41_ptestc:
12025 case Intrinsic::x86_avx_ptestc_256:
12027 X86CC = X86::COND_B;
12029 case Intrinsic::x86_avx_vtestnzc_ps:
12030 case Intrinsic::x86_avx_vtestnzc_pd:
12031 case Intrinsic::x86_avx_vtestnzc_ps_256:
12032 case Intrinsic::x86_avx_vtestnzc_pd_256:
12033 IsTestPacked = true; // Fallthrough
12034 case Intrinsic::x86_sse41_ptestnzc:
12035 case Intrinsic::x86_avx_ptestnzc_256:
12037 X86CC = X86::COND_A;
12041 SDValue LHS = Op.getOperand(1);
12042 SDValue RHS = Op.getOperand(2);
12043 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12044 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12045 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12046 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12047 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12049 case Intrinsic::x86_avx512_kortestz_w:
12050 case Intrinsic::x86_avx512_kortestc_w: {
12051 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12052 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12053 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12054 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12055 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12056 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12057 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12060 // SSE/AVX shift intrinsics
12061 case Intrinsic::x86_sse2_psll_w:
12062 case Intrinsic::x86_sse2_psll_d:
12063 case Intrinsic::x86_sse2_psll_q:
12064 case Intrinsic::x86_avx2_psll_w:
12065 case Intrinsic::x86_avx2_psll_d:
12066 case Intrinsic::x86_avx2_psll_q:
12067 case Intrinsic::x86_sse2_psrl_w:
12068 case Intrinsic::x86_sse2_psrl_d:
12069 case Intrinsic::x86_sse2_psrl_q:
12070 case Intrinsic::x86_avx2_psrl_w:
12071 case Intrinsic::x86_avx2_psrl_d:
12072 case Intrinsic::x86_avx2_psrl_q:
12073 case Intrinsic::x86_sse2_psra_w:
12074 case Intrinsic::x86_sse2_psra_d:
12075 case Intrinsic::x86_avx2_psra_w:
12076 case Intrinsic::x86_avx2_psra_d: {
12079 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12080 case Intrinsic::x86_sse2_psll_w:
12081 case Intrinsic::x86_sse2_psll_d:
12082 case Intrinsic::x86_sse2_psll_q:
12083 case Intrinsic::x86_avx2_psll_w:
12084 case Intrinsic::x86_avx2_psll_d:
12085 case Intrinsic::x86_avx2_psll_q:
12086 Opcode = X86ISD::VSHL;
12088 case Intrinsic::x86_sse2_psrl_w:
12089 case Intrinsic::x86_sse2_psrl_d:
12090 case Intrinsic::x86_sse2_psrl_q:
12091 case Intrinsic::x86_avx2_psrl_w:
12092 case Intrinsic::x86_avx2_psrl_d:
12093 case Intrinsic::x86_avx2_psrl_q:
12094 Opcode = X86ISD::VSRL;
12096 case Intrinsic::x86_sse2_psra_w:
12097 case Intrinsic::x86_sse2_psra_d:
12098 case Intrinsic::x86_avx2_psra_w:
12099 case Intrinsic::x86_avx2_psra_d:
12100 Opcode = X86ISD::VSRA;
12103 return DAG.getNode(Opcode, dl, Op.getValueType(),
12104 Op.getOperand(1), Op.getOperand(2));
12107 // SSE/AVX immediate shift intrinsics
12108 case Intrinsic::x86_sse2_pslli_w:
12109 case Intrinsic::x86_sse2_pslli_d:
12110 case Intrinsic::x86_sse2_pslli_q:
12111 case Intrinsic::x86_avx2_pslli_w:
12112 case Intrinsic::x86_avx2_pslli_d:
12113 case Intrinsic::x86_avx2_pslli_q:
12114 case Intrinsic::x86_sse2_psrli_w:
12115 case Intrinsic::x86_sse2_psrli_d:
12116 case Intrinsic::x86_sse2_psrli_q:
12117 case Intrinsic::x86_avx2_psrli_w:
12118 case Intrinsic::x86_avx2_psrli_d:
12119 case Intrinsic::x86_avx2_psrli_q:
12120 case Intrinsic::x86_sse2_psrai_w:
12121 case Intrinsic::x86_sse2_psrai_d:
12122 case Intrinsic::x86_avx2_psrai_w:
12123 case Intrinsic::x86_avx2_psrai_d: {
12126 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12127 case Intrinsic::x86_sse2_pslli_w:
12128 case Intrinsic::x86_sse2_pslli_d:
12129 case Intrinsic::x86_sse2_pslli_q:
12130 case Intrinsic::x86_avx2_pslli_w:
12131 case Intrinsic::x86_avx2_pslli_d:
12132 case Intrinsic::x86_avx2_pslli_q:
12133 Opcode = X86ISD::VSHLI;
12135 case Intrinsic::x86_sse2_psrli_w:
12136 case Intrinsic::x86_sse2_psrli_d:
12137 case Intrinsic::x86_sse2_psrli_q:
12138 case Intrinsic::x86_avx2_psrli_w:
12139 case Intrinsic::x86_avx2_psrli_d:
12140 case Intrinsic::x86_avx2_psrli_q:
12141 Opcode = X86ISD::VSRLI;
12143 case Intrinsic::x86_sse2_psrai_w:
12144 case Intrinsic::x86_sse2_psrai_d:
12145 case Intrinsic::x86_avx2_psrai_w:
12146 case Intrinsic::x86_avx2_psrai_d:
12147 Opcode = X86ISD::VSRAI;
12150 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12151 Op.getOperand(1), Op.getOperand(2), DAG);
12154 case Intrinsic::x86_sse42_pcmpistria128:
12155 case Intrinsic::x86_sse42_pcmpestria128:
12156 case Intrinsic::x86_sse42_pcmpistric128:
12157 case Intrinsic::x86_sse42_pcmpestric128:
12158 case Intrinsic::x86_sse42_pcmpistrio128:
12159 case Intrinsic::x86_sse42_pcmpestrio128:
12160 case Intrinsic::x86_sse42_pcmpistris128:
12161 case Intrinsic::x86_sse42_pcmpestris128:
12162 case Intrinsic::x86_sse42_pcmpistriz128:
12163 case Intrinsic::x86_sse42_pcmpestriz128: {
12167 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12168 case Intrinsic::x86_sse42_pcmpistria128:
12169 Opcode = X86ISD::PCMPISTRI;
12170 X86CC = X86::COND_A;
12172 case Intrinsic::x86_sse42_pcmpestria128:
12173 Opcode = X86ISD::PCMPESTRI;
12174 X86CC = X86::COND_A;
12176 case Intrinsic::x86_sse42_pcmpistric128:
12177 Opcode = X86ISD::PCMPISTRI;
12178 X86CC = X86::COND_B;
12180 case Intrinsic::x86_sse42_pcmpestric128:
12181 Opcode = X86ISD::PCMPESTRI;
12182 X86CC = X86::COND_B;
12184 case Intrinsic::x86_sse42_pcmpistrio128:
12185 Opcode = X86ISD::PCMPISTRI;
12186 X86CC = X86::COND_O;
12188 case Intrinsic::x86_sse42_pcmpestrio128:
12189 Opcode = X86ISD::PCMPESTRI;
12190 X86CC = X86::COND_O;
12192 case Intrinsic::x86_sse42_pcmpistris128:
12193 Opcode = X86ISD::PCMPISTRI;
12194 X86CC = X86::COND_S;
12196 case Intrinsic::x86_sse42_pcmpestris128:
12197 Opcode = X86ISD::PCMPESTRI;
12198 X86CC = X86::COND_S;
12200 case Intrinsic::x86_sse42_pcmpistriz128:
12201 Opcode = X86ISD::PCMPISTRI;
12202 X86CC = X86::COND_E;
12204 case Intrinsic::x86_sse42_pcmpestriz128:
12205 Opcode = X86ISD::PCMPESTRI;
12206 X86CC = X86::COND_E;
12209 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12210 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12211 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12212 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12213 DAG.getConstant(X86CC, MVT::i8),
12214 SDValue(PCMP.getNode(), 1));
12215 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12218 case Intrinsic::x86_sse42_pcmpistri128:
12219 case Intrinsic::x86_sse42_pcmpestri128: {
12221 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12222 Opcode = X86ISD::PCMPISTRI;
12224 Opcode = X86ISD::PCMPESTRI;
12226 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12227 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12228 return DAG.getNode(Opcode, dl, VTs, NewOps);
12230 case Intrinsic::x86_fma_vfmadd_ps:
12231 case Intrinsic::x86_fma_vfmadd_pd:
12232 case Intrinsic::x86_fma_vfmsub_ps:
12233 case Intrinsic::x86_fma_vfmsub_pd:
12234 case Intrinsic::x86_fma_vfnmadd_ps:
12235 case Intrinsic::x86_fma_vfnmadd_pd:
12236 case Intrinsic::x86_fma_vfnmsub_ps:
12237 case Intrinsic::x86_fma_vfnmsub_pd:
12238 case Intrinsic::x86_fma_vfmaddsub_ps:
12239 case Intrinsic::x86_fma_vfmaddsub_pd:
12240 case Intrinsic::x86_fma_vfmsubadd_ps:
12241 case Intrinsic::x86_fma_vfmsubadd_pd:
12242 case Intrinsic::x86_fma_vfmadd_ps_256:
12243 case Intrinsic::x86_fma_vfmadd_pd_256:
12244 case Intrinsic::x86_fma_vfmsub_ps_256:
12245 case Intrinsic::x86_fma_vfmsub_pd_256:
12246 case Intrinsic::x86_fma_vfnmadd_ps_256:
12247 case Intrinsic::x86_fma_vfnmadd_pd_256:
12248 case Intrinsic::x86_fma_vfnmsub_ps_256:
12249 case Intrinsic::x86_fma_vfnmsub_pd_256:
12250 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12251 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12252 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12253 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12254 case Intrinsic::x86_fma_vfmadd_ps_512:
12255 case Intrinsic::x86_fma_vfmadd_pd_512:
12256 case Intrinsic::x86_fma_vfmsub_ps_512:
12257 case Intrinsic::x86_fma_vfmsub_pd_512:
12258 case Intrinsic::x86_fma_vfnmadd_ps_512:
12259 case Intrinsic::x86_fma_vfnmadd_pd_512:
12260 case Intrinsic::x86_fma_vfnmsub_ps_512:
12261 case Intrinsic::x86_fma_vfnmsub_pd_512:
12262 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12263 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12264 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12265 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12268 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12269 case Intrinsic::x86_fma_vfmadd_ps:
12270 case Intrinsic::x86_fma_vfmadd_pd:
12271 case Intrinsic::x86_fma_vfmadd_ps_256:
12272 case Intrinsic::x86_fma_vfmadd_pd_256:
12273 case Intrinsic::x86_fma_vfmadd_ps_512:
12274 case Intrinsic::x86_fma_vfmadd_pd_512:
12275 Opc = X86ISD::FMADD;
12277 case Intrinsic::x86_fma_vfmsub_ps:
12278 case Intrinsic::x86_fma_vfmsub_pd:
12279 case Intrinsic::x86_fma_vfmsub_ps_256:
12280 case Intrinsic::x86_fma_vfmsub_pd_256:
12281 case Intrinsic::x86_fma_vfmsub_ps_512:
12282 case Intrinsic::x86_fma_vfmsub_pd_512:
12283 Opc = X86ISD::FMSUB;
12285 case Intrinsic::x86_fma_vfnmadd_ps:
12286 case Intrinsic::x86_fma_vfnmadd_pd:
12287 case Intrinsic::x86_fma_vfnmadd_ps_256:
12288 case Intrinsic::x86_fma_vfnmadd_pd_256:
12289 case Intrinsic::x86_fma_vfnmadd_ps_512:
12290 case Intrinsic::x86_fma_vfnmadd_pd_512:
12291 Opc = X86ISD::FNMADD;
12293 case Intrinsic::x86_fma_vfnmsub_ps:
12294 case Intrinsic::x86_fma_vfnmsub_pd:
12295 case Intrinsic::x86_fma_vfnmsub_ps_256:
12296 case Intrinsic::x86_fma_vfnmsub_pd_256:
12297 case Intrinsic::x86_fma_vfnmsub_ps_512:
12298 case Intrinsic::x86_fma_vfnmsub_pd_512:
12299 Opc = X86ISD::FNMSUB;
12301 case Intrinsic::x86_fma_vfmaddsub_ps:
12302 case Intrinsic::x86_fma_vfmaddsub_pd:
12303 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12304 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12305 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12306 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12307 Opc = X86ISD::FMADDSUB;
12309 case Intrinsic::x86_fma_vfmsubadd_ps:
12310 case Intrinsic::x86_fma_vfmsubadd_pd:
12311 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12312 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12313 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12314 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12315 Opc = X86ISD::FMSUBADD;
12319 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12320 Op.getOperand(2), Op.getOperand(3));
12325 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12326 SDValue Base, SDValue Index,
12327 SDValue ScaleOp, SDValue Chain,
12328 const X86Subtarget * Subtarget) {
12330 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12331 assert(C && "Invalid scale type");
12332 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12333 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12334 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12335 Index.getSimpleValueType().getVectorNumElements());
12336 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12337 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12338 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12339 SDValue Segment = DAG.getRegister(0, MVT::i32);
12340 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12341 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12342 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12343 return DAG.getMergeValues(RetOps, dl);
12346 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12347 SDValue Src, SDValue Mask, SDValue Base,
12348 SDValue Index, SDValue ScaleOp, SDValue Chain,
12349 const X86Subtarget * Subtarget) {
12351 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12352 assert(C && "Invalid scale type");
12353 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12354 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12355 Index.getSimpleValueType().getVectorNumElements());
12356 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12357 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12358 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12359 SDValue Segment = DAG.getRegister(0, MVT::i32);
12360 if (Src.getOpcode() == ISD::UNDEF)
12361 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12362 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12363 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12364 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12365 return DAG.getMergeValues(RetOps, dl);
12368 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12369 SDValue Src, SDValue Base, SDValue Index,
12370 SDValue ScaleOp, SDValue Chain) {
12372 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12373 assert(C && "Invalid scale type");
12374 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12375 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12376 SDValue Segment = DAG.getRegister(0, MVT::i32);
12377 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12378 Index.getSimpleValueType().getVectorNumElements());
12379 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12380 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12381 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12382 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12383 return SDValue(Res, 1);
12386 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12387 SDValue Src, SDValue Mask, SDValue Base,
12388 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12390 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12391 assert(C && "Invalid scale type");
12392 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12393 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12394 SDValue Segment = DAG.getRegister(0, MVT::i32);
12395 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12396 Index.getSimpleValueType().getVectorNumElements());
12397 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12398 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12399 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12400 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12401 return SDValue(Res, 1);
12404 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12405 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12406 // also used to custom lower READCYCLECOUNTER nodes.
12407 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12408 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12409 SmallVectorImpl<SDValue> &Results) {
12410 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12411 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12414 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12415 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12416 // and the EAX register is loaded with the low-order 32 bits.
12417 if (Subtarget->is64Bit()) {
12418 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12419 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12422 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12423 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12426 SDValue Chain = HI.getValue(1);
12428 if (Opcode == X86ISD::RDTSCP_DAG) {
12429 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12431 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12432 // the ECX register. Add 'ecx' explicitly to the chain.
12433 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12435 // Explicitly store the content of ECX at the location passed in input
12436 // to the 'rdtscp' intrinsic.
12437 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12438 MachinePointerInfo(), false, false, 0);
12441 if (Subtarget->is64Bit()) {
12442 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12443 // the EAX register is loaded with the low-order 32 bits.
12444 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12445 DAG.getConstant(32, MVT::i8));
12446 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12447 Results.push_back(Chain);
12451 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12452 SDValue Ops[] = { LO, HI };
12453 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12454 Results.push_back(Pair);
12455 Results.push_back(Chain);
12458 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12459 SelectionDAG &DAG) {
12460 SmallVector<SDValue, 2> Results;
12462 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12464 return DAG.getMergeValues(Results, DL);
12467 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12468 SelectionDAG &DAG) {
12470 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12472 default: return SDValue(); // Don't custom lower most intrinsics.
12474 // RDRAND/RDSEED intrinsics.
12475 case Intrinsic::x86_rdrand_16:
12476 case Intrinsic::x86_rdrand_32:
12477 case Intrinsic::x86_rdrand_64:
12478 case Intrinsic::x86_rdseed_16:
12479 case Intrinsic::x86_rdseed_32:
12480 case Intrinsic::x86_rdseed_64: {
12481 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12482 IntNo == Intrinsic::x86_rdseed_32 ||
12483 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12485 // Emit the node with the right value type.
12486 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12487 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12489 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12490 // Otherwise return the value from Rand, which is always 0, casted to i32.
12491 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12492 DAG.getConstant(1, Op->getValueType(1)),
12493 DAG.getConstant(X86::COND_B, MVT::i32),
12494 SDValue(Result.getNode(), 1) };
12495 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12496 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12499 // Return { result, isValid, chain }.
12500 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12501 SDValue(Result.getNode(), 2));
12503 //int_gather(index, base, scale);
12504 case Intrinsic::x86_avx512_gather_qpd_512:
12505 case Intrinsic::x86_avx512_gather_qps_512:
12506 case Intrinsic::x86_avx512_gather_dpd_512:
12507 case Intrinsic::x86_avx512_gather_qpi_512:
12508 case Intrinsic::x86_avx512_gather_qpq_512:
12509 case Intrinsic::x86_avx512_gather_dpq_512:
12510 case Intrinsic::x86_avx512_gather_dps_512:
12511 case Intrinsic::x86_avx512_gather_dpi_512: {
12514 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12515 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12516 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12517 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12518 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12519 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12520 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12521 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12522 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12524 SDValue Chain = Op.getOperand(0);
12525 SDValue Index = Op.getOperand(2);
12526 SDValue Base = Op.getOperand(3);
12527 SDValue Scale = Op.getOperand(4);
12528 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12530 //int_gather_mask(v1, mask, index, base, scale);
12531 case Intrinsic::x86_avx512_gather_qps_mask_512:
12532 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12533 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12534 case Intrinsic::x86_avx512_gather_dps_mask_512:
12535 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12536 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12537 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12538 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12541 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12542 case Intrinsic::x86_avx512_gather_qps_mask_512:
12543 Opc = X86::VGATHERQPSZrm; break;
12544 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12545 Opc = X86::VGATHERQPDZrm; break;
12546 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12547 Opc = X86::VGATHERDPDZrm; break;
12548 case Intrinsic::x86_avx512_gather_dps_mask_512:
12549 Opc = X86::VGATHERDPSZrm; break;
12550 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12551 Opc = X86::VPGATHERQDZrm; break;
12552 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12553 Opc = X86::VPGATHERQQZrm; break;
12554 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12555 Opc = X86::VPGATHERDDZrm; break;
12556 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12557 Opc = X86::VPGATHERDQZrm; break;
12559 SDValue Chain = Op.getOperand(0);
12560 SDValue Src = Op.getOperand(2);
12561 SDValue Mask = Op.getOperand(3);
12562 SDValue Index = Op.getOperand(4);
12563 SDValue Base = Op.getOperand(5);
12564 SDValue Scale = Op.getOperand(6);
12565 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12568 //int_scatter(base, index, v1, scale);
12569 case Intrinsic::x86_avx512_scatter_qpd_512:
12570 case Intrinsic::x86_avx512_scatter_qps_512:
12571 case Intrinsic::x86_avx512_scatter_dpd_512:
12572 case Intrinsic::x86_avx512_scatter_qpi_512:
12573 case Intrinsic::x86_avx512_scatter_qpq_512:
12574 case Intrinsic::x86_avx512_scatter_dpq_512:
12575 case Intrinsic::x86_avx512_scatter_dps_512:
12576 case Intrinsic::x86_avx512_scatter_dpi_512: {
12579 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12580 case Intrinsic::x86_avx512_scatter_qpd_512:
12581 Opc = X86::VSCATTERQPDZmr; break;
12582 case Intrinsic::x86_avx512_scatter_qps_512:
12583 Opc = X86::VSCATTERQPSZmr; break;
12584 case Intrinsic::x86_avx512_scatter_dpd_512:
12585 Opc = X86::VSCATTERDPDZmr; break;
12586 case Intrinsic::x86_avx512_scatter_dps_512:
12587 Opc = X86::VSCATTERDPSZmr; break;
12588 case Intrinsic::x86_avx512_scatter_qpi_512:
12589 Opc = X86::VPSCATTERQDZmr; break;
12590 case Intrinsic::x86_avx512_scatter_qpq_512:
12591 Opc = X86::VPSCATTERQQZmr; break;
12592 case Intrinsic::x86_avx512_scatter_dpq_512:
12593 Opc = X86::VPSCATTERDQZmr; break;
12594 case Intrinsic::x86_avx512_scatter_dpi_512:
12595 Opc = X86::VPSCATTERDDZmr; break;
12597 SDValue Chain = Op.getOperand(0);
12598 SDValue Base = Op.getOperand(2);
12599 SDValue Index = Op.getOperand(3);
12600 SDValue Src = Op.getOperand(4);
12601 SDValue Scale = Op.getOperand(5);
12602 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12604 //int_scatter_mask(base, mask, index, v1, scale);
12605 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12606 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12607 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12608 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12609 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12610 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12611 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12612 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12615 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12616 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12617 Opc = X86::VSCATTERQPDZmr; break;
12618 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12619 Opc = X86::VSCATTERQPSZmr; break;
12620 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12621 Opc = X86::VSCATTERDPDZmr; break;
12622 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12623 Opc = X86::VSCATTERDPSZmr; break;
12624 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12625 Opc = X86::VPSCATTERQDZmr; break;
12626 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12627 Opc = X86::VPSCATTERQQZmr; break;
12628 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12629 Opc = X86::VPSCATTERDQZmr; break;
12630 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12631 Opc = X86::VPSCATTERDDZmr; break;
12633 SDValue Chain = Op.getOperand(0);
12634 SDValue Base = Op.getOperand(2);
12635 SDValue Mask = Op.getOperand(3);
12636 SDValue Index = Op.getOperand(4);
12637 SDValue Src = Op.getOperand(5);
12638 SDValue Scale = Op.getOperand(6);
12639 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12641 // Read Time Stamp Counter (RDTSC).
12642 case Intrinsic::x86_rdtsc:
12643 // Read Time Stamp Counter and Processor ID (RDTSCP).
12644 case Intrinsic::x86_rdtscp: {
12647 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12648 case Intrinsic::x86_rdtsc:
12649 Opc = X86ISD::RDTSC_DAG; break;
12650 case Intrinsic::x86_rdtscp:
12651 Opc = X86ISD::RDTSCP_DAG; break;
12653 SmallVector<SDValue, 2> Results;
12654 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12655 return DAG.getMergeValues(Results, dl);
12657 // XTEST intrinsics.
12658 case Intrinsic::x86_xtest: {
12659 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12660 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12661 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12662 DAG.getConstant(X86::COND_NE, MVT::i8),
12664 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12665 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12666 Ret, SDValue(InTrans.getNode(), 1));
12671 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12672 SelectionDAG &DAG) const {
12673 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12674 MFI->setReturnAddressIsTaken(true);
12676 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12679 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12681 EVT PtrVT = getPointerTy();
12684 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12685 const X86RegisterInfo *RegInfo =
12686 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12687 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12688 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12689 DAG.getNode(ISD::ADD, dl, PtrVT,
12690 FrameAddr, Offset),
12691 MachinePointerInfo(), false, false, false, 0);
12694 // Just load the return address.
12695 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12696 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12697 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12700 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12701 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12702 MFI->setFrameAddressIsTaken(true);
12704 EVT VT = Op.getValueType();
12705 SDLoc dl(Op); // FIXME probably not meaningful
12706 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12707 const X86RegisterInfo *RegInfo =
12708 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12709 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12710 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12711 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12712 "Invalid Frame Register!");
12713 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12715 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12716 MachinePointerInfo(),
12717 false, false, false, 0);
12721 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12722 SelectionDAG &DAG) const {
12723 const X86RegisterInfo *RegInfo =
12724 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12725 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12728 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12729 SDValue Chain = Op.getOperand(0);
12730 SDValue Offset = Op.getOperand(1);
12731 SDValue Handler = Op.getOperand(2);
12734 EVT PtrVT = getPointerTy();
12735 const X86RegisterInfo *RegInfo =
12736 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12737 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12738 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12739 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12740 "Invalid Frame Register!");
12741 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12742 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12744 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12745 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12746 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12747 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12749 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12751 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12752 DAG.getRegister(StoreAddrReg, PtrVT));
12755 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12756 SelectionDAG &DAG) const {
12758 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12759 DAG.getVTList(MVT::i32, MVT::Other),
12760 Op.getOperand(0), Op.getOperand(1));
12763 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12764 SelectionDAG &DAG) const {
12766 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12767 Op.getOperand(0), Op.getOperand(1));
12770 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12771 return Op.getOperand(0);
12774 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12775 SelectionDAG &DAG) const {
12776 SDValue Root = Op.getOperand(0);
12777 SDValue Trmp = Op.getOperand(1); // trampoline
12778 SDValue FPtr = Op.getOperand(2); // nested function
12779 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12782 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12783 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12785 if (Subtarget->is64Bit()) {
12786 SDValue OutChains[6];
12788 // Large code-model.
12789 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12790 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12792 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12793 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12795 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12797 // Load the pointer to the nested function into R11.
12798 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12799 SDValue Addr = Trmp;
12800 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12801 Addr, MachinePointerInfo(TrmpAddr),
12804 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12805 DAG.getConstant(2, MVT::i64));
12806 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12807 MachinePointerInfo(TrmpAddr, 2),
12810 // Load the 'nest' parameter value into R10.
12811 // R10 is specified in X86CallingConv.td
12812 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12813 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12814 DAG.getConstant(10, MVT::i64));
12815 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12816 Addr, MachinePointerInfo(TrmpAddr, 10),
12819 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12820 DAG.getConstant(12, MVT::i64));
12821 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12822 MachinePointerInfo(TrmpAddr, 12),
12825 // Jump to the nested function.
12826 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12827 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12828 DAG.getConstant(20, MVT::i64));
12829 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12830 Addr, MachinePointerInfo(TrmpAddr, 20),
12833 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12834 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12835 DAG.getConstant(22, MVT::i64));
12836 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12837 MachinePointerInfo(TrmpAddr, 22),
12840 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12842 const Function *Func =
12843 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12844 CallingConv::ID CC = Func->getCallingConv();
12849 llvm_unreachable("Unsupported calling convention");
12850 case CallingConv::C:
12851 case CallingConv::X86_StdCall: {
12852 // Pass 'nest' parameter in ECX.
12853 // Must be kept in sync with X86CallingConv.td
12854 NestReg = X86::ECX;
12856 // Check that ECX wasn't needed by an 'inreg' parameter.
12857 FunctionType *FTy = Func->getFunctionType();
12858 const AttributeSet &Attrs = Func->getAttributes();
12860 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12861 unsigned InRegCount = 0;
12864 for (FunctionType::param_iterator I = FTy->param_begin(),
12865 E = FTy->param_end(); I != E; ++I, ++Idx)
12866 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12867 // FIXME: should only count parameters that are lowered to integers.
12868 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12870 if (InRegCount > 2) {
12871 report_fatal_error("Nest register in use - reduce number of inreg"
12877 case CallingConv::X86_FastCall:
12878 case CallingConv::X86_ThisCall:
12879 case CallingConv::Fast:
12880 // Pass 'nest' parameter in EAX.
12881 // Must be kept in sync with X86CallingConv.td
12882 NestReg = X86::EAX;
12886 SDValue OutChains[4];
12887 SDValue Addr, Disp;
12889 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12890 DAG.getConstant(10, MVT::i32));
12891 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12893 // This is storing the opcode for MOV32ri.
12894 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12895 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12896 OutChains[0] = DAG.getStore(Root, dl,
12897 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12898 Trmp, MachinePointerInfo(TrmpAddr),
12901 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12902 DAG.getConstant(1, MVT::i32));
12903 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12904 MachinePointerInfo(TrmpAddr, 1),
12907 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12908 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12909 DAG.getConstant(5, MVT::i32));
12910 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12911 MachinePointerInfo(TrmpAddr, 5),
12914 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12915 DAG.getConstant(6, MVT::i32));
12916 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12917 MachinePointerInfo(TrmpAddr, 6),
12920 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12924 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12925 SelectionDAG &DAG) const {
12927 The rounding mode is in bits 11:10 of FPSR, and has the following
12929 00 Round to nearest
12934 FLT_ROUNDS, on the other hand, expects the following:
12941 To perform the conversion, we do:
12942 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12945 MachineFunction &MF = DAG.getMachineFunction();
12946 const TargetMachine &TM = MF.getTarget();
12947 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12948 unsigned StackAlignment = TFI.getStackAlignment();
12949 MVT VT = Op.getSimpleValueType();
12952 // Save FP Control Word to stack slot
12953 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12954 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12956 MachineMemOperand *MMO =
12957 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12958 MachineMemOperand::MOStore, 2, 2);
12960 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12961 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12962 DAG.getVTList(MVT::Other),
12963 Ops, MVT::i16, MMO);
12965 // Load FP Control Word from stack slot
12966 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12967 MachinePointerInfo(), false, false, false, 0);
12969 // Transform as necessary
12971 DAG.getNode(ISD::SRL, DL, MVT::i16,
12972 DAG.getNode(ISD::AND, DL, MVT::i16,
12973 CWD, DAG.getConstant(0x800, MVT::i16)),
12974 DAG.getConstant(11, MVT::i8));
12976 DAG.getNode(ISD::SRL, DL, MVT::i16,
12977 DAG.getNode(ISD::AND, DL, MVT::i16,
12978 CWD, DAG.getConstant(0x400, MVT::i16)),
12979 DAG.getConstant(9, MVT::i8));
12982 DAG.getNode(ISD::AND, DL, MVT::i16,
12983 DAG.getNode(ISD::ADD, DL, MVT::i16,
12984 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12985 DAG.getConstant(1, MVT::i16)),
12986 DAG.getConstant(3, MVT::i16));
12988 return DAG.getNode((VT.getSizeInBits() < 16 ?
12989 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12992 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12993 MVT VT = Op.getSimpleValueType();
12995 unsigned NumBits = VT.getSizeInBits();
12998 Op = Op.getOperand(0);
12999 if (VT == MVT::i8) {
13000 // Zero extend to i32 since there is not an i8 bsr.
13002 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13005 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13006 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13007 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13009 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13012 DAG.getConstant(NumBits+NumBits-1, OpVT),
13013 DAG.getConstant(X86::COND_E, MVT::i8),
13016 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13018 // Finally xor with NumBits-1.
13019 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13022 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13026 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13027 MVT VT = Op.getSimpleValueType();
13029 unsigned NumBits = VT.getSizeInBits();
13032 Op = Op.getOperand(0);
13033 if (VT == MVT::i8) {
13034 // Zero extend to i32 since there is not an i8 bsr.
13036 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13039 // Issue a bsr (scan bits in reverse).
13040 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13041 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13043 // And xor with NumBits-1.
13044 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13047 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13051 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13052 MVT VT = Op.getSimpleValueType();
13053 unsigned NumBits = VT.getSizeInBits();
13055 Op = Op.getOperand(0);
13057 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13058 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13059 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13061 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13064 DAG.getConstant(NumBits, VT),
13065 DAG.getConstant(X86::COND_E, MVT::i8),
13068 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13071 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13072 // ones, and then concatenate the result back.
13073 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13074 MVT VT = Op.getSimpleValueType();
13076 assert(VT.is256BitVector() && VT.isInteger() &&
13077 "Unsupported value type for operation");
13079 unsigned NumElems = VT.getVectorNumElements();
13082 // Extract the LHS vectors
13083 SDValue LHS = Op.getOperand(0);
13084 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13085 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13087 // Extract the RHS vectors
13088 SDValue RHS = Op.getOperand(1);
13089 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13090 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13092 MVT EltVT = VT.getVectorElementType();
13093 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13095 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13096 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13097 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13100 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13101 assert(Op.getSimpleValueType().is256BitVector() &&
13102 Op.getSimpleValueType().isInteger() &&
13103 "Only handle AVX 256-bit vector integer operation");
13104 return Lower256IntArith(Op, DAG);
13107 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13108 assert(Op.getSimpleValueType().is256BitVector() &&
13109 Op.getSimpleValueType().isInteger() &&
13110 "Only handle AVX 256-bit vector integer operation");
13111 return Lower256IntArith(Op, DAG);
13114 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13115 SelectionDAG &DAG) {
13117 MVT VT = Op.getSimpleValueType();
13119 // Decompose 256-bit ops into smaller 128-bit ops.
13120 if (VT.is256BitVector() && !Subtarget->hasInt256())
13121 return Lower256IntArith(Op, DAG);
13123 SDValue A = Op.getOperand(0);
13124 SDValue B = Op.getOperand(1);
13126 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13127 if (VT == MVT::v4i32) {
13128 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13129 "Should not custom lower when pmuldq is available!");
13131 // Extract the odd parts.
13132 static const int UnpackMask[] = { 1, -1, 3, -1 };
13133 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13134 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13136 // Multiply the even parts.
13137 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13138 // Now multiply odd parts.
13139 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13141 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13142 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13144 // Merge the two vectors back together with a shuffle. This expands into 2
13146 static const int ShufMask[] = { 0, 4, 2, 6 };
13147 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13150 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13151 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13153 // Ahi = psrlqi(a, 32);
13154 // Bhi = psrlqi(b, 32);
13156 // AloBlo = pmuludq(a, b);
13157 // AloBhi = pmuludq(a, Bhi);
13158 // AhiBlo = pmuludq(Ahi, b);
13160 // AloBhi = psllqi(AloBhi, 32);
13161 // AhiBlo = psllqi(AhiBlo, 32);
13162 // return AloBlo + AloBhi + AhiBlo;
13164 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13165 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13167 // Bit cast to 32-bit vectors for MULUDQ
13168 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13169 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13170 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13171 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13172 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13173 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13175 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13176 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13177 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13179 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13180 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13182 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13183 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13186 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13187 SelectionDAG &DAG) {
13188 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13189 EVT VT = Op0.getValueType();
13192 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13193 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13195 // Get the high parts.
13196 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13197 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13198 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13200 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13202 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13203 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13205 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13206 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13207 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13208 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13209 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13211 // Shuffle it back into the right order.
13212 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13213 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13214 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13215 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13217 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13218 // unsigned multiply.
13219 if (IsSigned && !Subtarget->hasSSE41()) {
13221 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13222 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13223 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13224 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13225 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13227 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13228 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13231 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13234 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13235 const X86Subtarget *Subtarget) {
13236 MVT VT = Op.getSimpleValueType();
13238 SDValue R = Op.getOperand(0);
13239 SDValue Amt = Op.getOperand(1);
13241 // Optimize shl/srl/sra with constant shift amount.
13242 if (isSplatVector(Amt.getNode())) {
13243 SDValue SclrAmt = Amt->getOperand(0);
13244 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13245 uint64_t ShiftAmt = C->getZExtValue();
13247 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13248 (Subtarget->hasInt256() &&
13249 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13250 (Subtarget->hasAVX512() &&
13251 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13252 if (Op.getOpcode() == ISD::SHL)
13253 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13255 if (Op.getOpcode() == ISD::SRL)
13256 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13258 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13259 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13263 if (VT == MVT::v16i8) {
13264 if (Op.getOpcode() == ISD::SHL) {
13265 // Make a large shift.
13266 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13267 MVT::v8i16, R, ShiftAmt,
13269 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13270 // Zero out the rightmost bits.
13271 SmallVector<SDValue, 16> V(16,
13272 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13274 return DAG.getNode(ISD::AND, dl, VT, SHL,
13275 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13277 if (Op.getOpcode() == ISD::SRL) {
13278 // Make a large shift.
13279 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13280 MVT::v8i16, R, ShiftAmt,
13282 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13283 // Zero out the leftmost bits.
13284 SmallVector<SDValue, 16> V(16,
13285 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13287 return DAG.getNode(ISD::AND, dl, VT, SRL,
13288 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13290 if (Op.getOpcode() == ISD::SRA) {
13291 if (ShiftAmt == 7) {
13292 // R s>> 7 === R s< 0
13293 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13294 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13297 // R s>> a === ((R u>> a) ^ m) - m
13298 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13299 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13301 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13302 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13303 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13306 llvm_unreachable("Unknown shift opcode.");
13309 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13310 if (Op.getOpcode() == ISD::SHL) {
13311 // Make a large shift.
13312 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13313 MVT::v16i16, R, ShiftAmt,
13315 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13316 // Zero out the rightmost bits.
13317 SmallVector<SDValue, 32> V(32,
13318 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13320 return DAG.getNode(ISD::AND, dl, VT, SHL,
13321 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13323 if (Op.getOpcode() == ISD::SRL) {
13324 // Make a large shift.
13325 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13326 MVT::v16i16, R, ShiftAmt,
13328 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13329 // Zero out the leftmost bits.
13330 SmallVector<SDValue, 32> V(32,
13331 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13333 return DAG.getNode(ISD::AND, dl, VT, SRL,
13334 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13336 if (Op.getOpcode() == ISD::SRA) {
13337 if (ShiftAmt == 7) {
13338 // R s>> 7 === R s< 0
13339 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13340 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13343 // R s>> a === ((R u>> a) ^ m) - m
13344 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13345 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13347 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13348 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13349 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13352 llvm_unreachable("Unknown shift opcode.");
13357 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13358 if (!Subtarget->is64Bit() &&
13359 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13360 Amt.getOpcode() == ISD::BITCAST &&
13361 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13362 Amt = Amt.getOperand(0);
13363 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13364 VT.getVectorNumElements();
13365 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13366 uint64_t ShiftAmt = 0;
13367 for (unsigned i = 0; i != Ratio; ++i) {
13368 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13372 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13374 // Check remaining shift amounts.
13375 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13376 uint64_t ShAmt = 0;
13377 for (unsigned j = 0; j != Ratio; ++j) {
13378 ConstantSDNode *C =
13379 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13383 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13385 if (ShAmt != ShiftAmt)
13388 switch (Op.getOpcode()) {
13390 llvm_unreachable("Unknown shift opcode!");
13392 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13395 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13398 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13406 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13407 const X86Subtarget* Subtarget) {
13408 MVT VT = Op.getSimpleValueType();
13410 SDValue R = Op.getOperand(0);
13411 SDValue Amt = Op.getOperand(1);
13413 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13414 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13415 (Subtarget->hasInt256() &&
13416 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13417 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13418 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13420 EVT EltVT = VT.getVectorElementType();
13422 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13423 unsigned NumElts = VT.getVectorNumElements();
13425 for (i = 0; i != NumElts; ++i) {
13426 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13430 for (j = i; j != NumElts; ++j) {
13431 SDValue Arg = Amt.getOperand(j);
13432 if (Arg.getOpcode() == ISD::UNDEF) continue;
13433 if (Arg != Amt.getOperand(i))
13436 if (i != NumElts && j == NumElts)
13437 BaseShAmt = Amt.getOperand(i);
13439 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13440 Amt = Amt.getOperand(0);
13441 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13442 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13443 SDValue InVec = Amt.getOperand(0);
13444 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13445 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13447 for (; i != NumElts; ++i) {
13448 SDValue Arg = InVec.getOperand(i);
13449 if (Arg.getOpcode() == ISD::UNDEF) continue;
13453 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13454 if (ConstantSDNode *C =
13455 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13456 unsigned SplatIdx =
13457 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13458 if (C->getZExtValue() == SplatIdx)
13459 BaseShAmt = InVec.getOperand(1);
13462 if (!BaseShAmt.getNode())
13463 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13464 DAG.getIntPtrConstant(0));
13468 if (BaseShAmt.getNode()) {
13469 if (EltVT.bitsGT(MVT::i32))
13470 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13471 else if (EltVT.bitsLT(MVT::i32))
13472 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13474 switch (Op.getOpcode()) {
13476 llvm_unreachable("Unknown shift opcode!");
13478 switch (VT.SimpleTy) {
13479 default: return SDValue();
13488 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13491 switch (VT.SimpleTy) {
13492 default: return SDValue();
13499 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13502 switch (VT.SimpleTy) {
13503 default: return SDValue();
13512 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13518 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13519 if (!Subtarget->is64Bit() &&
13520 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13521 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13522 Amt.getOpcode() == ISD::BITCAST &&
13523 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13524 Amt = Amt.getOperand(0);
13525 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13526 VT.getVectorNumElements();
13527 std::vector<SDValue> Vals(Ratio);
13528 for (unsigned i = 0; i != Ratio; ++i)
13529 Vals[i] = Amt.getOperand(i);
13530 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13531 for (unsigned j = 0; j != Ratio; ++j)
13532 if (Vals[j] != Amt.getOperand(i + j))
13535 switch (Op.getOpcode()) {
13537 llvm_unreachable("Unknown shift opcode!");
13539 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13541 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13543 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13550 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13551 SelectionDAG &DAG) {
13553 MVT VT = Op.getSimpleValueType();
13555 SDValue R = Op.getOperand(0);
13556 SDValue Amt = Op.getOperand(1);
13559 if (!Subtarget->hasSSE2())
13562 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13566 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13570 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13572 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13573 if (Subtarget->hasInt256()) {
13574 if (Op.getOpcode() == ISD::SRL &&
13575 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13576 VT == MVT::v4i64 || VT == MVT::v8i32))
13578 if (Op.getOpcode() == ISD::SHL &&
13579 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13580 VT == MVT::v4i64 || VT == MVT::v8i32))
13582 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13586 // If possible, lower this packed shift into a vector multiply instead of
13587 // expanding it into a sequence of scalar shifts.
13588 // Do this only if the vector shift count is a constant build_vector.
13589 if (Op.getOpcode() == ISD::SHL &&
13590 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13591 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13592 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13593 SmallVector<SDValue, 8> Elts;
13594 EVT SVT = VT.getScalarType();
13595 unsigned SVTBits = SVT.getSizeInBits();
13596 const APInt &One = APInt(SVTBits, 1);
13597 unsigned NumElems = VT.getVectorNumElements();
13599 for (unsigned i=0; i !=NumElems; ++i) {
13600 SDValue Op = Amt->getOperand(i);
13601 if (Op->getOpcode() == ISD::UNDEF) {
13602 Elts.push_back(Op);
13606 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13607 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13608 uint64_t ShAmt = C.getZExtValue();
13609 if (ShAmt >= SVTBits) {
13610 Elts.push_back(DAG.getUNDEF(SVT));
13613 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13615 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13616 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13619 // Lower SHL with variable shift amount.
13620 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13621 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13623 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13624 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13625 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13626 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13629 // If possible, lower this shift as a sequence of two shifts by
13630 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13632 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13634 // Could be rewritten as:
13635 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13637 // The advantage is that the two shifts from the example would be
13638 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13639 // the vector shift into four scalar shifts plus four pairs of vector
13641 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13642 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13643 unsigned TargetOpcode = X86ISD::MOVSS;
13644 bool CanBeSimplified;
13645 // The splat value for the first packed shift (the 'X' from the example).
13646 SDValue Amt1 = Amt->getOperand(0);
13647 // The splat value for the second packed shift (the 'Y' from the example).
13648 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13649 Amt->getOperand(2);
13651 // See if it is possible to replace this node with a sequence of
13652 // two shifts followed by a MOVSS/MOVSD
13653 if (VT == MVT::v4i32) {
13654 // Check if it is legal to use a MOVSS.
13655 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13656 Amt2 == Amt->getOperand(3);
13657 if (!CanBeSimplified) {
13658 // Otherwise, check if we can still simplify this node using a MOVSD.
13659 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13660 Amt->getOperand(2) == Amt->getOperand(3);
13661 TargetOpcode = X86ISD::MOVSD;
13662 Amt2 = Amt->getOperand(2);
13665 // Do similar checks for the case where the machine value type
13667 CanBeSimplified = Amt1 == Amt->getOperand(1);
13668 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13669 CanBeSimplified = Amt2 == Amt->getOperand(i);
13671 if (!CanBeSimplified) {
13672 TargetOpcode = X86ISD::MOVSD;
13673 CanBeSimplified = true;
13674 Amt2 = Amt->getOperand(4);
13675 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13676 CanBeSimplified = Amt1 == Amt->getOperand(i);
13677 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13678 CanBeSimplified = Amt2 == Amt->getOperand(j);
13682 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13683 isa<ConstantSDNode>(Amt2)) {
13684 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13685 EVT CastVT = MVT::v4i32;
13687 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13688 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13690 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13691 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13692 if (TargetOpcode == X86ISD::MOVSD)
13693 CastVT = MVT::v2i64;
13694 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13695 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13696 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13698 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13702 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13703 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13706 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13707 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13709 // Turn 'a' into a mask suitable for VSELECT
13710 SDValue VSelM = DAG.getConstant(0x80, VT);
13711 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13712 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13714 SDValue CM1 = DAG.getConstant(0x0f, VT);
13715 SDValue CM2 = DAG.getConstant(0x3f, VT);
13717 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13718 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13719 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13720 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13721 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13724 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13725 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13726 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13728 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13729 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13730 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13731 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13732 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13735 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13736 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13737 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13739 // return VSELECT(r, r+r, a);
13740 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13741 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13745 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13746 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13747 // solution better.
13748 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13749 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13751 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13752 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13753 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13754 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13755 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13758 // Decompose 256-bit shifts into smaller 128-bit shifts.
13759 if (VT.is256BitVector()) {
13760 unsigned NumElems = VT.getVectorNumElements();
13761 MVT EltVT = VT.getVectorElementType();
13762 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13764 // Extract the two vectors
13765 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13766 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13768 // Recreate the shift amount vectors
13769 SDValue Amt1, Amt2;
13770 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13771 // Constant shift amount
13772 SmallVector<SDValue, 4> Amt1Csts;
13773 SmallVector<SDValue, 4> Amt2Csts;
13774 for (unsigned i = 0; i != NumElems/2; ++i)
13775 Amt1Csts.push_back(Amt->getOperand(i));
13776 for (unsigned i = NumElems/2; i != NumElems; ++i)
13777 Amt2Csts.push_back(Amt->getOperand(i));
13779 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13780 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13782 // Variable shift amount
13783 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13784 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13787 // Issue new vector shifts for the smaller types
13788 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13789 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13791 // Concatenate the result back
13792 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13798 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13799 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13800 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13801 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13802 // has only one use.
13803 SDNode *N = Op.getNode();
13804 SDValue LHS = N->getOperand(0);
13805 SDValue RHS = N->getOperand(1);
13806 unsigned BaseOp = 0;
13809 switch (Op.getOpcode()) {
13810 default: llvm_unreachable("Unknown ovf instruction!");
13812 // A subtract of one will be selected as a INC. Note that INC doesn't
13813 // set CF, so we can't do this for UADDO.
13814 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13816 BaseOp = X86ISD::INC;
13817 Cond = X86::COND_O;
13820 BaseOp = X86ISD::ADD;
13821 Cond = X86::COND_O;
13824 BaseOp = X86ISD::ADD;
13825 Cond = X86::COND_B;
13828 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13829 // set CF, so we can't do this for USUBO.
13830 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13832 BaseOp = X86ISD::DEC;
13833 Cond = X86::COND_O;
13836 BaseOp = X86ISD::SUB;
13837 Cond = X86::COND_O;
13840 BaseOp = X86ISD::SUB;
13841 Cond = X86::COND_B;
13844 BaseOp = X86ISD::SMUL;
13845 Cond = X86::COND_O;
13847 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13848 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13850 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13853 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13854 DAG.getConstant(X86::COND_O, MVT::i32),
13855 SDValue(Sum.getNode(), 2));
13857 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13861 // Also sets EFLAGS.
13862 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13863 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13866 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13867 DAG.getConstant(Cond, MVT::i32),
13868 SDValue(Sum.getNode(), 1));
13870 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13873 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13874 SelectionDAG &DAG) const {
13876 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13877 MVT VT = Op.getSimpleValueType();
13879 if (!Subtarget->hasSSE2() || !VT.isVector())
13882 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13883 ExtraVT.getScalarType().getSizeInBits();
13885 switch (VT.SimpleTy) {
13886 default: return SDValue();
13889 if (!Subtarget->hasFp256())
13891 if (!Subtarget->hasInt256()) {
13892 // needs to be split
13893 unsigned NumElems = VT.getVectorNumElements();
13895 // Extract the LHS vectors
13896 SDValue LHS = Op.getOperand(0);
13897 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13898 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13900 MVT EltVT = VT.getVectorElementType();
13901 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13903 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13904 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13905 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13907 SDValue Extra = DAG.getValueType(ExtraVT);
13909 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13910 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13912 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13917 SDValue Op0 = Op.getOperand(0);
13918 SDValue Op00 = Op0.getOperand(0);
13920 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13921 if (Op0.getOpcode() == ISD::BITCAST &&
13922 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13923 // (sext (vzext x)) -> (vsext x)
13924 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13925 if (Tmp1.getNode()) {
13926 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13927 // This folding is only valid when the in-reg type is a vector of i8,
13929 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13930 ExtraEltVT == MVT::i32) {
13931 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13932 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13933 "This optimization is invalid without a VZEXT.");
13934 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13940 // If the above didn't work, then just use Shift-Left + Shift-Right.
13941 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13943 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13949 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13950 SelectionDAG &DAG) {
13952 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13953 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13954 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13955 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13957 // The only fence that needs an instruction is a sequentially-consistent
13958 // cross-thread fence.
13959 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13960 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13961 // no-sse2). There isn't any reason to disable it if the target processor
13963 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13964 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13966 SDValue Chain = Op.getOperand(0);
13967 SDValue Zero = DAG.getConstant(0, MVT::i32);
13969 DAG.getRegister(X86::ESP, MVT::i32), // Base
13970 DAG.getTargetConstant(1, MVT::i8), // Scale
13971 DAG.getRegister(0, MVT::i32), // Index
13972 DAG.getTargetConstant(0, MVT::i32), // Disp
13973 DAG.getRegister(0, MVT::i32), // Segment.
13977 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13978 return SDValue(Res, 0);
13981 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13982 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13985 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13986 SelectionDAG &DAG) {
13987 MVT T = Op.getSimpleValueType();
13991 switch(T.SimpleTy) {
13992 default: llvm_unreachable("Invalid value type!");
13993 case MVT::i8: Reg = X86::AL; size = 1; break;
13994 case MVT::i16: Reg = X86::AX; size = 2; break;
13995 case MVT::i32: Reg = X86::EAX; size = 4; break;
13997 assert(Subtarget->is64Bit() && "Node not type legal!");
13998 Reg = X86::RAX; size = 8;
14001 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14002 Op.getOperand(2), SDValue());
14003 SDValue Ops[] = { cpIn.getValue(0),
14006 DAG.getTargetConstant(size, MVT::i8),
14007 cpIn.getValue(1) };
14008 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14009 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14010 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14013 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14017 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14018 SelectionDAG &DAG) {
14019 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14020 MVT DstVT = Op.getSimpleValueType();
14021 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14022 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14023 assert((DstVT == MVT::i64 ||
14024 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14025 "Unexpected custom BITCAST");
14026 // i64 <=> MMX conversions are Legal.
14027 if (SrcVT==MVT::i64 && DstVT.isVector())
14029 if (DstVT==MVT::i64 && SrcVT.isVector())
14031 // MMX <=> MMX conversions are Legal.
14032 if (SrcVT.isVector() && DstVT.isVector())
14034 // All other conversions need to be expanded.
14038 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14039 SDNode *Node = Op.getNode();
14041 EVT T = Node->getValueType(0);
14042 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14043 DAG.getConstant(0, T), Node->getOperand(2));
14044 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14045 cast<AtomicSDNode>(Node)->getMemoryVT(),
14046 Node->getOperand(0),
14047 Node->getOperand(1), negOp,
14048 cast<AtomicSDNode>(Node)->getMemOperand(),
14049 cast<AtomicSDNode>(Node)->getOrdering(),
14050 cast<AtomicSDNode>(Node)->getSynchScope());
14053 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14054 SDNode *Node = Op.getNode();
14056 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14058 // Convert seq_cst store -> xchg
14059 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14060 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14061 // (The only way to get a 16-byte store is cmpxchg16b)
14062 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14063 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14064 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14065 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14066 cast<AtomicSDNode>(Node)->getMemoryVT(),
14067 Node->getOperand(0),
14068 Node->getOperand(1), Node->getOperand(2),
14069 cast<AtomicSDNode>(Node)->getMemOperand(),
14070 cast<AtomicSDNode>(Node)->getOrdering(),
14071 cast<AtomicSDNode>(Node)->getSynchScope());
14072 return Swap.getValue(1);
14074 // Other atomic stores have a simple pattern.
14078 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14079 EVT VT = Op.getNode()->getSimpleValueType(0);
14081 // Let legalize expand this if it isn't a legal type yet.
14082 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14085 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14088 bool ExtraOp = false;
14089 switch (Op.getOpcode()) {
14090 default: llvm_unreachable("Invalid code");
14091 case ISD::ADDC: Opc = X86ISD::ADD; break;
14092 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14093 case ISD::SUBC: Opc = X86ISD::SUB; break;
14094 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14098 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14100 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14101 Op.getOperand(1), Op.getOperand(2));
14104 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14105 SelectionDAG &DAG) {
14106 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14108 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14109 // which returns the values as { float, float } (in XMM0) or
14110 // { double, double } (which is returned in XMM0, XMM1).
14112 SDValue Arg = Op.getOperand(0);
14113 EVT ArgVT = Arg.getValueType();
14114 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14116 TargetLowering::ArgListTy Args;
14117 TargetLowering::ArgListEntry Entry;
14121 Entry.isSExt = false;
14122 Entry.isZExt = false;
14123 Args.push_back(Entry);
14125 bool isF64 = ArgVT == MVT::f64;
14126 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14127 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14128 // the results are returned via SRet in memory.
14129 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14130 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14131 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14133 Type *RetTy = isF64
14134 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14135 : (Type*)VectorType::get(ArgTy, 4);
14137 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14138 false, false, false, false, 0,
14139 CallingConv::C, /*isTaillCall=*/false,
14140 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14141 Callee, Args, DAG, dl);
14142 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14145 // Returned in xmm0 and xmm1.
14146 return CallResult.first;
14148 // Returned in bits 0:31 and 32:64 xmm0.
14149 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14150 CallResult.first, DAG.getIntPtrConstant(0));
14151 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14152 CallResult.first, DAG.getIntPtrConstant(1));
14153 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14154 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14157 /// LowerOperation - Provide custom lowering hooks for some operations.
14159 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14160 switch (Op.getOpcode()) {
14161 default: llvm_unreachable("Should not custom lower this!");
14162 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14163 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14164 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14165 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14166 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14167 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14168 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14169 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14170 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14171 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14172 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14173 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14174 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14175 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14176 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14177 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14178 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14179 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14180 case ISD::SHL_PARTS:
14181 case ISD::SRA_PARTS:
14182 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14183 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14184 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14185 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14186 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14187 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14188 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14189 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14190 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14191 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14192 case ISD::FABS: return LowerFABS(Op, DAG);
14193 case ISD::FNEG: return LowerFNEG(Op, DAG);
14194 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14195 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14196 case ISD::SETCC: return LowerSETCC(Op, DAG);
14197 case ISD::SELECT: return LowerSELECT(Op, DAG);
14198 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14199 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14200 case ISD::VASTART: return LowerVASTART(Op, DAG);
14201 case ISD::VAARG: return LowerVAARG(Op, DAG);
14202 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14203 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14204 case ISD::INTRINSIC_VOID:
14205 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14206 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14207 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14208 case ISD::FRAME_TO_ARGS_OFFSET:
14209 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14210 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14211 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14212 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14213 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14214 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14215 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14216 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14217 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14218 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14219 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14220 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14221 case ISD::UMUL_LOHI:
14222 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14225 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14231 case ISD::UMULO: return LowerXALUO(Op, DAG);
14232 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14233 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14237 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14238 case ISD::ADD: return LowerADD(Op, DAG);
14239 case ISD::SUB: return LowerSUB(Op, DAG);
14240 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14244 static void ReplaceATOMIC_LOAD(SDNode *Node,
14245 SmallVectorImpl<SDValue> &Results,
14246 SelectionDAG &DAG) {
14248 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14250 // Convert wide load -> cmpxchg8b/cmpxchg16b
14251 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14252 // (The only way to get a 16-byte load is cmpxchg16b)
14253 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14254 SDValue Zero = DAG.getConstant(0, VT);
14255 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14256 Node->getOperand(0),
14257 Node->getOperand(1), Zero, Zero,
14258 cast<AtomicSDNode>(Node)->getMemOperand(),
14259 cast<AtomicSDNode>(Node)->getOrdering(),
14260 cast<AtomicSDNode>(Node)->getOrdering(),
14261 cast<AtomicSDNode>(Node)->getSynchScope());
14262 Results.push_back(Swap.getValue(0));
14263 Results.push_back(Swap.getValue(1));
14267 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14268 SelectionDAG &DAG, unsigned NewOp) {
14270 assert (Node->getValueType(0) == MVT::i64 &&
14271 "Only know how to expand i64 atomics");
14273 SDValue Chain = Node->getOperand(0);
14274 SDValue In1 = Node->getOperand(1);
14275 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14276 Node->getOperand(2), DAG.getIntPtrConstant(0));
14277 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14278 Node->getOperand(2), DAG.getIntPtrConstant(1));
14279 SDValue Ops[] = { Chain, In1, In2L, In2H };
14280 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14282 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14283 cast<MemSDNode>(Node)->getMemOperand());
14284 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14285 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14286 Results.push_back(Result.getValue(2));
14289 /// ReplaceNodeResults - Replace a node with an illegal result type
14290 /// with a new node built out of custom code.
14291 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14292 SmallVectorImpl<SDValue>&Results,
14293 SelectionDAG &DAG) const {
14295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14296 switch (N->getOpcode()) {
14298 llvm_unreachable("Do not know how to custom type legalize this operation!");
14299 case ISD::SIGN_EXTEND_INREG:
14304 // We don't want to expand or promote these.
14306 case ISD::FP_TO_SINT:
14307 case ISD::FP_TO_UINT: {
14308 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14310 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14313 std::pair<SDValue,SDValue> Vals =
14314 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14315 SDValue FIST = Vals.first, StackSlot = Vals.second;
14316 if (FIST.getNode()) {
14317 EVT VT = N->getValueType(0);
14318 // Return a load from the stack slot.
14319 if (StackSlot.getNode())
14320 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14321 MachinePointerInfo(),
14322 false, false, false, 0));
14324 Results.push_back(FIST);
14328 case ISD::UINT_TO_FP: {
14329 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14330 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14331 N->getValueType(0) != MVT::v2f32)
14333 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14335 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14337 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14338 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14339 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14340 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14341 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14342 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14345 case ISD::FP_ROUND: {
14346 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14348 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14349 Results.push_back(V);
14352 case ISD::INTRINSIC_W_CHAIN: {
14353 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14355 default : llvm_unreachable("Do not know how to custom type "
14356 "legalize this intrinsic operation!");
14357 case Intrinsic::x86_rdtsc:
14358 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14360 case Intrinsic::x86_rdtscp:
14361 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14365 case ISD::READCYCLECOUNTER: {
14366 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14369 case ISD::ATOMIC_CMP_SWAP: {
14370 EVT T = N->getValueType(0);
14371 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14372 bool Regs64bit = T == MVT::i128;
14373 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14374 SDValue cpInL, cpInH;
14375 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14376 DAG.getConstant(0, HalfT));
14377 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14378 DAG.getConstant(1, HalfT));
14379 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14380 Regs64bit ? X86::RAX : X86::EAX,
14382 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14383 Regs64bit ? X86::RDX : X86::EDX,
14384 cpInH, cpInL.getValue(1));
14385 SDValue swapInL, swapInH;
14386 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14387 DAG.getConstant(0, HalfT));
14388 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14389 DAG.getConstant(1, HalfT));
14390 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14391 Regs64bit ? X86::RBX : X86::EBX,
14392 swapInL, cpInH.getValue(1));
14393 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14394 Regs64bit ? X86::RCX : X86::ECX,
14395 swapInH, swapInL.getValue(1));
14396 SDValue Ops[] = { swapInH.getValue(0),
14398 swapInH.getValue(1) };
14399 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14400 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14401 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14402 X86ISD::LCMPXCHG8_DAG;
14403 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14404 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14405 Regs64bit ? X86::RAX : X86::EAX,
14406 HalfT, Result.getValue(1));
14407 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14408 Regs64bit ? X86::RDX : X86::EDX,
14409 HalfT, cpOutL.getValue(2));
14410 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14411 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14412 Results.push_back(cpOutH.getValue(1));
14415 case ISD::ATOMIC_LOAD_ADD:
14416 case ISD::ATOMIC_LOAD_AND:
14417 case ISD::ATOMIC_LOAD_NAND:
14418 case ISD::ATOMIC_LOAD_OR:
14419 case ISD::ATOMIC_LOAD_SUB:
14420 case ISD::ATOMIC_LOAD_XOR:
14421 case ISD::ATOMIC_LOAD_MAX:
14422 case ISD::ATOMIC_LOAD_MIN:
14423 case ISD::ATOMIC_LOAD_UMAX:
14424 case ISD::ATOMIC_LOAD_UMIN:
14425 case ISD::ATOMIC_SWAP: {
14427 switch (N->getOpcode()) {
14428 default: llvm_unreachable("Unexpected opcode");
14429 case ISD::ATOMIC_LOAD_ADD:
14430 Opc = X86ISD::ATOMADD64_DAG;
14432 case ISD::ATOMIC_LOAD_AND:
14433 Opc = X86ISD::ATOMAND64_DAG;
14435 case ISD::ATOMIC_LOAD_NAND:
14436 Opc = X86ISD::ATOMNAND64_DAG;
14438 case ISD::ATOMIC_LOAD_OR:
14439 Opc = X86ISD::ATOMOR64_DAG;
14441 case ISD::ATOMIC_LOAD_SUB:
14442 Opc = X86ISD::ATOMSUB64_DAG;
14444 case ISD::ATOMIC_LOAD_XOR:
14445 Opc = X86ISD::ATOMXOR64_DAG;
14447 case ISD::ATOMIC_LOAD_MAX:
14448 Opc = X86ISD::ATOMMAX64_DAG;
14450 case ISD::ATOMIC_LOAD_MIN:
14451 Opc = X86ISD::ATOMMIN64_DAG;
14453 case ISD::ATOMIC_LOAD_UMAX:
14454 Opc = X86ISD::ATOMUMAX64_DAG;
14456 case ISD::ATOMIC_LOAD_UMIN:
14457 Opc = X86ISD::ATOMUMIN64_DAG;
14459 case ISD::ATOMIC_SWAP:
14460 Opc = X86ISD::ATOMSWAP64_DAG;
14463 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14466 case ISD::ATOMIC_LOAD:
14467 ReplaceATOMIC_LOAD(N, Results, DAG);
14471 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14473 default: return nullptr;
14474 case X86ISD::BSF: return "X86ISD::BSF";
14475 case X86ISD::BSR: return "X86ISD::BSR";
14476 case X86ISD::SHLD: return "X86ISD::SHLD";
14477 case X86ISD::SHRD: return "X86ISD::SHRD";
14478 case X86ISD::FAND: return "X86ISD::FAND";
14479 case X86ISD::FANDN: return "X86ISD::FANDN";
14480 case X86ISD::FOR: return "X86ISD::FOR";
14481 case X86ISD::FXOR: return "X86ISD::FXOR";
14482 case X86ISD::FSRL: return "X86ISD::FSRL";
14483 case X86ISD::FILD: return "X86ISD::FILD";
14484 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14485 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14486 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14487 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14488 case X86ISD::FLD: return "X86ISD::FLD";
14489 case X86ISD::FST: return "X86ISD::FST";
14490 case X86ISD::CALL: return "X86ISD::CALL";
14491 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14492 case X86ISD::BT: return "X86ISD::BT";
14493 case X86ISD::CMP: return "X86ISD::CMP";
14494 case X86ISD::COMI: return "X86ISD::COMI";
14495 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14496 case X86ISD::CMPM: return "X86ISD::CMPM";
14497 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14498 case X86ISD::SETCC: return "X86ISD::SETCC";
14499 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14500 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14501 case X86ISD::CMOV: return "X86ISD::CMOV";
14502 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14503 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14504 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14505 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14506 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14507 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14508 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14509 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14510 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14511 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14512 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14513 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14514 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14515 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14516 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14517 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14518 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14519 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14520 case X86ISD::HADD: return "X86ISD::HADD";
14521 case X86ISD::HSUB: return "X86ISD::HSUB";
14522 case X86ISD::FHADD: return "X86ISD::FHADD";
14523 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14524 case X86ISD::UMAX: return "X86ISD::UMAX";
14525 case X86ISD::UMIN: return "X86ISD::UMIN";
14526 case X86ISD::SMAX: return "X86ISD::SMAX";
14527 case X86ISD::SMIN: return "X86ISD::SMIN";
14528 case X86ISD::FMAX: return "X86ISD::FMAX";
14529 case X86ISD::FMIN: return "X86ISD::FMIN";
14530 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14531 case X86ISD::FMINC: return "X86ISD::FMINC";
14532 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14533 case X86ISD::FRCP: return "X86ISD::FRCP";
14534 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14535 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14536 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14537 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14538 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14539 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14540 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14541 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14542 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14543 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14544 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14545 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14546 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14547 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14548 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14549 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14550 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14551 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14552 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14553 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14554 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14555 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14556 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14557 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14558 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14559 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14560 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14561 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14562 case X86ISD::VSHL: return "X86ISD::VSHL";
14563 case X86ISD::VSRL: return "X86ISD::VSRL";
14564 case X86ISD::VSRA: return "X86ISD::VSRA";
14565 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14566 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14567 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14568 case X86ISD::CMPP: return "X86ISD::CMPP";
14569 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14570 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14571 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14572 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14573 case X86ISD::ADD: return "X86ISD::ADD";
14574 case X86ISD::SUB: return "X86ISD::SUB";
14575 case X86ISD::ADC: return "X86ISD::ADC";
14576 case X86ISD::SBB: return "X86ISD::SBB";
14577 case X86ISD::SMUL: return "X86ISD::SMUL";
14578 case X86ISD::UMUL: return "X86ISD::UMUL";
14579 case X86ISD::INC: return "X86ISD::INC";
14580 case X86ISD::DEC: return "X86ISD::DEC";
14581 case X86ISD::OR: return "X86ISD::OR";
14582 case X86ISD::XOR: return "X86ISD::XOR";
14583 case X86ISD::AND: return "X86ISD::AND";
14584 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14585 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14586 case X86ISD::PTEST: return "X86ISD::PTEST";
14587 case X86ISD::TESTP: return "X86ISD::TESTP";
14588 case X86ISD::TESTM: return "X86ISD::TESTM";
14589 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14590 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14591 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14592 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14593 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14594 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14595 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14596 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14597 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14598 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14599 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14600 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14601 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14602 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14603 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14604 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14605 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14606 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14607 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14608 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14609 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14610 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14611 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14612 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14613 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14614 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14615 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14616 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14617 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14618 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14619 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14620 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14621 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14622 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14623 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14624 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14625 case X86ISD::SAHF: return "X86ISD::SAHF";
14626 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14627 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14628 case X86ISD::FMADD: return "X86ISD::FMADD";
14629 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14630 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14631 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14632 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14633 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14634 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14635 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14636 case X86ISD::XTEST: return "X86ISD::XTEST";
14640 // isLegalAddressingMode - Return true if the addressing mode represented
14641 // by AM is legal for this target, for a load/store of the specified type.
14642 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14644 // X86 supports extremely general addressing modes.
14645 CodeModel::Model M = getTargetMachine().getCodeModel();
14646 Reloc::Model R = getTargetMachine().getRelocationModel();
14648 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14649 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14654 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14656 // If a reference to this global requires an extra load, we can't fold it.
14657 if (isGlobalStubReference(GVFlags))
14660 // If BaseGV requires a register for the PIC base, we cannot also have a
14661 // BaseReg specified.
14662 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14665 // If lower 4G is not available, then we must use rip-relative addressing.
14666 if ((M != CodeModel::Small || R != Reloc::Static) &&
14667 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14671 switch (AM.Scale) {
14677 // These scales always work.
14682 // These scales are formed with basereg+scalereg. Only accept if there is
14687 default: // Other stuff never works.
14694 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14695 unsigned Bits = Ty->getScalarSizeInBits();
14697 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14698 // particularly cheaper than those without.
14702 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14703 // variable shifts just as cheap as scalar ones.
14704 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14707 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14708 // fully general vector.
14712 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14713 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14715 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14716 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14717 return NumBits1 > NumBits2;
14720 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14721 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14724 if (!isTypeLegal(EVT::getEVT(Ty1)))
14727 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14729 // Assuming the caller doesn't have a zeroext or signext return parameter,
14730 // truncation all the way down to i1 is valid.
14734 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14735 return isInt<32>(Imm);
14738 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14739 // Can also use sub to handle negated immediates.
14740 return isInt<32>(Imm);
14743 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14744 if (!VT1.isInteger() || !VT2.isInteger())
14746 unsigned NumBits1 = VT1.getSizeInBits();
14747 unsigned NumBits2 = VT2.getSizeInBits();
14748 return NumBits1 > NumBits2;
14751 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14752 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14753 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14756 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14757 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14758 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14761 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14762 EVT VT1 = Val.getValueType();
14763 if (isZExtFree(VT1, VT2))
14766 if (Val.getOpcode() != ISD::LOAD)
14769 if (!VT1.isSimple() || !VT1.isInteger() ||
14770 !VT2.isSimple() || !VT2.isInteger())
14773 switch (VT1.getSimpleVT().SimpleTy) {
14778 // X86 has 8, 16, and 32-bit zero-extending loads.
14786 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14787 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14790 VT = VT.getScalarType();
14792 if (!VT.isSimple())
14795 switch (VT.getSimpleVT().SimpleTy) {
14806 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14807 // i16 instructions are longer (0x66 prefix) and potentially slower.
14808 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14811 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14812 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14813 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14814 /// are assumed to be legal.
14816 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14818 if (!VT.isSimple())
14821 MVT SVT = VT.getSimpleVT();
14823 // Very little shuffling can be done for 64-bit vectors right now.
14824 if (VT.getSizeInBits() == 64)
14827 // FIXME: pshufb, blends, shifts.
14828 return (SVT.getVectorNumElements() == 2 ||
14829 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14830 isMOVLMask(M, SVT) ||
14831 isSHUFPMask(M, SVT) ||
14832 isPSHUFDMask(M, SVT) ||
14833 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14834 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14835 isPALIGNRMask(M, SVT, Subtarget) ||
14836 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14837 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14838 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14839 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14843 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14845 if (!VT.isSimple())
14848 MVT SVT = VT.getSimpleVT();
14849 unsigned NumElts = SVT.getVectorNumElements();
14850 // FIXME: This collection of masks seems suspect.
14853 if (NumElts == 4 && SVT.is128BitVector()) {
14854 return (isMOVLMask(Mask, SVT) ||
14855 isCommutedMOVLMask(Mask, SVT, true) ||
14856 isSHUFPMask(Mask, SVT) ||
14857 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14862 //===----------------------------------------------------------------------===//
14863 // X86 Scheduler Hooks
14864 //===----------------------------------------------------------------------===//
14866 /// Utility function to emit xbegin specifying the start of an RTM region.
14867 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14868 const TargetInstrInfo *TII) {
14869 DebugLoc DL = MI->getDebugLoc();
14871 const BasicBlock *BB = MBB->getBasicBlock();
14872 MachineFunction::iterator I = MBB;
14875 // For the v = xbegin(), we generate
14886 MachineBasicBlock *thisMBB = MBB;
14887 MachineFunction *MF = MBB->getParent();
14888 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14889 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14890 MF->insert(I, mainMBB);
14891 MF->insert(I, sinkMBB);
14893 // Transfer the remainder of BB and its successor edges to sinkMBB.
14894 sinkMBB->splice(sinkMBB->begin(), MBB,
14895 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14896 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14900 // # fallthrough to mainMBB
14901 // # abortion to sinkMBB
14902 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14903 thisMBB->addSuccessor(mainMBB);
14904 thisMBB->addSuccessor(sinkMBB);
14908 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14909 mainMBB->addSuccessor(sinkMBB);
14912 // EAX is live into the sinkMBB
14913 sinkMBB->addLiveIn(X86::EAX);
14914 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14915 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14918 MI->eraseFromParent();
14922 // Get CMPXCHG opcode for the specified data type.
14923 static unsigned getCmpXChgOpcode(EVT VT) {
14924 switch (VT.getSimpleVT().SimpleTy) {
14925 case MVT::i8: return X86::LCMPXCHG8;
14926 case MVT::i16: return X86::LCMPXCHG16;
14927 case MVT::i32: return X86::LCMPXCHG32;
14928 case MVT::i64: return X86::LCMPXCHG64;
14932 llvm_unreachable("Invalid operand size!");
14935 // Get LOAD opcode for the specified data type.
14936 static unsigned getLoadOpcode(EVT VT) {
14937 switch (VT.getSimpleVT().SimpleTy) {
14938 case MVT::i8: return X86::MOV8rm;
14939 case MVT::i16: return X86::MOV16rm;
14940 case MVT::i32: return X86::MOV32rm;
14941 case MVT::i64: return X86::MOV64rm;
14945 llvm_unreachable("Invalid operand size!");
14948 // Get opcode of the non-atomic one from the specified atomic instruction.
14949 static unsigned getNonAtomicOpcode(unsigned Opc) {
14951 case X86::ATOMAND8: return X86::AND8rr;
14952 case X86::ATOMAND16: return X86::AND16rr;
14953 case X86::ATOMAND32: return X86::AND32rr;
14954 case X86::ATOMAND64: return X86::AND64rr;
14955 case X86::ATOMOR8: return X86::OR8rr;
14956 case X86::ATOMOR16: return X86::OR16rr;
14957 case X86::ATOMOR32: return X86::OR32rr;
14958 case X86::ATOMOR64: return X86::OR64rr;
14959 case X86::ATOMXOR8: return X86::XOR8rr;
14960 case X86::ATOMXOR16: return X86::XOR16rr;
14961 case X86::ATOMXOR32: return X86::XOR32rr;
14962 case X86::ATOMXOR64: return X86::XOR64rr;
14964 llvm_unreachable("Unhandled atomic-load-op opcode!");
14967 // Get opcode of the non-atomic one from the specified atomic instruction with
14969 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14970 unsigned &ExtraOpc) {
14972 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14973 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14974 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14975 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14976 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14977 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14978 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14979 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14980 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14981 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14982 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14983 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14984 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14985 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14986 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14987 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14988 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14989 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14990 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14991 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14993 llvm_unreachable("Unhandled atomic-load-op opcode!");
14996 // Get opcode of the non-atomic one from the specified atomic instruction for
14997 // 64-bit data type on 32-bit target.
14998 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15000 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15001 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15002 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15003 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15004 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15005 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15006 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15007 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15008 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15009 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15011 llvm_unreachable("Unhandled atomic-load-op opcode!");
15014 // Get opcode of the non-atomic one from the specified atomic instruction for
15015 // 64-bit data type on 32-bit target with extra opcode.
15016 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15018 unsigned &ExtraOpc) {
15020 case X86::ATOMNAND6432:
15021 ExtraOpc = X86::NOT32r;
15022 HiOpc = X86::AND32rr;
15023 return X86::AND32rr;
15025 llvm_unreachable("Unhandled atomic-load-op opcode!");
15028 // Get pseudo CMOV opcode from the specified data type.
15029 static unsigned getPseudoCMOVOpc(EVT VT) {
15030 switch (VT.getSimpleVT().SimpleTy) {
15031 case MVT::i8: return X86::CMOV_GR8;
15032 case MVT::i16: return X86::CMOV_GR16;
15033 case MVT::i32: return X86::CMOV_GR32;
15037 llvm_unreachable("Unknown CMOV opcode!");
15040 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15041 // They will be translated into a spin-loop or compare-exchange loop from
15044 // dst = atomic-fetch-op MI.addr, MI.val
15050 // t1 = LOAD MI.addr
15052 // t4 = phi(t1, t3 / loop)
15053 // t2 = OP MI.val, t4
15055 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15061 MachineBasicBlock *
15062 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15063 MachineBasicBlock *MBB) const {
15064 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15065 DebugLoc DL = MI->getDebugLoc();
15067 MachineFunction *MF = MBB->getParent();
15068 MachineRegisterInfo &MRI = MF->getRegInfo();
15070 const BasicBlock *BB = MBB->getBasicBlock();
15071 MachineFunction::iterator I = MBB;
15074 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15075 "Unexpected number of operands");
15077 assert(MI->hasOneMemOperand() &&
15078 "Expected atomic-load-op to have one memoperand");
15080 // Memory Reference
15081 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15082 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15084 unsigned DstReg, SrcReg;
15085 unsigned MemOpndSlot;
15087 unsigned CurOp = 0;
15089 DstReg = MI->getOperand(CurOp++).getReg();
15090 MemOpndSlot = CurOp;
15091 CurOp += X86::AddrNumOperands;
15092 SrcReg = MI->getOperand(CurOp++).getReg();
15094 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15095 MVT::SimpleValueType VT = *RC->vt_begin();
15096 unsigned t1 = MRI.createVirtualRegister(RC);
15097 unsigned t2 = MRI.createVirtualRegister(RC);
15098 unsigned t3 = MRI.createVirtualRegister(RC);
15099 unsigned t4 = MRI.createVirtualRegister(RC);
15100 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15102 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15103 unsigned LOADOpc = getLoadOpcode(VT);
15105 // For the atomic load-arith operator, we generate
15108 // t1 = LOAD [MI.addr]
15110 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15111 // t1 = OP MI.val, EAX
15113 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15119 MachineBasicBlock *thisMBB = MBB;
15120 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15121 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15122 MF->insert(I, mainMBB);
15123 MF->insert(I, sinkMBB);
15125 MachineInstrBuilder MIB;
15127 // Transfer the remainder of BB and its successor edges to sinkMBB.
15128 sinkMBB->splice(sinkMBB->begin(), MBB,
15129 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15130 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15133 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15134 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15135 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15137 NewMO.setIsKill(false);
15138 MIB.addOperand(NewMO);
15140 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15141 unsigned flags = (*MMOI)->getFlags();
15142 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15143 MachineMemOperand *MMO =
15144 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15145 (*MMOI)->getSize(),
15146 (*MMOI)->getBaseAlignment(),
15147 (*MMOI)->getTBAAInfo(),
15148 (*MMOI)->getRanges());
15149 MIB.addMemOperand(MMO);
15152 thisMBB->addSuccessor(mainMBB);
15155 MachineBasicBlock *origMainMBB = mainMBB;
15158 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15159 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15161 unsigned Opc = MI->getOpcode();
15164 llvm_unreachable("Unhandled atomic-load-op opcode!");
15165 case X86::ATOMAND8:
15166 case X86::ATOMAND16:
15167 case X86::ATOMAND32:
15168 case X86::ATOMAND64:
15170 case X86::ATOMOR16:
15171 case X86::ATOMOR32:
15172 case X86::ATOMOR64:
15173 case X86::ATOMXOR8:
15174 case X86::ATOMXOR16:
15175 case X86::ATOMXOR32:
15176 case X86::ATOMXOR64: {
15177 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15178 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15182 case X86::ATOMNAND8:
15183 case X86::ATOMNAND16:
15184 case X86::ATOMNAND32:
15185 case X86::ATOMNAND64: {
15186 unsigned Tmp = MRI.createVirtualRegister(RC);
15188 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15189 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15191 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15194 case X86::ATOMMAX8:
15195 case X86::ATOMMAX16:
15196 case X86::ATOMMAX32:
15197 case X86::ATOMMAX64:
15198 case X86::ATOMMIN8:
15199 case X86::ATOMMIN16:
15200 case X86::ATOMMIN32:
15201 case X86::ATOMMIN64:
15202 case X86::ATOMUMAX8:
15203 case X86::ATOMUMAX16:
15204 case X86::ATOMUMAX32:
15205 case X86::ATOMUMAX64:
15206 case X86::ATOMUMIN8:
15207 case X86::ATOMUMIN16:
15208 case X86::ATOMUMIN32:
15209 case X86::ATOMUMIN64: {
15211 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15213 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15217 if (Subtarget->hasCMov()) {
15218 if (VT != MVT::i8) {
15220 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15224 // Promote i8 to i32 to use CMOV32
15225 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15226 const TargetRegisterClass *RC32 =
15227 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15228 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15229 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15230 unsigned Tmp = MRI.createVirtualRegister(RC32);
15232 unsigned Undef = MRI.createVirtualRegister(RC32);
15233 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15235 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15238 .addImm(X86::sub_8bit);
15239 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15242 .addImm(X86::sub_8bit);
15244 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15248 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15249 .addReg(Tmp, 0, X86::sub_8bit);
15252 // Use pseudo select and lower them.
15253 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15254 "Invalid atomic-load-op transformation!");
15255 unsigned SelOpc = getPseudoCMOVOpc(VT);
15256 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15257 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15258 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15259 .addReg(SrcReg).addReg(t4)
15261 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15262 // Replace the original PHI node as mainMBB is changed after CMOV
15264 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15265 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15266 Phi->eraseFromParent();
15272 // Copy PhyReg back from virtual register.
15273 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15276 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15277 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15278 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15280 NewMO.setIsKill(false);
15281 MIB.addOperand(NewMO);
15284 MIB.setMemRefs(MMOBegin, MMOEnd);
15286 // Copy PhyReg back to virtual register.
15287 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15290 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15292 mainMBB->addSuccessor(origMainMBB);
15293 mainMBB->addSuccessor(sinkMBB);
15296 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15297 TII->get(TargetOpcode::COPY), DstReg)
15300 MI->eraseFromParent();
15304 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15305 // instructions. They will be translated into a spin-loop or compare-exchange
15309 // dst = atomic-fetch-op MI.addr, MI.val
15315 // t1L = LOAD [MI.addr + 0]
15316 // t1H = LOAD [MI.addr + 4]
15318 // t4L = phi(t1L, t3L / loop)
15319 // t4H = phi(t1H, t3H / loop)
15320 // t2L = OP MI.val.lo, t4L
15321 // t2H = OP MI.val.hi, t4H
15326 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15334 MachineBasicBlock *
15335 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15336 MachineBasicBlock *MBB) const {
15337 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15338 DebugLoc DL = MI->getDebugLoc();
15340 MachineFunction *MF = MBB->getParent();
15341 MachineRegisterInfo &MRI = MF->getRegInfo();
15343 const BasicBlock *BB = MBB->getBasicBlock();
15344 MachineFunction::iterator I = MBB;
15347 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15348 "Unexpected number of operands");
15350 assert(MI->hasOneMemOperand() &&
15351 "Expected atomic-load-op32 to have one memoperand");
15353 // Memory Reference
15354 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15355 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15357 unsigned DstLoReg, DstHiReg;
15358 unsigned SrcLoReg, SrcHiReg;
15359 unsigned MemOpndSlot;
15361 unsigned CurOp = 0;
15363 DstLoReg = MI->getOperand(CurOp++).getReg();
15364 DstHiReg = MI->getOperand(CurOp++).getReg();
15365 MemOpndSlot = CurOp;
15366 CurOp += X86::AddrNumOperands;
15367 SrcLoReg = MI->getOperand(CurOp++).getReg();
15368 SrcHiReg = MI->getOperand(CurOp++).getReg();
15370 const TargetRegisterClass *RC = &X86::GR32RegClass;
15371 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15373 unsigned t1L = MRI.createVirtualRegister(RC);
15374 unsigned t1H = MRI.createVirtualRegister(RC);
15375 unsigned t2L = MRI.createVirtualRegister(RC);
15376 unsigned t2H = MRI.createVirtualRegister(RC);
15377 unsigned t3L = MRI.createVirtualRegister(RC);
15378 unsigned t3H = MRI.createVirtualRegister(RC);
15379 unsigned t4L = MRI.createVirtualRegister(RC);
15380 unsigned t4H = MRI.createVirtualRegister(RC);
15382 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15383 unsigned LOADOpc = X86::MOV32rm;
15385 // For the atomic load-arith operator, we generate
15388 // t1L = LOAD [MI.addr + 0]
15389 // t1H = LOAD [MI.addr + 4]
15391 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15392 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15393 // t2L = OP MI.val.lo, t4L
15394 // t2H = OP MI.val.hi, t4H
15397 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15405 MachineBasicBlock *thisMBB = MBB;
15406 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15407 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15408 MF->insert(I, mainMBB);
15409 MF->insert(I, sinkMBB);
15411 MachineInstrBuilder MIB;
15413 // Transfer the remainder of BB and its successor edges to sinkMBB.
15414 sinkMBB->splice(sinkMBB->begin(), MBB,
15415 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15416 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15420 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15421 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15422 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15424 NewMO.setIsKill(false);
15425 MIB.addOperand(NewMO);
15427 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15428 unsigned flags = (*MMOI)->getFlags();
15429 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15430 MachineMemOperand *MMO =
15431 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15432 (*MMOI)->getSize(),
15433 (*MMOI)->getBaseAlignment(),
15434 (*MMOI)->getTBAAInfo(),
15435 (*MMOI)->getRanges());
15436 MIB.addMemOperand(MMO);
15438 MachineInstr *LowMI = MIB;
15441 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15442 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15443 if (i == X86::AddrDisp) {
15444 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15446 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15448 NewMO.setIsKill(false);
15449 MIB.addOperand(NewMO);
15452 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15454 thisMBB->addSuccessor(mainMBB);
15457 MachineBasicBlock *origMainMBB = mainMBB;
15460 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15461 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15462 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15463 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15465 unsigned Opc = MI->getOpcode();
15468 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15469 case X86::ATOMAND6432:
15470 case X86::ATOMOR6432:
15471 case X86::ATOMXOR6432:
15472 case X86::ATOMADD6432:
15473 case X86::ATOMSUB6432: {
15475 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15476 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15478 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15482 case X86::ATOMNAND6432: {
15483 unsigned HiOpc, NOTOpc;
15484 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15485 unsigned TmpL = MRI.createVirtualRegister(RC);
15486 unsigned TmpH = MRI.createVirtualRegister(RC);
15487 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15489 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15491 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15492 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15495 case X86::ATOMMAX6432:
15496 case X86::ATOMMIN6432:
15497 case X86::ATOMUMAX6432:
15498 case X86::ATOMUMIN6432: {
15500 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15501 unsigned cL = MRI.createVirtualRegister(RC8);
15502 unsigned cH = MRI.createVirtualRegister(RC8);
15503 unsigned cL32 = MRI.createVirtualRegister(RC);
15504 unsigned cH32 = MRI.createVirtualRegister(RC);
15505 unsigned cc = MRI.createVirtualRegister(RC);
15506 // cl := cmp src_lo, lo
15507 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15508 .addReg(SrcLoReg).addReg(t4L);
15509 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15510 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15511 // ch := cmp src_hi, hi
15512 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15513 .addReg(SrcHiReg).addReg(t4H);
15514 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15515 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15516 // cc := if (src_hi == hi) ? cl : ch;
15517 if (Subtarget->hasCMov()) {
15518 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15519 .addReg(cH32).addReg(cL32);
15521 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15522 .addReg(cH32).addReg(cL32)
15523 .addImm(X86::COND_E);
15524 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15526 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15527 if (Subtarget->hasCMov()) {
15528 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15529 .addReg(SrcLoReg).addReg(t4L);
15530 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15531 .addReg(SrcHiReg).addReg(t4H);
15533 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15534 .addReg(SrcLoReg).addReg(t4L)
15535 .addImm(X86::COND_NE);
15536 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15537 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15538 // 2nd CMOV lowering.
15539 mainMBB->addLiveIn(X86::EFLAGS);
15540 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15541 .addReg(SrcHiReg).addReg(t4H)
15542 .addImm(X86::COND_NE);
15543 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15544 // Replace the original PHI node as mainMBB is changed after CMOV
15546 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15547 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15548 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15549 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15550 PhiL->eraseFromParent();
15551 PhiH->eraseFromParent();
15555 case X86::ATOMSWAP6432: {
15557 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15558 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15559 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15564 // Copy EDX:EAX back from HiReg:LoReg
15565 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15566 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15567 // Copy ECX:EBX from t1H:t1L
15568 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15569 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15571 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15572 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15573 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15575 NewMO.setIsKill(false);
15576 MIB.addOperand(NewMO);
15578 MIB.setMemRefs(MMOBegin, MMOEnd);
15580 // Copy EDX:EAX back to t3H:t3L
15581 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15582 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15584 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15586 mainMBB->addSuccessor(origMainMBB);
15587 mainMBB->addSuccessor(sinkMBB);
15590 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15591 TII->get(TargetOpcode::COPY), DstLoReg)
15593 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15594 TII->get(TargetOpcode::COPY), DstHiReg)
15597 MI->eraseFromParent();
15601 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15602 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15603 // in the .td file.
15604 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15605 const TargetInstrInfo *TII) {
15607 switch (MI->getOpcode()) {
15608 default: llvm_unreachable("illegal opcode!");
15609 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15610 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15611 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15612 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15613 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15614 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15615 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15616 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15619 DebugLoc dl = MI->getDebugLoc();
15620 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15622 unsigned NumArgs = MI->getNumOperands();
15623 for (unsigned i = 1; i < NumArgs; ++i) {
15624 MachineOperand &Op = MI->getOperand(i);
15625 if (!(Op.isReg() && Op.isImplicit()))
15626 MIB.addOperand(Op);
15628 if (MI->hasOneMemOperand())
15629 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15631 BuildMI(*BB, MI, dl,
15632 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15633 .addReg(X86::XMM0);
15635 MI->eraseFromParent();
15639 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15640 // defs in an instruction pattern
15641 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15642 const TargetInstrInfo *TII) {
15644 switch (MI->getOpcode()) {
15645 default: llvm_unreachable("illegal opcode!");
15646 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15647 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15648 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15649 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15650 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15651 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15652 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15653 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15656 DebugLoc dl = MI->getDebugLoc();
15657 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15659 unsigned NumArgs = MI->getNumOperands(); // remove the results
15660 for (unsigned i = 1; i < NumArgs; ++i) {
15661 MachineOperand &Op = MI->getOperand(i);
15662 if (!(Op.isReg() && Op.isImplicit()))
15663 MIB.addOperand(Op);
15665 if (MI->hasOneMemOperand())
15666 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15668 BuildMI(*BB, MI, dl,
15669 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15672 MI->eraseFromParent();
15676 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15677 const TargetInstrInfo *TII,
15678 const X86Subtarget* Subtarget) {
15679 DebugLoc dl = MI->getDebugLoc();
15681 // Address into RAX/EAX, other two args into ECX, EDX.
15682 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15683 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15684 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15685 for (int i = 0; i < X86::AddrNumOperands; ++i)
15686 MIB.addOperand(MI->getOperand(i));
15688 unsigned ValOps = X86::AddrNumOperands;
15689 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15690 .addReg(MI->getOperand(ValOps).getReg());
15691 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15692 .addReg(MI->getOperand(ValOps+1).getReg());
15694 // The instruction doesn't actually take any operands though.
15695 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15697 MI->eraseFromParent(); // The pseudo is gone now.
15701 MachineBasicBlock *
15702 X86TargetLowering::EmitVAARG64WithCustomInserter(
15704 MachineBasicBlock *MBB) const {
15705 // Emit va_arg instruction on X86-64.
15707 // Operands to this pseudo-instruction:
15708 // 0 ) Output : destination address (reg)
15709 // 1-5) Input : va_list address (addr, i64mem)
15710 // 6 ) ArgSize : Size (in bytes) of vararg type
15711 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15712 // 8 ) Align : Alignment of type
15713 // 9 ) EFLAGS (implicit-def)
15715 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15716 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15718 unsigned DestReg = MI->getOperand(0).getReg();
15719 MachineOperand &Base = MI->getOperand(1);
15720 MachineOperand &Scale = MI->getOperand(2);
15721 MachineOperand &Index = MI->getOperand(3);
15722 MachineOperand &Disp = MI->getOperand(4);
15723 MachineOperand &Segment = MI->getOperand(5);
15724 unsigned ArgSize = MI->getOperand(6).getImm();
15725 unsigned ArgMode = MI->getOperand(7).getImm();
15726 unsigned Align = MI->getOperand(8).getImm();
15728 // Memory Reference
15729 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15730 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15731 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15733 // Machine Information
15734 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15735 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15736 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15737 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15738 DebugLoc DL = MI->getDebugLoc();
15740 // struct va_list {
15743 // i64 overflow_area (address)
15744 // i64 reg_save_area (address)
15746 // sizeof(va_list) = 24
15747 // alignment(va_list) = 8
15749 unsigned TotalNumIntRegs = 6;
15750 unsigned TotalNumXMMRegs = 8;
15751 bool UseGPOffset = (ArgMode == 1);
15752 bool UseFPOffset = (ArgMode == 2);
15753 unsigned MaxOffset = TotalNumIntRegs * 8 +
15754 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15756 /* Align ArgSize to a multiple of 8 */
15757 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15758 bool NeedsAlign = (Align > 8);
15760 MachineBasicBlock *thisMBB = MBB;
15761 MachineBasicBlock *overflowMBB;
15762 MachineBasicBlock *offsetMBB;
15763 MachineBasicBlock *endMBB;
15765 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15766 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15767 unsigned OffsetReg = 0;
15769 if (!UseGPOffset && !UseFPOffset) {
15770 // If we only pull from the overflow region, we don't create a branch.
15771 // We don't need to alter control flow.
15772 OffsetDestReg = 0; // unused
15773 OverflowDestReg = DestReg;
15775 offsetMBB = nullptr;
15776 overflowMBB = thisMBB;
15779 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15780 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15781 // If not, pull from overflow_area. (branch to overflowMBB)
15786 // offsetMBB overflowMBB
15791 // Registers for the PHI in endMBB
15792 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15793 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15795 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15796 MachineFunction *MF = MBB->getParent();
15797 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15798 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15799 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15801 MachineFunction::iterator MBBIter = MBB;
15804 // Insert the new basic blocks
15805 MF->insert(MBBIter, offsetMBB);
15806 MF->insert(MBBIter, overflowMBB);
15807 MF->insert(MBBIter, endMBB);
15809 // Transfer the remainder of MBB and its successor edges to endMBB.
15810 endMBB->splice(endMBB->begin(), thisMBB,
15811 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15812 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15814 // Make offsetMBB and overflowMBB successors of thisMBB
15815 thisMBB->addSuccessor(offsetMBB);
15816 thisMBB->addSuccessor(overflowMBB);
15818 // endMBB is a successor of both offsetMBB and overflowMBB
15819 offsetMBB->addSuccessor(endMBB);
15820 overflowMBB->addSuccessor(endMBB);
15822 // Load the offset value into a register
15823 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15824 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15828 .addDisp(Disp, UseFPOffset ? 4 : 0)
15829 .addOperand(Segment)
15830 .setMemRefs(MMOBegin, MMOEnd);
15832 // Check if there is enough room left to pull this argument.
15833 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15835 .addImm(MaxOffset + 8 - ArgSizeA8);
15837 // Branch to "overflowMBB" if offset >= max
15838 // Fall through to "offsetMBB" otherwise
15839 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15840 .addMBB(overflowMBB);
15843 // In offsetMBB, emit code to use the reg_save_area.
15845 assert(OffsetReg != 0);
15847 // Read the reg_save_area address.
15848 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15849 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15854 .addOperand(Segment)
15855 .setMemRefs(MMOBegin, MMOEnd);
15857 // Zero-extend the offset
15858 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15859 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15862 .addImm(X86::sub_32bit);
15864 // Add the offset to the reg_save_area to get the final address.
15865 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15866 .addReg(OffsetReg64)
15867 .addReg(RegSaveReg);
15869 // Compute the offset for the next argument
15870 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15871 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15873 .addImm(UseFPOffset ? 16 : 8);
15875 // Store it back into the va_list.
15876 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15880 .addDisp(Disp, UseFPOffset ? 4 : 0)
15881 .addOperand(Segment)
15882 .addReg(NextOffsetReg)
15883 .setMemRefs(MMOBegin, MMOEnd);
15886 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15891 // Emit code to use overflow area
15894 // Load the overflow_area address into a register.
15895 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15896 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15901 .addOperand(Segment)
15902 .setMemRefs(MMOBegin, MMOEnd);
15904 // If we need to align it, do so. Otherwise, just copy the address
15905 // to OverflowDestReg.
15907 // Align the overflow address
15908 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15909 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15911 // aligned_addr = (addr + (align-1)) & ~(align-1)
15912 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15913 .addReg(OverflowAddrReg)
15916 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15918 .addImm(~(uint64_t)(Align-1));
15920 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15921 .addReg(OverflowAddrReg);
15924 // Compute the next overflow address after this argument.
15925 // (the overflow address should be kept 8-byte aligned)
15926 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15927 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15928 .addReg(OverflowDestReg)
15929 .addImm(ArgSizeA8);
15931 // Store the new overflow address.
15932 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15937 .addOperand(Segment)
15938 .addReg(NextAddrReg)
15939 .setMemRefs(MMOBegin, MMOEnd);
15941 // If we branched, emit the PHI to the front of endMBB.
15943 BuildMI(*endMBB, endMBB->begin(), DL,
15944 TII->get(X86::PHI), DestReg)
15945 .addReg(OffsetDestReg).addMBB(offsetMBB)
15946 .addReg(OverflowDestReg).addMBB(overflowMBB);
15949 // Erase the pseudo instruction
15950 MI->eraseFromParent();
15955 MachineBasicBlock *
15956 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15958 MachineBasicBlock *MBB) const {
15959 // Emit code to save XMM registers to the stack. The ABI says that the
15960 // number of registers to save is given in %al, so it's theoretically
15961 // possible to do an indirect jump trick to avoid saving all of them,
15962 // however this code takes a simpler approach and just executes all
15963 // of the stores if %al is non-zero. It's less code, and it's probably
15964 // easier on the hardware branch predictor, and stores aren't all that
15965 // expensive anyway.
15967 // Create the new basic blocks. One block contains all the XMM stores,
15968 // and one block is the final destination regardless of whether any
15969 // stores were performed.
15970 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15971 MachineFunction *F = MBB->getParent();
15972 MachineFunction::iterator MBBIter = MBB;
15974 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15975 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15976 F->insert(MBBIter, XMMSaveMBB);
15977 F->insert(MBBIter, EndMBB);
15979 // Transfer the remainder of MBB and its successor edges to EndMBB.
15980 EndMBB->splice(EndMBB->begin(), MBB,
15981 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15982 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15984 // The original block will now fall through to the XMM save block.
15985 MBB->addSuccessor(XMMSaveMBB);
15986 // The XMMSaveMBB will fall through to the end block.
15987 XMMSaveMBB->addSuccessor(EndMBB);
15989 // Now add the instructions.
15990 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15991 DebugLoc DL = MI->getDebugLoc();
15993 unsigned CountReg = MI->getOperand(0).getReg();
15994 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15995 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15997 if (!Subtarget->isTargetWin64()) {
15998 // If %al is 0, branch around the XMM save block.
15999 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16000 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16001 MBB->addSuccessor(EndMBB);
16004 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16005 // that was just emitted, but clearly shouldn't be "saved".
16006 assert((MI->getNumOperands() <= 3 ||
16007 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16008 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16009 && "Expected last argument to be EFLAGS");
16010 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16011 // In the XMM save block, save all the XMM argument registers.
16012 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16013 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16014 MachineMemOperand *MMO =
16015 F->getMachineMemOperand(
16016 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16017 MachineMemOperand::MOStore,
16018 /*Size=*/16, /*Align=*/16);
16019 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16020 .addFrameIndex(RegSaveFrameIndex)
16021 .addImm(/*Scale=*/1)
16022 .addReg(/*IndexReg=*/0)
16023 .addImm(/*Disp=*/Offset)
16024 .addReg(/*Segment=*/0)
16025 .addReg(MI->getOperand(i).getReg())
16026 .addMemOperand(MMO);
16029 MI->eraseFromParent(); // The pseudo instruction is gone now.
16034 // The EFLAGS operand of SelectItr might be missing a kill marker
16035 // because there were multiple uses of EFLAGS, and ISel didn't know
16036 // which to mark. Figure out whether SelectItr should have had a
16037 // kill marker, and set it if it should. Returns the correct kill
16039 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16040 MachineBasicBlock* BB,
16041 const TargetRegisterInfo* TRI) {
16042 // Scan forward through BB for a use/def of EFLAGS.
16043 MachineBasicBlock::iterator miI(std::next(SelectItr));
16044 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16045 const MachineInstr& mi = *miI;
16046 if (mi.readsRegister(X86::EFLAGS))
16048 if (mi.definesRegister(X86::EFLAGS))
16049 break; // Should have kill-flag - update below.
16052 // If we hit the end of the block, check whether EFLAGS is live into a
16054 if (miI == BB->end()) {
16055 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16056 sEnd = BB->succ_end();
16057 sItr != sEnd; ++sItr) {
16058 MachineBasicBlock* succ = *sItr;
16059 if (succ->isLiveIn(X86::EFLAGS))
16064 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16065 // out. SelectMI should have a kill flag on EFLAGS.
16066 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16070 MachineBasicBlock *
16071 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16072 MachineBasicBlock *BB) const {
16073 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16074 DebugLoc DL = MI->getDebugLoc();
16076 // To "insert" a SELECT_CC instruction, we actually have to insert the
16077 // diamond control-flow pattern. The incoming instruction knows the
16078 // destination vreg to set, the condition code register to branch on, the
16079 // true/false values to select between, and a branch opcode to use.
16080 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16081 MachineFunction::iterator It = BB;
16087 // cmpTY ccX, r1, r2
16089 // fallthrough --> copy0MBB
16090 MachineBasicBlock *thisMBB = BB;
16091 MachineFunction *F = BB->getParent();
16092 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16093 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16094 F->insert(It, copy0MBB);
16095 F->insert(It, sinkMBB);
16097 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16098 // live into the sink and copy blocks.
16099 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16100 if (!MI->killsRegister(X86::EFLAGS) &&
16101 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16102 copy0MBB->addLiveIn(X86::EFLAGS);
16103 sinkMBB->addLiveIn(X86::EFLAGS);
16106 // Transfer the remainder of BB and its successor edges to sinkMBB.
16107 sinkMBB->splice(sinkMBB->begin(), BB,
16108 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16109 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16111 // Add the true and fallthrough blocks as its successors.
16112 BB->addSuccessor(copy0MBB);
16113 BB->addSuccessor(sinkMBB);
16115 // Create the conditional branch instruction.
16117 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16118 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16121 // %FalseValue = ...
16122 // # fallthrough to sinkMBB
16123 copy0MBB->addSuccessor(sinkMBB);
16126 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16128 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16129 TII->get(X86::PHI), MI->getOperand(0).getReg())
16130 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16131 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16133 MI->eraseFromParent(); // The pseudo instruction is gone now.
16137 MachineBasicBlock *
16138 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16139 bool Is64Bit) const {
16140 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16141 DebugLoc DL = MI->getDebugLoc();
16142 MachineFunction *MF = BB->getParent();
16143 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16145 assert(MF->shouldSplitStack());
16147 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16148 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16151 // ... [Till the alloca]
16152 // If stacklet is not large enough, jump to mallocMBB
16155 // Allocate by subtracting from RSP
16156 // Jump to continueMBB
16159 // Allocate by call to runtime
16163 // [rest of original BB]
16166 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16167 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16168 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16170 MachineRegisterInfo &MRI = MF->getRegInfo();
16171 const TargetRegisterClass *AddrRegClass =
16172 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16174 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16175 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16176 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16177 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16178 sizeVReg = MI->getOperand(1).getReg(),
16179 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16181 MachineFunction::iterator MBBIter = BB;
16184 MF->insert(MBBIter, bumpMBB);
16185 MF->insert(MBBIter, mallocMBB);
16186 MF->insert(MBBIter, continueMBB);
16188 continueMBB->splice(continueMBB->begin(), BB,
16189 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16190 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16192 // Add code to the main basic block to check if the stack limit has been hit,
16193 // and if so, jump to mallocMBB otherwise to bumpMBB.
16194 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16195 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16196 .addReg(tmpSPVReg).addReg(sizeVReg);
16197 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16198 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16199 .addReg(SPLimitVReg);
16200 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16202 // bumpMBB simply decreases the stack pointer, since we know the current
16203 // stacklet has enough space.
16204 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16205 .addReg(SPLimitVReg);
16206 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16207 .addReg(SPLimitVReg);
16208 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16210 // Calls into a routine in libgcc to allocate more space from the heap.
16211 const uint32_t *RegMask =
16212 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16214 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16216 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16217 .addExternalSymbol("__morestack_allocate_stack_space")
16218 .addRegMask(RegMask)
16219 .addReg(X86::RDI, RegState::Implicit)
16220 .addReg(X86::RAX, RegState::ImplicitDefine);
16222 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16224 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16225 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16226 .addExternalSymbol("__morestack_allocate_stack_space")
16227 .addRegMask(RegMask)
16228 .addReg(X86::EAX, RegState::ImplicitDefine);
16232 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16235 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16236 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16237 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16239 // Set up the CFG correctly.
16240 BB->addSuccessor(bumpMBB);
16241 BB->addSuccessor(mallocMBB);
16242 mallocMBB->addSuccessor(continueMBB);
16243 bumpMBB->addSuccessor(continueMBB);
16245 // Take care of the PHI nodes.
16246 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16247 MI->getOperand(0).getReg())
16248 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16249 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16251 // Delete the original pseudo instruction.
16252 MI->eraseFromParent();
16255 return continueMBB;
16258 MachineBasicBlock *
16259 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16260 MachineBasicBlock *BB) const {
16261 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16262 DebugLoc DL = MI->getDebugLoc();
16264 assert(!Subtarget->isTargetMacho());
16266 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16267 // non-trivial part is impdef of ESP.
16269 if (Subtarget->isTargetWin64()) {
16270 if (Subtarget->isTargetCygMing()) {
16271 // ___chkstk(Mingw64):
16272 // Clobbers R10, R11, RAX and EFLAGS.
16274 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16275 .addExternalSymbol("___chkstk")
16276 .addReg(X86::RAX, RegState::Implicit)
16277 .addReg(X86::RSP, RegState::Implicit)
16278 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16279 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16280 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16282 // __chkstk(MSVCRT): does not update stack pointer.
16283 // Clobbers R10, R11 and EFLAGS.
16284 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16285 .addExternalSymbol("__chkstk")
16286 .addReg(X86::RAX, RegState::Implicit)
16287 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16288 // RAX has the offset to be subtracted from RSP.
16289 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16294 const char *StackProbeSymbol =
16295 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16297 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16298 .addExternalSymbol(StackProbeSymbol)
16299 .addReg(X86::EAX, RegState::Implicit)
16300 .addReg(X86::ESP, RegState::Implicit)
16301 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16302 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16303 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16306 MI->eraseFromParent(); // The pseudo instruction is gone now.
16310 MachineBasicBlock *
16311 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16312 MachineBasicBlock *BB) const {
16313 // This is pretty easy. We're taking the value that we received from
16314 // our load from the relocation, sticking it in either RDI (x86-64)
16315 // or EAX and doing an indirect call. The return value will then
16316 // be in the normal return register.
16317 const X86InstrInfo *TII
16318 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16319 DebugLoc DL = MI->getDebugLoc();
16320 MachineFunction *F = BB->getParent();
16322 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16323 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16325 // Get a register mask for the lowered call.
16326 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16327 // proper register mask.
16328 const uint32_t *RegMask =
16329 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16330 if (Subtarget->is64Bit()) {
16331 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16332 TII->get(X86::MOV64rm), X86::RDI)
16334 .addImm(0).addReg(0)
16335 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16336 MI->getOperand(3).getTargetFlags())
16338 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16339 addDirectMem(MIB, X86::RDI);
16340 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16341 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16342 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16343 TII->get(X86::MOV32rm), X86::EAX)
16345 .addImm(0).addReg(0)
16346 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16347 MI->getOperand(3).getTargetFlags())
16349 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16350 addDirectMem(MIB, X86::EAX);
16351 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16353 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16354 TII->get(X86::MOV32rm), X86::EAX)
16355 .addReg(TII->getGlobalBaseReg(F))
16356 .addImm(0).addReg(0)
16357 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16358 MI->getOperand(3).getTargetFlags())
16360 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16361 addDirectMem(MIB, X86::EAX);
16362 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16365 MI->eraseFromParent(); // The pseudo instruction is gone now.
16369 MachineBasicBlock *
16370 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16371 MachineBasicBlock *MBB) const {
16372 DebugLoc DL = MI->getDebugLoc();
16373 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16375 MachineFunction *MF = MBB->getParent();
16376 MachineRegisterInfo &MRI = MF->getRegInfo();
16378 const BasicBlock *BB = MBB->getBasicBlock();
16379 MachineFunction::iterator I = MBB;
16382 // Memory Reference
16383 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16384 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16387 unsigned MemOpndSlot = 0;
16389 unsigned CurOp = 0;
16391 DstReg = MI->getOperand(CurOp++).getReg();
16392 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16393 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16394 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16395 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16397 MemOpndSlot = CurOp;
16399 MVT PVT = getPointerTy();
16400 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16401 "Invalid Pointer Size!");
16403 // For v = setjmp(buf), we generate
16406 // buf[LabelOffset] = restoreMBB
16407 // SjLjSetup restoreMBB
16413 // v = phi(main, restore)
16418 MachineBasicBlock *thisMBB = MBB;
16419 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16420 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16421 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16422 MF->insert(I, mainMBB);
16423 MF->insert(I, sinkMBB);
16424 MF->push_back(restoreMBB);
16426 MachineInstrBuilder MIB;
16428 // Transfer the remainder of BB and its successor edges to sinkMBB.
16429 sinkMBB->splice(sinkMBB->begin(), MBB,
16430 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16431 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16434 unsigned PtrStoreOpc = 0;
16435 unsigned LabelReg = 0;
16436 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16437 Reloc::Model RM = getTargetMachine().getRelocationModel();
16438 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16439 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16441 // Prepare IP either in reg or imm.
16442 if (!UseImmLabel) {
16443 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16444 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16445 LabelReg = MRI.createVirtualRegister(PtrRC);
16446 if (Subtarget->is64Bit()) {
16447 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16451 .addMBB(restoreMBB)
16454 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16455 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16456 .addReg(XII->getGlobalBaseReg(MF))
16459 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16463 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16465 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16466 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16467 if (i == X86::AddrDisp)
16468 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16470 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16473 MIB.addReg(LabelReg);
16475 MIB.addMBB(restoreMBB);
16476 MIB.setMemRefs(MMOBegin, MMOEnd);
16478 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16479 .addMBB(restoreMBB);
16481 const X86RegisterInfo *RegInfo =
16482 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16483 MIB.addRegMask(RegInfo->getNoPreservedMask());
16484 thisMBB->addSuccessor(mainMBB);
16485 thisMBB->addSuccessor(restoreMBB);
16489 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16490 mainMBB->addSuccessor(sinkMBB);
16493 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16494 TII->get(X86::PHI), DstReg)
16495 .addReg(mainDstReg).addMBB(mainMBB)
16496 .addReg(restoreDstReg).addMBB(restoreMBB);
16499 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16500 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16501 restoreMBB->addSuccessor(sinkMBB);
16503 MI->eraseFromParent();
16507 MachineBasicBlock *
16508 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16509 MachineBasicBlock *MBB) const {
16510 DebugLoc DL = MI->getDebugLoc();
16511 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16513 MachineFunction *MF = MBB->getParent();
16514 MachineRegisterInfo &MRI = MF->getRegInfo();
16516 // Memory Reference
16517 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16518 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16520 MVT PVT = getPointerTy();
16521 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16522 "Invalid Pointer Size!");
16524 const TargetRegisterClass *RC =
16525 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16526 unsigned Tmp = MRI.createVirtualRegister(RC);
16527 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16528 const X86RegisterInfo *RegInfo =
16529 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16530 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16531 unsigned SP = RegInfo->getStackRegister();
16533 MachineInstrBuilder MIB;
16535 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16536 const int64_t SPOffset = 2 * PVT.getStoreSize();
16538 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16539 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16542 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16543 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16544 MIB.addOperand(MI->getOperand(i));
16545 MIB.setMemRefs(MMOBegin, MMOEnd);
16547 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16548 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16549 if (i == X86::AddrDisp)
16550 MIB.addDisp(MI->getOperand(i), LabelOffset);
16552 MIB.addOperand(MI->getOperand(i));
16554 MIB.setMemRefs(MMOBegin, MMOEnd);
16556 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16557 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16558 if (i == X86::AddrDisp)
16559 MIB.addDisp(MI->getOperand(i), SPOffset);
16561 MIB.addOperand(MI->getOperand(i));
16563 MIB.setMemRefs(MMOBegin, MMOEnd);
16565 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16567 MI->eraseFromParent();
16571 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16572 // accumulator loops. Writing back to the accumulator allows the coalescer
16573 // to remove extra copies in the loop.
16574 MachineBasicBlock *
16575 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16576 MachineBasicBlock *MBB) const {
16577 MachineOperand &AddendOp = MI->getOperand(3);
16579 // Bail out early if the addend isn't a register - we can't switch these.
16580 if (!AddendOp.isReg())
16583 MachineFunction &MF = *MBB->getParent();
16584 MachineRegisterInfo &MRI = MF.getRegInfo();
16586 // Check whether the addend is defined by a PHI:
16587 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16588 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16589 if (!AddendDef.isPHI())
16592 // Look for the following pattern:
16594 // %addend = phi [%entry, 0], [%loop, %result]
16596 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16600 // %addend = phi [%entry, 0], [%loop, %result]
16602 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16604 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16605 assert(AddendDef.getOperand(i).isReg());
16606 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16607 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16608 if (&PHISrcInst == MI) {
16609 // Found a matching instruction.
16610 unsigned NewFMAOpc = 0;
16611 switch (MI->getOpcode()) {
16612 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16613 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16614 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16615 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16616 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16617 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16618 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16619 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16620 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16621 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16622 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16623 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16624 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16625 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16626 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16627 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16628 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16629 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16630 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16631 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16632 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16633 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16634 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16635 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16636 default: llvm_unreachable("Unrecognized FMA variant.");
16639 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16640 MachineInstrBuilder MIB =
16641 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16642 .addOperand(MI->getOperand(0))
16643 .addOperand(MI->getOperand(3))
16644 .addOperand(MI->getOperand(2))
16645 .addOperand(MI->getOperand(1));
16646 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16647 MI->eraseFromParent();
16654 MachineBasicBlock *
16655 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16656 MachineBasicBlock *BB) const {
16657 switch (MI->getOpcode()) {
16658 default: llvm_unreachable("Unexpected instr type to insert");
16659 case X86::TAILJMPd64:
16660 case X86::TAILJMPr64:
16661 case X86::TAILJMPm64:
16662 llvm_unreachable("TAILJMP64 would not be touched here.");
16663 case X86::TCRETURNdi64:
16664 case X86::TCRETURNri64:
16665 case X86::TCRETURNmi64:
16667 case X86::WIN_ALLOCA:
16668 return EmitLoweredWinAlloca(MI, BB);
16669 case X86::SEG_ALLOCA_32:
16670 return EmitLoweredSegAlloca(MI, BB, false);
16671 case X86::SEG_ALLOCA_64:
16672 return EmitLoweredSegAlloca(MI, BB, true);
16673 case X86::TLSCall_32:
16674 case X86::TLSCall_64:
16675 return EmitLoweredTLSCall(MI, BB);
16676 case X86::CMOV_GR8:
16677 case X86::CMOV_FR32:
16678 case X86::CMOV_FR64:
16679 case X86::CMOV_V4F32:
16680 case X86::CMOV_V2F64:
16681 case X86::CMOV_V2I64:
16682 case X86::CMOV_V8F32:
16683 case X86::CMOV_V4F64:
16684 case X86::CMOV_V4I64:
16685 case X86::CMOV_V16F32:
16686 case X86::CMOV_V8F64:
16687 case X86::CMOV_V8I64:
16688 case X86::CMOV_GR16:
16689 case X86::CMOV_GR32:
16690 case X86::CMOV_RFP32:
16691 case X86::CMOV_RFP64:
16692 case X86::CMOV_RFP80:
16693 return EmitLoweredSelect(MI, BB);
16695 case X86::FP32_TO_INT16_IN_MEM:
16696 case X86::FP32_TO_INT32_IN_MEM:
16697 case X86::FP32_TO_INT64_IN_MEM:
16698 case X86::FP64_TO_INT16_IN_MEM:
16699 case X86::FP64_TO_INT32_IN_MEM:
16700 case X86::FP64_TO_INT64_IN_MEM:
16701 case X86::FP80_TO_INT16_IN_MEM:
16702 case X86::FP80_TO_INT32_IN_MEM:
16703 case X86::FP80_TO_INT64_IN_MEM: {
16704 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16705 DebugLoc DL = MI->getDebugLoc();
16707 // Change the floating point control register to use "round towards zero"
16708 // mode when truncating to an integer value.
16709 MachineFunction *F = BB->getParent();
16710 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16711 addFrameReference(BuildMI(*BB, MI, DL,
16712 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16714 // Load the old value of the high byte of the control word...
16716 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16717 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16720 // Set the high part to be round to zero...
16721 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16724 // Reload the modified control word now...
16725 addFrameReference(BuildMI(*BB, MI, DL,
16726 TII->get(X86::FLDCW16m)), CWFrameIdx);
16728 // Restore the memory image of control word to original value
16729 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16732 // Get the X86 opcode to use.
16734 switch (MI->getOpcode()) {
16735 default: llvm_unreachable("illegal opcode!");
16736 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16737 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16738 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16739 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16740 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16741 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16742 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16743 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16744 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16748 MachineOperand &Op = MI->getOperand(0);
16750 AM.BaseType = X86AddressMode::RegBase;
16751 AM.Base.Reg = Op.getReg();
16753 AM.BaseType = X86AddressMode::FrameIndexBase;
16754 AM.Base.FrameIndex = Op.getIndex();
16756 Op = MI->getOperand(1);
16758 AM.Scale = Op.getImm();
16759 Op = MI->getOperand(2);
16761 AM.IndexReg = Op.getImm();
16762 Op = MI->getOperand(3);
16763 if (Op.isGlobal()) {
16764 AM.GV = Op.getGlobal();
16766 AM.Disp = Op.getImm();
16768 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16769 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16771 // Reload the original control word now.
16772 addFrameReference(BuildMI(*BB, MI, DL,
16773 TII->get(X86::FLDCW16m)), CWFrameIdx);
16775 MI->eraseFromParent(); // The pseudo instruction is gone now.
16778 // String/text processing lowering.
16779 case X86::PCMPISTRM128REG:
16780 case X86::VPCMPISTRM128REG:
16781 case X86::PCMPISTRM128MEM:
16782 case X86::VPCMPISTRM128MEM:
16783 case X86::PCMPESTRM128REG:
16784 case X86::VPCMPESTRM128REG:
16785 case X86::PCMPESTRM128MEM:
16786 case X86::VPCMPESTRM128MEM:
16787 assert(Subtarget->hasSSE42() &&
16788 "Target must have SSE4.2 or AVX features enabled");
16789 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16791 // String/text processing lowering.
16792 case X86::PCMPISTRIREG:
16793 case X86::VPCMPISTRIREG:
16794 case X86::PCMPISTRIMEM:
16795 case X86::VPCMPISTRIMEM:
16796 case X86::PCMPESTRIREG:
16797 case X86::VPCMPESTRIREG:
16798 case X86::PCMPESTRIMEM:
16799 case X86::VPCMPESTRIMEM:
16800 assert(Subtarget->hasSSE42() &&
16801 "Target must have SSE4.2 or AVX features enabled");
16802 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16804 // Thread synchronization.
16806 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16810 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16812 // Atomic Lowering.
16813 case X86::ATOMAND8:
16814 case X86::ATOMAND16:
16815 case X86::ATOMAND32:
16816 case X86::ATOMAND64:
16819 case X86::ATOMOR16:
16820 case X86::ATOMOR32:
16821 case X86::ATOMOR64:
16823 case X86::ATOMXOR16:
16824 case X86::ATOMXOR8:
16825 case X86::ATOMXOR32:
16826 case X86::ATOMXOR64:
16828 case X86::ATOMNAND8:
16829 case X86::ATOMNAND16:
16830 case X86::ATOMNAND32:
16831 case X86::ATOMNAND64:
16833 case X86::ATOMMAX8:
16834 case X86::ATOMMAX16:
16835 case X86::ATOMMAX32:
16836 case X86::ATOMMAX64:
16838 case X86::ATOMMIN8:
16839 case X86::ATOMMIN16:
16840 case X86::ATOMMIN32:
16841 case X86::ATOMMIN64:
16843 case X86::ATOMUMAX8:
16844 case X86::ATOMUMAX16:
16845 case X86::ATOMUMAX32:
16846 case X86::ATOMUMAX64:
16848 case X86::ATOMUMIN8:
16849 case X86::ATOMUMIN16:
16850 case X86::ATOMUMIN32:
16851 case X86::ATOMUMIN64:
16852 return EmitAtomicLoadArith(MI, BB);
16854 // This group does 64-bit operations on a 32-bit host.
16855 case X86::ATOMAND6432:
16856 case X86::ATOMOR6432:
16857 case X86::ATOMXOR6432:
16858 case X86::ATOMNAND6432:
16859 case X86::ATOMADD6432:
16860 case X86::ATOMSUB6432:
16861 case X86::ATOMMAX6432:
16862 case X86::ATOMMIN6432:
16863 case X86::ATOMUMAX6432:
16864 case X86::ATOMUMIN6432:
16865 case X86::ATOMSWAP6432:
16866 return EmitAtomicLoadArith6432(MI, BB);
16868 case X86::VASTART_SAVE_XMM_REGS:
16869 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16871 case X86::VAARG_64:
16872 return EmitVAARG64WithCustomInserter(MI, BB);
16874 case X86::EH_SjLj_SetJmp32:
16875 case X86::EH_SjLj_SetJmp64:
16876 return emitEHSjLjSetJmp(MI, BB);
16878 case X86::EH_SjLj_LongJmp32:
16879 case X86::EH_SjLj_LongJmp64:
16880 return emitEHSjLjLongJmp(MI, BB);
16882 case TargetOpcode::STACKMAP:
16883 case TargetOpcode::PATCHPOINT:
16884 return emitPatchPoint(MI, BB);
16886 case X86::VFMADDPDr213r:
16887 case X86::VFMADDPSr213r:
16888 case X86::VFMADDSDr213r:
16889 case X86::VFMADDSSr213r:
16890 case X86::VFMSUBPDr213r:
16891 case X86::VFMSUBPSr213r:
16892 case X86::VFMSUBSDr213r:
16893 case X86::VFMSUBSSr213r:
16894 case X86::VFNMADDPDr213r:
16895 case X86::VFNMADDPSr213r:
16896 case X86::VFNMADDSDr213r:
16897 case X86::VFNMADDSSr213r:
16898 case X86::VFNMSUBPDr213r:
16899 case X86::VFNMSUBPSr213r:
16900 case X86::VFNMSUBSDr213r:
16901 case X86::VFNMSUBSSr213r:
16902 case X86::VFMADDPDr213rY:
16903 case X86::VFMADDPSr213rY:
16904 case X86::VFMSUBPDr213rY:
16905 case X86::VFMSUBPSr213rY:
16906 case X86::VFNMADDPDr213rY:
16907 case X86::VFNMADDPSr213rY:
16908 case X86::VFNMSUBPDr213rY:
16909 case X86::VFNMSUBPSr213rY:
16910 return emitFMA3Instr(MI, BB);
16914 //===----------------------------------------------------------------------===//
16915 // X86 Optimization Hooks
16916 //===----------------------------------------------------------------------===//
16918 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16921 const SelectionDAG &DAG,
16922 unsigned Depth) const {
16923 unsigned BitWidth = KnownZero.getBitWidth();
16924 unsigned Opc = Op.getOpcode();
16925 assert((Opc >= ISD::BUILTIN_OP_END ||
16926 Opc == ISD::INTRINSIC_WO_CHAIN ||
16927 Opc == ISD::INTRINSIC_W_CHAIN ||
16928 Opc == ISD::INTRINSIC_VOID) &&
16929 "Should use MaskedValueIsZero if you don't know whether Op"
16930 " is a target node!");
16932 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16946 // These nodes' second result is a boolean.
16947 if (Op.getResNo() == 0)
16950 case X86ISD::SETCC:
16951 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16953 case ISD::INTRINSIC_WO_CHAIN: {
16954 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16955 unsigned NumLoBits = 0;
16958 case Intrinsic::x86_sse_movmsk_ps:
16959 case Intrinsic::x86_avx_movmsk_ps_256:
16960 case Intrinsic::x86_sse2_movmsk_pd:
16961 case Intrinsic::x86_avx_movmsk_pd_256:
16962 case Intrinsic::x86_mmx_pmovmskb:
16963 case Intrinsic::x86_sse2_pmovmskb_128:
16964 case Intrinsic::x86_avx2_pmovmskb: {
16965 // High bits of movmskp{s|d}, pmovmskb are known zero.
16967 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16968 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16969 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16970 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16971 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16972 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16973 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16974 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16976 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16985 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16987 const SelectionDAG &,
16988 unsigned Depth) const {
16989 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16990 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16991 return Op.getValueType().getScalarType().getSizeInBits();
16997 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16998 /// node is a GlobalAddress + offset.
16999 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17000 const GlobalValue* &GA,
17001 int64_t &Offset) const {
17002 if (N->getOpcode() == X86ISD::Wrapper) {
17003 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17004 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17005 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17009 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17012 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17013 /// same as extracting the high 128-bit part of 256-bit vector and then
17014 /// inserting the result into the low part of a new 256-bit vector
17015 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17016 EVT VT = SVOp->getValueType(0);
17017 unsigned NumElems = VT.getVectorNumElements();
17019 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17020 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17021 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17022 SVOp->getMaskElt(j) >= 0)
17028 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17029 /// same as extracting the low 128-bit part of 256-bit vector and then
17030 /// inserting the result into the high part of a new 256-bit vector
17031 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17032 EVT VT = SVOp->getValueType(0);
17033 unsigned NumElems = VT.getVectorNumElements();
17035 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17036 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17037 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17038 SVOp->getMaskElt(j) >= 0)
17044 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17045 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17046 TargetLowering::DAGCombinerInfo &DCI,
17047 const X86Subtarget* Subtarget) {
17049 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17050 SDValue V1 = SVOp->getOperand(0);
17051 SDValue V2 = SVOp->getOperand(1);
17052 EVT VT = SVOp->getValueType(0);
17053 unsigned NumElems = VT.getVectorNumElements();
17055 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17056 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17060 // V UNDEF BUILD_VECTOR UNDEF
17062 // CONCAT_VECTOR CONCAT_VECTOR
17065 // RESULT: V + zero extended
17067 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17068 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17069 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17072 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17075 // To match the shuffle mask, the first half of the mask should
17076 // be exactly the first vector, and all the rest a splat with the
17077 // first element of the second one.
17078 for (unsigned i = 0; i != NumElems/2; ++i)
17079 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17080 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17083 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17084 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17085 if (Ld->hasNUsesOfValue(1, 0)) {
17086 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17087 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17089 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17091 Ld->getPointerInfo(),
17092 Ld->getAlignment(),
17093 false/*isVolatile*/, true/*ReadMem*/,
17094 false/*WriteMem*/);
17096 // Make sure the newly-created LOAD is in the same position as Ld in
17097 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17098 // and update uses of Ld's output chain to use the TokenFactor.
17099 if (Ld->hasAnyUseOfValue(1)) {
17100 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17101 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17102 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17103 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17104 SDValue(ResNode.getNode(), 1));
17107 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17111 // Emit a zeroed vector and insert the desired subvector on its
17113 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17114 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17115 return DCI.CombineTo(N, InsV);
17118 //===--------------------------------------------------------------------===//
17119 // Combine some shuffles into subvector extracts and inserts:
17122 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17123 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17124 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17125 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17126 return DCI.CombineTo(N, InsV);
17129 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17130 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17131 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17132 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17133 return DCI.CombineTo(N, InsV);
17139 /// PerformShuffleCombine - Performs several different shuffle combines.
17140 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17141 TargetLowering::DAGCombinerInfo &DCI,
17142 const X86Subtarget *Subtarget) {
17144 EVT VT = N->getValueType(0);
17146 // Don't create instructions with illegal types after legalize types has run.
17147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17148 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17151 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17152 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17153 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17154 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17156 // Only handle 128 wide vector from here on.
17157 if (!VT.is128BitVector())
17160 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17161 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17162 // consecutive, non-overlapping, and in the right order.
17163 SmallVector<SDValue, 16> Elts;
17164 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17165 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17167 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17170 /// PerformTruncateCombine - Converts truncate operation to
17171 /// a sequence of vector shuffle operations.
17172 /// It is possible when we truncate 256-bit vector to 128-bit vector
17173 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17174 TargetLowering::DAGCombinerInfo &DCI,
17175 const X86Subtarget *Subtarget) {
17179 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17180 /// specific shuffle of a load can be folded into a single element load.
17181 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17182 /// shuffles have been customed lowered so we need to handle those here.
17183 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17184 TargetLowering::DAGCombinerInfo &DCI) {
17185 if (DCI.isBeforeLegalizeOps())
17188 SDValue InVec = N->getOperand(0);
17189 SDValue EltNo = N->getOperand(1);
17191 if (!isa<ConstantSDNode>(EltNo))
17194 EVT VT = InVec.getValueType();
17196 bool HasShuffleIntoBitcast = false;
17197 if (InVec.getOpcode() == ISD::BITCAST) {
17198 // Don't duplicate a load with other uses.
17199 if (!InVec.hasOneUse())
17201 EVT BCVT = InVec.getOperand(0).getValueType();
17202 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17204 InVec = InVec.getOperand(0);
17205 HasShuffleIntoBitcast = true;
17208 if (!isTargetShuffle(InVec.getOpcode()))
17211 // Don't duplicate a load with other uses.
17212 if (!InVec.hasOneUse())
17215 SmallVector<int, 16> ShuffleMask;
17217 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17221 // Select the input vector, guarding against out of range extract vector.
17222 unsigned NumElems = VT.getVectorNumElements();
17223 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17224 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17225 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17226 : InVec.getOperand(1);
17228 // If inputs to shuffle are the same for both ops, then allow 2 uses
17229 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17231 if (LdNode.getOpcode() == ISD::BITCAST) {
17232 // Don't duplicate a load with other uses.
17233 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17236 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17237 LdNode = LdNode.getOperand(0);
17240 if (!ISD::isNormalLoad(LdNode.getNode()))
17243 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17245 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17248 if (HasShuffleIntoBitcast) {
17249 // If there's a bitcast before the shuffle, check if the load type and
17250 // alignment is valid.
17251 unsigned Align = LN0->getAlignment();
17252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17253 unsigned NewAlign = TLI.getDataLayout()->
17254 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17256 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17260 // All checks match so transform back to vector_shuffle so that DAG combiner
17261 // can finish the job
17264 // Create shuffle node taking into account the case that its a unary shuffle
17265 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17266 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17267 InVec.getOperand(0), Shuffle,
17269 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17270 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17274 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17275 /// generation and convert it from being a bunch of shuffles and extracts
17276 /// to a simple store and scalar loads to extract the elements.
17277 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17278 TargetLowering::DAGCombinerInfo &DCI) {
17279 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17280 if (NewOp.getNode())
17283 SDValue InputVector = N->getOperand(0);
17285 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17286 // from mmx to v2i32 has a single usage.
17287 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17288 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17289 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17290 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17291 N->getValueType(0),
17292 InputVector.getNode()->getOperand(0));
17294 // Only operate on vectors of 4 elements, where the alternative shuffling
17295 // gets to be more expensive.
17296 if (InputVector.getValueType() != MVT::v4i32)
17299 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17300 // single use which is a sign-extend or zero-extend, and all elements are
17302 SmallVector<SDNode *, 4> Uses;
17303 unsigned ExtractedElements = 0;
17304 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17305 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17306 if (UI.getUse().getResNo() != InputVector.getResNo())
17309 SDNode *Extract = *UI;
17310 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17313 if (Extract->getValueType(0) != MVT::i32)
17315 if (!Extract->hasOneUse())
17317 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17318 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17320 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17323 // Record which element was extracted.
17324 ExtractedElements |=
17325 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17327 Uses.push_back(Extract);
17330 // If not all the elements were used, this may not be worthwhile.
17331 if (ExtractedElements != 15)
17334 // Ok, we've now decided to do the transformation.
17335 SDLoc dl(InputVector);
17337 // Store the value to a temporary stack slot.
17338 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17339 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17340 MachinePointerInfo(), false, false, 0);
17342 // Replace each use (extract) with a load of the appropriate element.
17343 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17344 UE = Uses.end(); UI != UE; ++UI) {
17345 SDNode *Extract = *UI;
17347 // cOMpute the element's address.
17348 SDValue Idx = Extract->getOperand(1);
17350 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17351 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17352 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17353 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17355 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17356 StackPtr, OffsetVal);
17358 // Load the scalar.
17359 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17360 ScalarAddr, MachinePointerInfo(),
17361 false, false, false, 0);
17363 // Replace the exact with the load.
17364 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17367 // The replacement was made in place; don't return anything.
17371 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17372 static std::pair<unsigned, bool>
17373 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17374 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17375 if (!VT.isVector())
17376 return std::make_pair(0, false);
17378 bool NeedSplit = false;
17379 switch (VT.getSimpleVT().SimpleTy) {
17380 default: return std::make_pair(0, false);
17384 if (!Subtarget->hasAVX2())
17386 if (!Subtarget->hasAVX())
17387 return std::make_pair(0, false);
17392 if (!Subtarget->hasSSE2())
17393 return std::make_pair(0, false);
17396 // SSE2 has only a small subset of the operations.
17397 bool hasUnsigned = Subtarget->hasSSE41() ||
17398 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17399 bool hasSigned = Subtarget->hasSSE41() ||
17400 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17402 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17405 // Check for x CC y ? x : y.
17406 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17407 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17412 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17415 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17418 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17421 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17423 // Check for x CC y ? y : x -- a min/max with reversed arms.
17424 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17425 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17430 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17433 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17436 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17439 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17443 return std::make_pair(Opc, NeedSplit);
17446 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17448 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17449 TargetLowering::DAGCombinerInfo &DCI,
17450 const X86Subtarget *Subtarget) {
17452 SDValue Cond = N->getOperand(0);
17453 // Get the LHS/RHS of the select.
17454 SDValue LHS = N->getOperand(1);
17455 SDValue RHS = N->getOperand(2);
17456 EVT VT = LHS.getValueType();
17457 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17459 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17460 // instructions match the semantics of the common C idiom x<y?x:y but not
17461 // x<=y?x:y, because of how they handle negative zero (which can be
17462 // ignored in unsafe-math mode).
17463 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17464 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17465 (Subtarget->hasSSE2() ||
17466 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17467 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17469 unsigned Opcode = 0;
17470 // Check for x CC y ? x : y.
17471 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17472 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17476 // Converting this to a min would handle NaNs incorrectly, and swapping
17477 // the operands would cause it to handle comparisons between positive
17478 // and negative zero incorrectly.
17479 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17480 if (!DAG.getTarget().Options.UnsafeFPMath &&
17481 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17483 std::swap(LHS, RHS);
17485 Opcode = X86ISD::FMIN;
17488 // Converting this to a min would handle comparisons between positive
17489 // and negative zero incorrectly.
17490 if (!DAG.getTarget().Options.UnsafeFPMath &&
17491 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17493 Opcode = X86ISD::FMIN;
17496 // Converting this to a min would handle both negative zeros and NaNs
17497 // incorrectly, but we can swap the operands to fix both.
17498 std::swap(LHS, RHS);
17502 Opcode = X86ISD::FMIN;
17506 // Converting this to a max would handle comparisons between positive
17507 // and negative zero incorrectly.
17508 if (!DAG.getTarget().Options.UnsafeFPMath &&
17509 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17511 Opcode = X86ISD::FMAX;
17514 // Converting this to a max would handle NaNs incorrectly, and swapping
17515 // the operands would cause it to handle comparisons between positive
17516 // and negative zero incorrectly.
17517 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17518 if (!DAG.getTarget().Options.UnsafeFPMath &&
17519 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17521 std::swap(LHS, RHS);
17523 Opcode = X86ISD::FMAX;
17526 // Converting this to a max would handle both negative zeros and NaNs
17527 // incorrectly, but we can swap the operands to fix both.
17528 std::swap(LHS, RHS);
17532 Opcode = X86ISD::FMAX;
17535 // Check for x CC y ? y : x -- a min/max with reversed arms.
17536 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17537 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17541 // Converting this to a min would handle comparisons between positive
17542 // and negative zero incorrectly, and swapping the operands would
17543 // cause it to handle NaNs incorrectly.
17544 if (!DAG.getTarget().Options.UnsafeFPMath &&
17545 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17546 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17548 std::swap(LHS, RHS);
17550 Opcode = X86ISD::FMIN;
17553 // Converting this to a min would handle NaNs incorrectly.
17554 if (!DAG.getTarget().Options.UnsafeFPMath &&
17555 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17557 Opcode = X86ISD::FMIN;
17560 // Converting this to a min would handle both negative zeros and NaNs
17561 // incorrectly, but we can swap the operands to fix both.
17562 std::swap(LHS, RHS);
17566 Opcode = X86ISD::FMIN;
17570 // Converting this to a max would handle NaNs incorrectly.
17571 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17573 Opcode = X86ISD::FMAX;
17576 // Converting this to a max would handle comparisons between positive
17577 // and negative zero incorrectly, and swapping the operands would
17578 // cause it to handle NaNs incorrectly.
17579 if (!DAG.getTarget().Options.UnsafeFPMath &&
17580 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17581 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17583 std::swap(LHS, RHS);
17585 Opcode = X86ISD::FMAX;
17588 // Converting this to a max would handle both negative zeros and NaNs
17589 // incorrectly, but we can swap the operands to fix both.
17590 std::swap(LHS, RHS);
17594 Opcode = X86ISD::FMAX;
17600 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17603 EVT CondVT = Cond.getValueType();
17604 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17605 CondVT.getVectorElementType() == MVT::i1) {
17606 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17607 // lowering on AVX-512. In this case we convert it to
17608 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17609 // The same situation for all 128 and 256-bit vectors of i8 and i16
17610 EVT OpVT = LHS.getValueType();
17611 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17612 (OpVT.getVectorElementType() == MVT::i8 ||
17613 OpVT.getVectorElementType() == MVT::i16)) {
17614 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17615 DCI.AddToWorklist(Cond.getNode());
17616 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17619 // If this is a select between two integer constants, try to do some
17621 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17622 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17623 // Don't do this for crazy integer types.
17624 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17625 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17626 // so that TrueC (the true value) is larger than FalseC.
17627 bool NeedsCondInvert = false;
17629 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17630 // Efficiently invertible.
17631 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17632 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17633 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17634 NeedsCondInvert = true;
17635 std::swap(TrueC, FalseC);
17638 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17639 if (FalseC->getAPIntValue() == 0 &&
17640 TrueC->getAPIntValue().isPowerOf2()) {
17641 if (NeedsCondInvert) // Invert the condition if needed.
17642 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17643 DAG.getConstant(1, Cond.getValueType()));
17645 // Zero extend the condition if needed.
17646 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17648 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17649 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17650 DAG.getConstant(ShAmt, MVT::i8));
17653 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17654 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17655 if (NeedsCondInvert) // Invert the condition if needed.
17656 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17657 DAG.getConstant(1, Cond.getValueType()));
17659 // Zero extend the condition if needed.
17660 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17661 FalseC->getValueType(0), Cond);
17662 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17663 SDValue(FalseC, 0));
17666 // Optimize cases that will turn into an LEA instruction. This requires
17667 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17668 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17669 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17670 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17672 bool isFastMultiplier = false;
17674 switch ((unsigned char)Diff) {
17676 case 1: // result = add base, cond
17677 case 2: // result = lea base( , cond*2)
17678 case 3: // result = lea base(cond, cond*2)
17679 case 4: // result = lea base( , cond*4)
17680 case 5: // result = lea base(cond, cond*4)
17681 case 8: // result = lea base( , cond*8)
17682 case 9: // result = lea base(cond, cond*8)
17683 isFastMultiplier = true;
17688 if (isFastMultiplier) {
17689 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17690 if (NeedsCondInvert) // Invert the condition if needed.
17691 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17692 DAG.getConstant(1, Cond.getValueType()));
17694 // Zero extend the condition if needed.
17695 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17697 // Scale the condition by the difference.
17699 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17700 DAG.getConstant(Diff, Cond.getValueType()));
17702 // Add the base if non-zero.
17703 if (FalseC->getAPIntValue() != 0)
17704 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17705 SDValue(FalseC, 0));
17712 // Canonicalize max and min:
17713 // (x > y) ? x : y -> (x >= y) ? x : y
17714 // (x < y) ? x : y -> (x <= y) ? x : y
17715 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17716 // the need for an extra compare
17717 // against zero. e.g.
17718 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17720 // testl %edi, %edi
17722 // cmovgl %edi, %eax
17726 // cmovsl %eax, %edi
17727 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17728 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17729 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17730 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17735 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17736 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17737 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17738 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17743 // Early exit check
17744 if (!TLI.isTypeLegal(VT))
17747 // Match VSELECTs into subs with unsigned saturation.
17748 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17749 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17750 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17751 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17752 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17754 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17755 // left side invert the predicate to simplify logic below.
17757 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17759 CC = ISD::getSetCCInverse(CC, true);
17760 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17764 if (Other.getNode() && Other->getNumOperands() == 2 &&
17765 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17766 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17767 SDValue CondRHS = Cond->getOperand(1);
17769 // Look for a general sub with unsigned saturation first.
17770 // x >= y ? x-y : 0 --> subus x, y
17771 // x > y ? x-y : 0 --> subus x, y
17772 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17773 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17774 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17776 // If the RHS is a constant we have to reverse the const canonicalization.
17777 // x > C-1 ? x+-C : 0 --> subus x, C
17778 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17779 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17780 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17781 if (CondRHS.getConstantOperandVal(0) == -A-1)
17782 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17783 DAG.getConstant(-A, VT));
17786 // Another special case: If C was a sign bit, the sub has been
17787 // canonicalized into a xor.
17788 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17789 // it's safe to decanonicalize the xor?
17790 // x s< 0 ? x^C : 0 --> subus x, C
17791 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17792 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17793 isSplatVector(OpRHS.getNode())) {
17794 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17796 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17801 // Try to match a min/max vector operation.
17802 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17803 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17804 unsigned Opc = ret.first;
17805 bool NeedSplit = ret.second;
17807 if (Opc && NeedSplit) {
17808 unsigned NumElems = VT.getVectorNumElements();
17809 // Extract the LHS vectors
17810 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17811 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17813 // Extract the RHS vectors
17814 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17815 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17817 // Create min/max for each subvector
17818 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17819 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17821 // Merge the result
17822 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17824 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17827 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17828 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17829 // Check if SETCC has already been promoted
17830 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17831 // Check that condition value type matches vselect operand type
17834 assert(Cond.getValueType().isVector() &&
17835 "vector select expects a vector selector!");
17837 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17838 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17840 if (!TValIsAllOnes && !FValIsAllZeros) {
17841 // Try invert the condition if true value is not all 1s and false value
17843 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17844 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17846 if (TValIsAllZeros || FValIsAllOnes) {
17847 SDValue CC = Cond.getOperand(2);
17848 ISD::CondCode NewCC =
17849 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17850 Cond.getOperand(0).getValueType().isInteger());
17851 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17852 std::swap(LHS, RHS);
17853 TValIsAllOnes = FValIsAllOnes;
17854 FValIsAllZeros = TValIsAllZeros;
17858 if (TValIsAllOnes || FValIsAllZeros) {
17861 if (TValIsAllOnes && FValIsAllZeros)
17863 else if (TValIsAllOnes)
17864 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17865 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17866 else if (FValIsAllZeros)
17867 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17868 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17870 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17874 // Try to fold this VSELECT into a MOVSS/MOVSD
17875 if (N->getOpcode() == ISD::VSELECT &&
17876 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17877 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17878 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17879 bool CanFold = false;
17880 unsigned NumElems = Cond.getNumOperands();
17884 if (isZero(Cond.getOperand(0))) {
17887 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17888 // fold (vselect <0,-1> -> (movsd A, B)
17889 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17890 CanFold = isAllOnes(Cond.getOperand(i));
17891 } else if (isAllOnes(Cond.getOperand(0))) {
17895 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17896 // fold (vselect <-1,0> -> (movsd B, A)
17897 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17898 CanFold = isZero(Cond.getOperand(i));
17902 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17903 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17904 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17907 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17908 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17909 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17910 // (v2i64 (bitcast B)))))
17912 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17913 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17914 // (v2f64 (bitcast B)))))
17916 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17917 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17918 // (v2i64 (bitcast A)))))
17920 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17921 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17922 // (v2f64 (bitcast A)))))
17924 CanFold = (isZero(Cond.getOperand(0)) &&
17925 isZero(Cond.getOperand(1)) &&
17926 isAllOnes(Cond.getOperand(2)) &&
17927 isAllOnes(Cond.getOperand(3)));
17929 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17930 isAllOnes(Cond.getOperand(1)) &&
17931 isZero(Cond.getOperand(2)) &&
17932 isZero(Cond.getOperand(3))) {
17934 std::swap(LHS, RHS);
17938 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17939 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17940 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17941 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17943 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17949 // If we know that this node is legal then we know that it is going to be
17950 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17951 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17952 // to simplify previous instructions.
17953 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17954 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17955 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17957 // Don't optimize vector selects that map to mask-registers.
17961 // Check all uses of that condition operand to check whether it will be
17962 // consumed by non-BLEND instructions, which may depend on all bits are set
17964 for (SDNode::use_iterator I = Cond->use_begin(),
17965 E = Cond->use_end(); I != E; ++I)
17966 if (I->getOpcode() != ISD::VSELECT)
17967 // TODO: Add other opcodes eventually lowered into BLEND.
17970 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17971 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17973 APInt KnownZero, KnownOne;
17974 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17975 DCI.isBeforeLegalizeOps());
17976 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17977 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17978 DCI.CommitTargetLoweringOpt(TLO);
17984 // Check whether a boolean test is testing a boolean value generated by
17985 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17988 // Simplify the following patterns:
17989 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17990 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17991 // to (Op EFLAGS Cond)
17993 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17994 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17995 // to (Op EFLAGS !Cond)
17997 // where Op could be BRCOND or CMOV.
17999 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18000 // Quit if not CMP and SUB with its value result used.
18001 if (Cmp.getOpcode() != X86ISD::CMP &&
18002 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18005 // Quit if not used as a boolean value.
18006 if (CC != X86::COND_E && CC != X86::COND_NE)
18009 // Check CMP operands. One of them should be 0 or 1 and the other should be
18010 // an SetCC or extended from it.
18011 SDValue Op1 = Cmp.getOperand(0);
18012 SDValue Op2 = Cmp.getOperand(1);
18015 const ConstantSDNode* C = nullptr;
18016 bool needOppositeCond = (CC == X86::COND_E);
18017 bool checkAgainstTrue = false; // Is it a comparison against 1?
18019 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18021 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18023 else // Quit if all operands are not constants.
18026 if (C->getZExtValue() == 1) {
18027 needOppositeCond = !needOppositeCond;
18028 checkAgainstTrue = true;
18029 } else if (C->getZExtValue() != 0)
18030 // Quit if the constant is neither 0 or 1.
18033 bool truncatedToBoolWithAnd = false;
18034 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18035 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18036 SetCC.getOpcode() == ISD::TRUNCATE ||
18037 SetCC.getOpcode() == ISD::AND) {
18038 if (SetCC.getOpcode() == ISD::AND) {
18040 ConstantSDNode *CS;
18041 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18042 CS->getZExtValue() == 1)
18044 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18045 CS->getZExtValue() == 1)
18049 SetCC = SetCC.getOperand(OpIdx);
18050 truncatedToBoolWithAnd = true;
18052 SetCC = SetCC.getOperand(0);
18055 switch (SetCC.getOpcode()) {
18056 case X86ISD::SETCC_CARRY:
18057 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18058 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18059 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18060 // truncated to i1 using 'and'.
18061 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18063 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18064 "Invalid use of SETCC_CARRY!");
18066 case X86ISD::SETCC:
18067 // Set the condition code or opposite one if necessary.
18068 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18069 if (needOppositeCond)
18070 CC = X86::GetOppositeBranchCondition(CC);
18071 return SetCC.getOperand(1);
18072 case X86ISD::CMOV: {
18073 // Check whether false/true value has canonical one, i.e. 0 or 1.
18074 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18075 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18076 // Quit if true value is not a constant.
18079 // Quit if false value is not a constant.
18081 SDValue Op = SetCC.getOperand(0);
18082 // Skip 'zext' or 'trunc' node.
18083 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18084 Op.getOpcode() == ISD::TRUNCATE)
18085 Op = Op.getOperand(0);
18086 // A special case for rdrand/rdseed, where 0 is set if false cond is
18088 if ((Op.getOpcode() != X86ISD::RDRAND &&
18089 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18092 // Quit if false value is not the constant 0 or 1.
18093 bool FValIsFalse = true;
18094 if (FVal && FVal->getZExtValue() != 0) {
18095 if (FVal->getZExtValue() != 1)
18097 // If FVal is 1, opposite cond is needed.
18098 needOppositeCond = !needOppositeCond;
18099 FValIsFalse = false;
18101 // Quit if TVal is not the constant opposite of FVal.
18102 if (FValIsFalse && TVal->getZExtValue() != 1)
18104 if (!FValIsFalse && TVal->getZExtValue() != 0)
18106 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18107 if (needOppositeCond)
18108 CC = X86::GetOppositeBranchCondition(CC);
18109 return SetCC.getOperand(3);
18116 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18117 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18118 TargetLowering::DAGCombinerInfo &DCI,
18119 const X86Subtarget *Subtarget) {
18122 // If the flag operand isn't dead, don't touch this CMOV.
18123 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18126 SDValue FalseOp = N->getOperand(0);
18127 SDValue TrueOp = N->getOperand(1);
18128 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18129 SDValue Cond = N->getOperand(3);
18131 if (CC == X86::COND_E || CC == X86::COND_NE) {
18132 switch (Cond.getOpcode()) {
18136 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18137 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18138 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18144 Flags = checkBoolTestSetCCCombine(Cond, CC);
18145 if (Flags.getNode() &&
18146 // Extra check as FCMOV only supports a subset of X86 cond.
18147 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18148 SDValue Ops[] = { FalseOp, TrueOp,
18149 DAG.getConstant(CC, MVT::i8), Flags };
18150 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18153 // If this is a select between two integer constants, try to do some
18154 // optimizations. Note that the operands are ordered the opposite of SELECT
18156 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18157 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18158 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18159 // larger than FalseC (the false value).
18160 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18161 CC = X86::GetOppositeBranchCondition(CC);
18162 std::swap(TrueC, FalseC);
18163 std::swap(TrueOp, FalseOp);
18166 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18167 // This is efficient for any integer data type (including i8/i16) and
18169 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18170 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18171 DAG.getConstant(CC, MVT::i8), Cond);
18173 // Zero extend the condition if needed.
18174 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18176 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18177 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18178 DAG.getConstant(ShAmt, MVT::i8));
18179 if (N->getNumValues() == 2) // Dead flag value?
18180 return DCI.CombineTo(N, Cond, SDValue());
18184 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18185 // for any integer data type, including i8/i16.
18186 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18187 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18188 DAG.getConstant(CC, MVT::i8), Cond);
18190 // Zero extend the condition if needed.
18191 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18192 FalseC->getValueType(0), Cond);
18193 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18194 SDValue(FalseC, 0));
18196 if (N->getNumValues() == 2) // Dead flag value?
18197 return DCI.CombineTo(N, Cond, SDValue());
18201 // Optimize cases that will turn into an LEA instruction. This requires
18202 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18203 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18204 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18205 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18207 bool isFastMultiplier = false;
18209 switch ((unsigned char)Diff) {
18211 case 1: // result = add base, cond
18212 case 2: // result = lea base( , cond*2)
18213 case 3: // result = lea base(cond, cond*2)
18214 case 4: // result = lea base( , cond*4)
18215 case 5: // result = lea base(cond, cond*4)
18216 case 8: // result = lea base( , cond*8)
18217 case 9: // result = lea base(cond, cond*8)
18218 isFastMultiplier = true;
18223 if (isFastMultiplier) {
18224 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18225 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18226 DAG.getConstant(CC, MVT::i8), Cond);
18227 // Zero extend the condition if needed.
18228 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18230 // Scale the condition by the difference.
18232 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18233 DAG.getConstant(Diff, Cond.getValueType()));
18235 // Add the base if non-zero.
18236 if (FalseC->getAPIntValue() != 0)
18237 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18238 SDValue(FalseC, 0));
18239 if (N->getNumValues() == 2) // Dead flag value?
18240 return DCI.CombineTo(N, Cond, SDValue());
18247 // Handle these cases:
18248 // (select (x != c), e, c) -> select (x != c), e, x),
18249 // (select (x == c), c, e) -> select (x == c), x, e)
18250 // where the c is an integer constant, and the "select" is the combination
18251 // of CMOV and CMP.
18253 // The rationale for this change is that the conditional-move from a constant
18254 // needs two instructions, however, conditional-move from a register needs
18255 // only one instruction.
18257 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18258 // some instruction-combining opportunities. This opt needs to be
18259 // postponed as late as possible.
18261 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18262 // the DCI.xxxx conditions are provided to postpone the optimization as
18263 // late as possible.
18265 ConstantSDNode *CmpAgainst = nullptr;
18266 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18267 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18268 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18270 if (CC == X86::COND_NE &&
18271 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18272 CC = X86::GetOppositeBranchCondition(CC);
18273 std::swap(TrueOp, FalseOp);
18276 if (CC == X86::COND_E &&
18277 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18278 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18279 DAG.getConstant(CC, MVT::i8), Cond };
18280 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18288 /// PerformMulCombine - Optimize a single multiply with constant into two
18289 /// in order to implement it with two cheaper instructions, e.g.
18290 /// LEA + SHL, LEA + LEA.
18291 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18292 TargetLowering::DAGCombinerInfo &DCI) {
18293 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18296 EVT VT = N->getValueType(0);
18297 if (VT != MVT::i64)
18300 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18303 uint64_t MulAmt = C->getZExtValue();
18304 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18307 uint64_t MulAmt1 = 0;
18308 uint64_t MulAmt2 = 0;
18309 if ((MulAmt % 9) == 0) {
18311 MulAmt2 = MulAmt / 9;
18312 } else if ((MulAmt % 5) == 0) {
18314 MulAmt2 = MulAmt / 5;
18315 } else if ((MulAmt % 3) == 0) {
18317 MulAmt2 = MulAmt / 3;
18320 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18323 if (isPowerOf2_64(MulAmt2) &&
18324 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18325 // If second multiplifer is pow2, issue it first. We want the multiply by
18326 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18328 std::swap(MulAmt1, MulAmt2);
18331 if (isPowerOf2_64(MulAmt1))
18332 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18333 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18335 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18336 DAG.getConstant(MulAmt1, VT));
18338 if (isPowerOf2_64(MulAmt2))
18339 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18340 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18342 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18343 DAG.getConstant(MulAmt2, VT));
18345 // Do not add new nodes to DAG combiner worklist.
18346 DCI.CombineTo(N, NewMul, false);
18351 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18352 SDValue N0 = N->getOperand(0);
18353 SDValue N1 = N->getOperand(1);
18354 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18355 EVT VT = N0.getValueType();
18357 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18358 // since the result of setcc_c is all zero's or all ones.
18359 if (VT.isInteger() && !VT.isVector() &&
18360 N1C && N0.getOpcode() == ISD::AND &&
18361 N0.getOperand(1).getOpcode() == ISD::Constant) {
18362 SDValue N00 = N0.getOperand(0);
18363 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18364 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18365 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18366 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18367 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18368 APInt ShAmt = N1C->getAPIntValue();
18369 Mask = Mask.shl(ShAmt);
18371 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18372 N00, DAG.getConstant(Mask, VT));
18376 // Hardware support for vector shifts is sparse which makes us scalarize the
18377 // vector operations in many cases. Also, on sandybridge ADD is faster than
18379 // (shl V, 1) -> add V,V
18380 if (isSplatVector(N1.getNode())) {
18381 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18382 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18383 // We shift all of the values by one. In many cases we do not have
18384 // hardware support for this operation. This is better expressed as an ADD
18386 if (N1C && (1 == N1C->getZExtValue())) {
18387 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18394 /// \brief Returns a vector of 0s if the node in input is a vector logical
18395 /// shift by a constant amount which is known to be bigger than or equal
18396 /// to the vector element size in bits.
18397 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18398 const X86Subtarget *Subtarget) {
18399 EVT VT = N->getValueType(0);
18401 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18402 (!Subtarget->hasInt256() ||
18403 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18406 SDValue Amt = N->getOperand(1);
18408 if (isSplatVector(Amt.getNode())) {
18409 SDValue SclrAmt = Amt->getOperand(0);
18410 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18411 APInt ShiftAmt = C->getAPIntValue();
18412 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18414 // SSE2/AVX2 logical shifts always return a vector of 0s
18415 // if the shift amount is bigger than or equal to
18416 // the element size. The constant shift amount will be
18417 // encoded as a 8-bit immediate.
18418 if (ShiftAmt.trunc(8).uge(MaxAmount))
18419 return getZeroVector(VT, Subtarget, DAG, DL);
18426 /// PerformShiftCombine - Combine shifts.
18427 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18428 TargetLowering::DAGCombinerInfo &DCI,
18429 const X86Subtarget *Subtarget) {
18430 if (N->getOpcode() == ISD::SHL) {
18431 SDValue V = PerformSHLCombine(N, DAG);
18432 if (V.getNode()) return V;
18435 if (N->getOpcode() != ISD::SRA) {
18436 // Try to fold this logical shift into a zero vector.
18437 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18438 if (V.getNode()) return V;
18444 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18445 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18446 // and friends. Likewise for OR -> CMPNEQSS.
18447 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18448 TargetLowering::DAGCombinerInfo &DCI,
18449 const X86Subtarget *Subtarget) {
18452 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18453 // we're requiring SSE2 for both.
18454 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18455 SDValue N0 = N->getOperand(0);
18456 SDValue N1 = N->getOperand(1);
18457 SDValue CMP0 = N0->getOperand(1);
18458 SDValue CMP1 = N1->getOperand(1);
18461 // The SETCCs should both refer to the same CMP.
18462 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18465 SDValue CMP00 = CMP0->getOperand(0);
18466 SDValue CMP01 = CMP0->getOperand(1);
18467 EVT VT = CMP00.getValueType();
18469 if (VT == MVT::f32 || VT == MVT::f64) {
18470 bool ExpectingFlags = false;
18471 // Check for any users that want flags:
18472 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18473 !ExpectingFlags && UI != UE; ++UI)
18474 switch (UI->getOpcode()) {
18479 ExpectingFlags = true;
18481 case ISD::CopyToReg:
18482 case ISD::SIGN_EXTEND:
18483 case ISD::ZERO_EXTEND:
18484 case ISD::ANY_EXTEND:
18488 if (!ExpectingFlags) {
18489 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18490 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18492 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18493 X86::CondCode tmp = cc0;
18498 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18499 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18500 // FIXME: need symbolic constants for these magic numbers.
18501 // See X86ATTInstPrinter.cpp:printSSECC().
18502 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18503 if (Subtarget->hasAVX512()) {
18504 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18505 CMP01, DAG.getConstant(x86cc, MVT::i8));
18506 if (N->getValueType(0) != MVT::i1)
18507 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18511 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18512 CMP00.getValueType(), CMP00, CMP01,
18513 DAG.getConstant(x86cc, MVT::i8));
18515 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18516 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18518 if (is64BitFP && !Subtarget->is64Bit()) {
18519 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18520 // 64-bit integer, since that's not a legal type. Since
18521 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18522 // bits, but can do this little dance to extract the lowest 32 bits
18523 // and work with those going forward.
18524 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18526 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18528 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18529 Vector32, DAG.getIntPtrConstant(0));
18533 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18534 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18535 DAG.getConstant(1, IntVT));
18536 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18537 return OneBitOfTruth;
18545 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18546 /// so it can be folded inside ANDNP.
18547 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18548 EVT VT = N->getValueType(0);
18550 // Match direct AllOnes for 128 and 256-bit vectors
18551 if (ISD::isBuildVectorAllOnes(N))
18554 // Look through a bit convert.
18555 if (N->getOpcode() == ISD::BITCAST)
18556 N = N->getOperand(0).getNode();
18558 // Sometimes the operand may come from a insert_subvector building a 256-bit
18560 if (VT.is256BitVector() &&
18561 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18562 SDValue V1 = N->getOperand(0);
18563 SDValue V2 = N->getOperand(1);
18565 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18566 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18567 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18568 ISD::isBuildVectorAllOnes(V2.getNode()))
18575 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18576 // register. In most cases we actually compare or select YMM-sized registers
18577 // and mixing the two types creates horrible code. This method optimizes
18578 // some of the transition sequences.
18579 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18580 TargetLowering::DAGCombinerInfo &DCI,
18581 const X86Subtarget *Subtarget) {
18582 EVT VT = N->getValueType(0);
18583 if (!VT.is256BitVector())
18586 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18587 N->getOpcode() == ISD::ZERO_EXTEND ||
18588 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18590 SDValue Narrow = N->getOperand(0);
18591 EVT NarrowVT = Narrow->getValueType(0);
18592 if (!NarrowVT.is128BitVector())
18595 if (Narrow->getOpcode() != ISD::XOR &&
18596 Narrow->getOpcode() != ISD::AND &&
18597 Narrow->getOpcode() != ISD::OR)
18600 SDValue N0 = Narrow->getOperand(0);
18601 SDValue N1 = Narrow->getOperand(1);
18604 // The Left side has to be a trunc.
18605 if (N0.getOpcode() != ISD::TRUNCATE)
18608 // The type of the truncated inputs.
18609 EVT WideVT = N0->getOperand(0)->getValueType(0);
18613 // The right side has to be a 'trunc' or a constant vector.
18614 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18615 bool RHSConst = (isSplatVector(N1.getNode()) &&
18616 isa<ConstantSDNode>(N1->getOperand(0)));
18617 if (!RHSTrunc && !RHSConst)
18620 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18622 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18625 // Set N0 and N1 to hold the inputs to the new wide operation.
18626 N0 = N0->getOperand(0);
18628 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18629 N1->getOperand(0));
18630 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18631 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18632 } else if (RHSTrunc) {
18633 N1 = N1->getOperand(0);
18636 // Generate the wide operation.
18637 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18638 unsigned Opcode = N->getOpcode();
18640 case ISD::ANY_EXTEND:
18642 case ISD::ZERO_EXTEND: {
18643 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18644 APInt Mask = APInt::getAllOnesValue(InBits);
18645 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18646 return DAG.getNode(ISD::AND, DL, VT,
18647 Op, DAG.getConstant(Mask, VT));
18649 case ISD::SIGN_EXTEND:
18650 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18651 Op, DAG.getValueType(NarrowVT));
18653 llvm_unreachable("Unexpected opcode");
18657 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18658 TargetLowering::DAGCombinerInfo &DCI,
18659 const X86Subtarget *Subtarget) {
18660 EVT VT = N->getValueType(0);
18661 if (DCI.isBeforeLegalizeOps())
18664 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18668 // Create BEXTR instructions
18669 // BEXTR is ((X >> imm) & (2**size-1))
18670 if (VT == MVT::i32 || VT == MVT::i64) {
18671 SDValue N0 = N->getOperand(0);
18672 SDValue N1 = N->getOperand(1);
18675 // Check for BEXTR.
18676 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18677 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18678 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18679 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18680 if (MaskNode && ShiftNode) {
18681 uint64_t Mask = MaskNode->getZExtValue();
18682 uint64_t Shift = ShiftNode->getZExtValue();
18683 if (isMask_64(Mask)) {
18684 uint64_t MaskSize = CountPopulation_64(Mask);
18685 if (Shift + MaskSize <= VT.getSizeInBits())
18686 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18687 DAG.getConstant(Shift | (MaskSize << 8), VT));
18695 // Want to form ANDNP nodes:
18696 // 1) In the hopes of then easily combining them with OR and AND nodes
18697 // to form PBLEND/PSIGN.
18698 // 2) To match ANDN packed intrinsics
18699 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18702 SDValue N0 = N->getOperand(0);
18703 SDValue N1 = N->getOperand(1);
18706 // Check LHS for vnot
18707 if (N0.getOpcode() == ISD::XOR &&
18708 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18709 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18710 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18712 // Check RHS for vnot
18713 if (N1.getOpcode() == ISD::XOR &&
18714 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18715 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18716 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18721 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18722 TargetLowering::DAGCombinerInfo &DCI,
18723 const X86Subtarget *Subtarget) {
18724 if (DCI.isBeforeLegalizeOps())
18727 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18731 SDValue N0 = N->getOperand(0);
18732 SDValue N1 = N->getOperand(1);
18733 EVT VT = N->getValueType(0);
18735 // look for psign/blend
18736 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18737 if (!Subtarget->hasSSSE3() ||
18738 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18741 // Canonicalize pandn to RHS
18742 if (N0.getOpcode() == X86ISD::ANDNP)
18744 // or (and (m, y), (pandn m, x))
18745 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18746 SDValue Mask = N1.getOperand(0);
18747 SDValue X = N1.getOperand(1);
18749 if (N0.getOperand(0) == Mask)
18750 Y = N0.getOperand(1);
18751 if (N0.getOperand(1) == Mask)
18752 Y = N0.getOperand(0);
18754 // Check to see if the mask appeared in both the AND and ANDNP and
18758 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18759 // Look through mask bitcast.
18760 if (Mask.getOpcode() == ISD::BITCAST)
18761 Mask = Mask.getOperand(0);
18762 if (X.getOpcode() == ISD::BITCAST)
18763 X = X.getOperand(0);
18764 if (Y.getOpcode() == ISD::BITCAST)
18765 Y = Y.getOperand(0);
18767 EVT MaskVT = Mask.getValueType();
18769 // Validate that the Mask operand is a vector sra node.
18770 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18771 // there is no psrai.b
18772 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18773 unsigned SraAmt = ~0;
18774 if (Mask.getOpcode() == ISD::SRA) {
18775 SDValue Amt = Mask.getOperand(1);
18776 if (isSplatVector(Amt.getNode())) {
18777 SDValue SclrAmt = Amt->getOperand(0);
18778 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18779 SraAmt = C->getZExtValue();
18781 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18782 SDValue SraC = Mask.getOperand(1);
18783 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18785 if ((SraAmt + 1) != EltBits)
18790 // Now we know we at least have a plendvb with the mask val. See if
18791 // we can form a psignb/w/d.
18792 // psign = x.type == y.type == mask.type && y = sub(0, x);
18793 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18794 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18795 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18796 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18797 "Unsupported VT for PSIGN");
18798 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18799 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18801 // PBLENDVB only available on SSE 4.1
18802 if (!Subtarget->hasSSE41())
18805 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18807 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18808 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18809 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18810 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18811 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18815 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18818 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18819 MachineFunction &MF = DAG.getMachineFunction();
18820 bool OptForSize = MF.getFunction()->getAttributes().
18821 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18823 // SHLD/SHRD instructions have lower register pressure, but on some
18824 // platforms they have higher latency than the equivalent
18825 // series of shifts/or that would otherwise be generated.
18826 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18827 // have higher latencies and we are not optimizing for size.
18828 if (!OptForSize && Subtarget->isSHLDSlow())
18831 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18833 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18835 if (!N0.hasOneUse() || !N1.hasOneUse())
18838 SDValue ShAmt0 = N0.getOperand(1);
18839 if (ShAmt0.getValueType() != MVT::i8)
18841 SDValue ShAmt1 = N1.getOperand(1);
18842 if (ShAmt1.getValueType() != MVT::i8)
18844 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18845 ShAmt0 = ShAmt0.getOperand(0);
18846 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18847 ShAmt1 = ShAmt1.getOperand(0);
18850 unsigned Opc = X86ISD::SHLD;
18851 SDValue Op0 = N0.getOperand(0);
18852 SDValue Op1 = N1.getOperand(0);
18853 if (ShAmt0.getOpcode() == ISD::SUB) {
18854 Opc = X86ISD::SHRD;
18855 std::swap(Op0, Op1);
18856 std::swap(ShAmt0, ShAmt1);
18859 unsigned Bits = VT.getSizeInBits();
18860 if (ShAmt1.getOpcode() == ISD::SUB) {
18861 SDValue Sum = ShAmt1.getOperand(0);
18862 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18863 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18864 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18865 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18866 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18867 return DAG.getNode(Opc, DL, VT,
18869 DAG.getNode(ISD::TRUNCATE, DL,
18872 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18873 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18875 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18876 return DAG.getNode(Opc, DL, VT,
18877 N0.getOperand(0), N1.getOperand(0),
18878 DAG.getNode(ISD::TRUNCATE, DL,
18885 // Generate NEG and CMOV for integer abs.
18886 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18887 EVT VT = N->getValueType(0);
18889 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18890 // 8-bit integer abs to NEG and CMOV.
18891 if (VT.isInteger() && VT.getSizeInBits() == 8)
18894 SDValue N0 = N->getOperand(0);
18895 SDValue N1 = N->getOperand(1);
18898 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18899 // and change it to SUB and CMOV.
18900 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18901 N0.getOpcode() == ISD::ADD &&
18902 N0.getOperand(1) == N1 &&
18903 N1.getOpcode() == ISD::SRA &&
18904 N1.getOperand(0) == N0.getOperand(0))
18905 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18906 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18907 // Generate SUB & CMOV.
18908 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18909 DAG.getConstant(0, VT), N0.getOperand(0));
18911 SDValue Ops[] = { N0.getOperand(0), Neg,
18912 DAG.getConstant(X86::COND_GE, MVT::i8),
18913 SDValue(Neg.getNode(), 1) };
18914 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18919 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18920 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18921 TargetLowering::DAGCombinerInfo &DCI,
18922 const X86Subtarget *Subtarget) {
18923 if (DCI.isBeforeLegalizeOps())
18926 if (Subtarget->hasCMov()) {
18927 SDValue RV = performIntegerAbsCombine(N, DAG);
18935 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18936 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18937 TargetLowering::DAGCombinerInfo &DCI,
18938 const X86Subtarget *Subtarget) {
18939 LoadSDNode *Ld = cast<LoadSDNode>(N);
18940 EVT RegVT = Ld->getValueType(0);
18941 EVT MemVT = Ld->getMemoryVT();
18943 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18944 unsigned RegSz = RegVT.getSizeInBits();
18946 // On Sandybridge unaligned 256bit loads are inefficient.
18947 ISD::LoadExtType Ext = Ld->getExtensionType();
18948 unsigned Alignment = Ld->getAlignment();
18949 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18950 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18951 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18952 unsigned NumElems = RegVT.getVectorNumElements();
18956 SDValue Ptr = Ld->getBasePtr();
18957 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18959 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18961 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18962 Ld->getPointerInfo(), Ld->isVolatile(),
18963 Ld->isNonTemporal(), Ld->isInvariant(),
18965 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18966 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18967 Ld->getPointerInfo(), Ld->isVolatile(),
18968 Ld->isNonTemporal(), Ld->isInvariant(),
18969 std::min(16U, Alignment));
18970 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18972 Load2.getValue(1));
18974 SDValue NewVec = DAG.getUNDEF(RegVT);
18975 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18976 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18977 return DCI.CombineTo(N, NewVec, TF, true);
18980 // If this is a vector EXT Load then attempt to optimize it using a
18981 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18982 // expansion is still better than scalar code.
18983 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18984 // emit a shuffle and a arithmetic shift.
18985 // TODO: It is possible to support ZExt by zeroing the undef values
18986 // during the shuffle phase or after the shuffle.
18987 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18988 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18989 assert(MemVT != RegVT && "Cannot extend to the same type");
18990 assert(MemVT.isVector() && "Must load a vector from memory");
18992 unsigned NumElems = RegVT.getVectorNumElements();
18993 unsigned MemSz = MemVT.getSizeInBits();
18994 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18996 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18999 // All sizes must be a power of two.
19000 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19003 // Attempt to load the original value using scalar loads.
19004 // Find the largest scalar type that divides the total loaded size.
19005 MVT SclrLoadTy = MVT::i8;
19006 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19007 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19008 MVT Tp = (MVT::SimpleValueType)tp;
19009 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19014 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19015 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19017 SclrLoadTy = MVT::f64;
19019 // Calculate the number of scalar loads that we need to perform
19020 // in order to load our vector from memory.
19021 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19022 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19025 unsigned loadRegZize = RegSz;
19026 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19029 // Represent our vector as a sequence of elements which are the
19030 // largest scalar that we can load.
19031 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19032 loadRegZize/SclrLoadTy.getSizeInBits());
19034 // Represent the data using the same element type that is stored in
19035 // memory. In practice, we ''widen'' MemVT.
19037 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19038 loadRegZize/MemVT.getScalarType().getSizeInBits());
19040 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19041 "Invalid vector type");
19043 // We can't shuffle using an illegal type.
19044 if (!TLI.isTypeLegal(WideVecVT))
19047 SmallVector<SDValue, 8> Chains;
19048 SDValue Ptr = Ld->getBasePtr();
19049 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19050 TLI.getPointerTy());
19051 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19053 for (unsigned i = 0; i < NumLoads; ++i) {
19054 // Perform a single load.
19055 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19056 Ptr, Ld->getPointerInfo(),
19057 Ld->isVolatile(), Ld->isNonTemporal(),
19058 Ld->isInvariant(), Ld->getAlignment());
19059 Chains.push_back(ScalarLoad.getValue(1));
19060 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19061 // another round of DAGCombining.
19063 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19065 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19066 ScalarLoad, DAG.getIntPtrConstant(i));
19068 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19071 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19073 // Bitcast the loaded value to a vector of the original element type, in
19074 // the size of the target vector type.
19075 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19076 unsigned SizeRatio = RegSz/MemSz;
19078 if (Ext == ISD::SEXTLOAD) {
19079 // If we have SSE4.1 we can directly emit a VSEXT node.
19080 if (Subtarget->hasSSE41()) {
19081 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19082 return DCI.CombineTo(N, Sext, TF, true);
19085 // Otherwise we'll shuffle the small elements in the high bits of the
19086 // larger type and perform an arithmetic shift. If the shift is not legal
19087 // it's better to scalarize.
19088 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19091 // Redistribute the loaded elements into the different locations.
19092 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19093 for (unsigned i = 0; i != NumElems; ++i)
19094 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19096 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19097 DAG.getUNDEF(WideVecVT),
19100 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19102 // Build the arithmetic shift.
19103 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19104 MemVT.getVectorElementType().getSizeInBits();
19105 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19106 DAG.getConstant(Amt, RegVT));
19108 return DCI.CombineTo(N, Shuff, TF, true);
19111 // Redistribute the loaded elements into the different locations.
19112 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19113 for (unsigned i = 0; i != NumElems; ++i)
19114 ShuffleVec[i*SizeRatio] = i;
19116 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19117 DAG.getUNDEF(WideVecVT),
19120 // Bitcast to the requested type.
19121 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19122 // Replace the original load with the new sequence
19123 // and return the new chain.
19124 return DCI.CombineTo(N, Shuff, TF, true);
19130 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19131 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19132 const X86Subtarget *Subtarget) {
19133 StoreSDNode *St = cast<StoreSDNode>(N);
19134 EVT VT = St->getValue().getValueType();
19135 EVT StVT = St->getMemoryVT();
19137 SDValue StoredVal = St->getOperand(1);
19138 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19140 // If we are saving a concatenation of two XMM registers, perform two stores.
19141 // On Sandy Bridge, 256-bit memory operations are executed by two
19142 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19143 // memory operation.
19144 unsigned Alignment = St->getAlignment();
19145 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19146 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19147 StVT == VT && !IsAligned) {
19148 unsigned NumElems = VT.getVectorNumElements();
19152 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19153 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19155 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19156 SDValue Ptr0 = St->getBasePtr();
19157 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19159 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19160 St->getPointerInfo(), St->isVolatile(),
19161 St->isNonTemporal(), Alignment);
19162 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19163 St->getPointerInfo(), St->isVolatile(),
19164 St->isNonTemporal(),
19165 std::min(16U, Alignment));
19166 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19169 // Optimize trunc store (of multiple scalars) to shuffle and store.
19170 // First, pack all of the elements in one place. Next, store to memory
19171 // in fewer chunks.
19172 if (St->isTruncatingStore() && VT.isVector()) {
19173 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19174 unsigned NumElems = VT.getVectorNumElements();
19175 assert(StVT != VT && "Cannot truncate to the same type");
19176 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19177 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19179 // From, To sizes and ElemCount must be pow of two
19180 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19181 // We are going to use the original vector elt for storing.
19182 // Accumulated smaller vector elements must be a multiple of the store size.
19183 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19185 unsigned SizeRatio = FromSz / ToSz;
19187 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19189 // Create a type on which we perform the shuffle
19190 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19191 StVT.getScalarType(), NumElems*SizeRatio);
19193 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19195 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19196 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19197 for (unsigned i = 0; i != NumElems; ++i)
19198 ShuffleVec[i] = i * SizeRatio;
19200 // Can't shuffle using an illegal type.
19201 if (!TLI.isTypeLegal(WideVecVT))
19204 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19205 DAG.getUNDEF(WideVecVT),
19207 // At this point all of the data is stored at the bottom of the
19208 // register. We now need to save it to mem.
19210 // Find the largest store unit
19211 MVT StoreType = MVT::i8;
19212 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19213 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19214 MVT Tp = (MVT::SimpleValueType)tp;
19215 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19219 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19220 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19221 (64 <= NumElems * ToSz))
19222 StoreType = MVT::f64;
19224 // Bitcast the original vector into a vector of store-size units
19225 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19226 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19227 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19228 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19229 SmallVector<SDValue, 8> Chains;
19230 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19231 TLI.getPointerTy());
19232 SDValue Ptr = St->getBasePtr();
19234 // Perform one or more big stores into memory.
19235 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19236 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19237 StoreType, ShuffWide,
19238 DAG.getIntPtrConstant(i));
19239 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19240 St->getPointerInfo(), St->isVolatile(),
19241 St->isNonTemporal(), St->getAlignment());
19242 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19243 Chains.push_back(Ch);
19246 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19249 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19250 // the FP state in cases where an emms may be missing.
19251 // A preferable solution to the general problem is to figure out the right
19252 // places to insert EMMS. This qualifies as a quick hack.
19254 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19255 if (VT.getSizeInBits() != 64)
19258 const Function *F = DAG.getMachineFunction().getFunction();
19259 bool NoImplicitFloatOps = F->getAttributes().
19260 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19261 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19262 && Subtarget->hasSSE2();
19263 if ((VT.isVector() ||
19264 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19265 isa<LoadSDNode>(St->getValue()) &&
19266 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19267 St->getChain().hasOneUse() && !St->isVolatile()) {
19268 SDNode* LdVal = St->getValue().getNode();
19269 LoadSDNode *Ld = nullptr;
19270 int TokenFactorIndex = -1;
19271 SmallVector<SDValue, 8> Ops;
19272 SDNode* ChainVal = St->getChain().getNode();
19273 // Must be a store of a load. We currently handle two cases: the load
19274 // is a direct child, and it's under an intervening TokenFactor. It is
19275 // possible to dig deeper under nested TokenFactors.
19276 if (ChainVal == LdVal)
19277 Ld = cast<LoadSDNode>(St->getChain());
19278 else if (St->getValue().hasOneUse() &&
19279 ChainVal->getOpcode() == ISD::TokenFactor) {
19280 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19281 if (ChainVal->getOperand(i).getNode() == LdVal) {
19282 TokenFactorIndex = i;
19283 Ld = cast<LoadSDNode>(St->getValue());
19285 Ops.push_back(ChainVal->getOperand(i));
19289 if (!Ld || !ISD::isNormalLoad(Ld))
19292 // If this is not the MMX case, i.e. we are just turning i64 load/store
19293 // into f64 load/store, avoid the transformation if there are multiple
19294 // uses of the loaded value.
19295 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19300 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19301 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19303 if (Subtarget->is64Bit() || F64IsLegal) {
19304 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19305 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19306 Ld->getPointerInfo(), Ld->isVolatile(),
19307 Ld->isNonTemporal(), Ld->isInvariant(),
19308 Ld->getAlignment());
19309 SDValue NewChain = NewLd.getValue(1);
19310 if (TokenFactorIndex != -1) {
19311 Ops.push_back(NewChain);
19312 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19314 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19315 St->getPointerInfo(),
19316 St->isVolatile(), St->isNonTemporal(),
19317 St->getAlignment());
19320 // Otherwise, lower to two pairs of 32-bit loads / stores.
19321 SDValue LoAddr = Ld->getBasePtr();
19322 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19323 DAG.getConstant(4, MVT::i32));
19325 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19326 Ld->getPointerInfo(),
19327 Ld->isVolatile(), Ld->isNonTemporal(),
19328 Ld->isInvariant(), Ld->getAlignment());
19329 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19330 Ld->getPointerInfo().getWithOffset(4),
19331 Ld->isVolatile(), Ld->isNonTemporal(),
19333 MinAlign(Ld->getAlignment(), 4));
19335 SDValue NewChain = LoLd.getValue(1);
19336 if (TokenFactorIndex != -1) {
19337 Ops.push_back(LoLd);
19338 Ops.push_back(HiLd);
19339 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19342 LoAddr = St->getBasePtr();
19343 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19344 DAG.getConstant(4, MVT::i32));
19346 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19347 St->getPointerInfo(),
19348 St->isVolatile(), St->isNonTemporal(),
19349 St->getAlignment());
19350 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19351 St->getPointerInfo().getWithOffset(4),
19353 St->isNonTemporal(),
19354 MinAlign(St->getAlignment(), 4));
19355 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19360 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19361 /// and return the operands for the horizontal operation in LHS and RHS. A
19362 /// horizontal operation performs the binary operation on successive elements
19363 /// of its first operand, then on successive elements of its second operand,
19364 /// returning the resulting values in a vector. For example, if
19365 /// A = < float a0, float a1, float a2, float a3 >
19367 /// B = < float b0, float b1, float b2, float b3 >
19368 /// then the result of doing a horizontal operation on A and B is
19369 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19370 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19371 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19372 /// set to A, RHS to B, and the routine returns 'true'.
19373 /// Note that the binary operation should have the property that if one of the
19374 /// operands is UNDEF then the result is UNDEF.
19375 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19376 // Look for the following pattern: if
19377 // A = < float a0, float a1, float a2, float a3 >
19378 // B = < float b0, float b1, float b2, float b3 >
19380 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19381 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19382 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19383 // which is A horizontal-op B.
19385 // At least one of the operands should be a vector shuffle.
19386 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19387 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19390 MVT VT = LHS.getSimpleValueType();
19392 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19393 "Unsupported vector type for horizontal add/sub");
19395 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19396 // operate independently on 128-bit lanes.
19397 unsigned NumElts = VT.getVectorNumElements();
19398 unsigned NumLanes = VT.getSizeInBits()/128;
19399 unsigned NumLaneElts = NumElts / NumLanes;
19400 assert((NumLaneElts % 2 == 0) &&
19401 "Vector type should have an even number of elements in each lane");
19402 unsigned HalfLaneElts = NumLaneElts/2;
19404 // View LHS in the form
19405 // LHS = VECTOR_SHUFFLE A, B, LMask
19406 // If LHS is not a shuffle then pretend it is the shuffle
19407 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19408 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19411 SmallVector<int, 16> LMask(NumElts);
19412 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19413 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19414 A = LHS.getOperand(0);
19415 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19416 B = LHS.getOperand(1);
19417 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19418 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19420 if (LHS.getOpcode() != ISD::UNDEF)
19422 for (unsigned i = 0; i != NumElts; ++i)
19426 // Likewise, view RHS in the form
19427 // RHS = VECTOR_SHUFFLE C, D, RMask
19429 SmallVector<int, 16> RMask(NumElts);
19430 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19431 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19432 C = RHS.getOperand(0);
19433 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19434 D = RHS.getOperand(1);
19435 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19436 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19438 if (RHS.getOpcode() != ISD::UNDEF)
19440 for (unsigned i = 0; i != NumElts; ++i)
19444 // Check that the shuffles are both shuffling the same vectors.
19445 if (!(A == C && B == D) && !(A == D && B == C))
19448 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19449 if (!A.getNode() && !B.getNode())
19452 // If A and B occur in reverse order in RHS, then "swap" them (which means
19453 // rewriting the mask).
19455 CommuteVectorShuffleMask(RMask, NumElts);
19457 // At this point LHS and RHS are equivalent to
19458 // LHS = VECTOR_SHUFFLE A, B, LMask
19459 // RHS = VECTOR_SHUFFLE A, B, RMask
19460 // Check that the masks correspond to performing a horizontal operation.
19461 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19462 for (unsigned i = 0; i != NumLaneElts; ++i) {
19463 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19465 // Ignore any UNDEF components.
19466 if (LIdx < 0 || RIdx < 0 ||
19467 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19468 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19471 // Check that successive elements are being operated on. If not, this is
19472 // not a horizontal operation.
19473 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19474 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19475 if (!(LIdx == Index && RIdx == Index + 1) &&
19476 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19481 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19482 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19486 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19487 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19488 const X86Subtarget *Subtarget) {
19489 EVT VT = N->getValueType(0);
19490 SDValue LHS = N->getOperand(0);
19491 SDValue RHS = N->getOperand(1);
19493 // Try to synthesize horizontal adds from adds of shuffles.
19494 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19495 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19496 isHorizontalBinOp(LHS, RHS, true))
19497 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19501 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19502 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19503 const X86Subtarget *Subtarget) {
19504 EVT VT = N->getValueType(0);
19505 SDValue LHS = N->getOperand(0);
19506 SDValue RHS = N->getOperand(1);
19508 // Try to synthesize horizontal subs from subs of shuffles.
19509 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19510 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19511 isHorizontalBinOp(LHS, RHS, false))
19512 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19516 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19517 /// X86ISD::FXOR nodes.
19518 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19519 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19520 // F[X]OR(0.0, x) -> x
19521 // F[X]OR(x, 0.0) -> x
19522 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19523 if (C->getValueAPF().isPosZero())
19524 return N->getOperand(1);
19525 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19526 if (C->getValueAPF().isPosZero())
19527 return N->getOperand(0);
19531 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19532 /// X86ISD::FMAX nodes.
19533 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19534 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19536 // Only perform optimizations if UnsafeMath is used.
19537 if (!DAG.getTarget().Options.UnsafeFPMath)
19540 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19541 // into FMINC and FMAXC, which are Commutative operations.
19542 unsigned NewOp = 0;
19543 switch (N->getOpcode()) {
19544 default: llvm_unreachable("unknown opcode");
19545 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19546 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19549 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19550 N->getOperand(0), N->getOperand(1));
19553 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19554 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19555 // FAND(0.0, x) -> 0.0
19556 // FAND(x, 0.0) -> 0.0
19557 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19558 if (C->getValueAPF().isPosZero())
19559 return N->getOperand(0);
19560 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19561 if (C->getValueAPF().isPosZero())
19562 return N->getOperand(1);
19566 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19567 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19568 // FANDN(x, 0.0) -> 0.0
19569 // FANDN(0.0, x) -> x
19570 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19571 if (C->getValueAPF().isPosZero())
19572 return N->getOperand(1);
19573 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19574 if (C->getValueAPF().isPosZero())
19575 return N->getOperand(1);
19579 static SDValue PerformBTCombine(SDNode *N,
19581 TargetLowering::DAGCombinerInfo &DCI) {
19582 // BT ignores high bits in the bit index operand.
19583 SDValue Op1 = N->getOperand(1);
19584 if (Op1.hasOneUse()) {
19585 unsigned BitWidth = Op1.getValueSizeInBits();
19586 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19587 APInt KnownZero, KnownOne;
19588 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19589 !DCI.isBeforeLegalizeOps());
19590 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19591 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19592 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19593 DCI.CommitTargetLoweringOpt(TLO);
19598 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19599 SDValue Op = N->getOperand(0);
19600 if (Op.getOpcode() == ISD::BITCAST)
19601 Op = Op.getOperand(0);
19602 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19603 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19604 VT.getVectorElementType().getSizeInBits() ==
19605 OpVT.getVectorElementType().getSizeInBits()) {
19606 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19611 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19612 const X86Subtarget *Subtarget) {
19613 EVT VT = N->getValueType(0);
19614 if (!VT.isVector())
19617 SDValue N0 = N->getOperand(0);
19618 SDValue N1 = N->getOperand(1);
19619 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19622 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19623 // both SSE and AVX2 since there is no sign-extended shift right
19624 // operation on a vector with 64-bit elements.
19625 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19626 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19627 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19628 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19629 SDValue N00 = N0.getOperand(0);
19631 // EXTLOAD has a better solution on AVX2,
19632 // it may be replaced with X86ISD::VSEXT node.
19633 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19634 if (!ISD::isNormalLoad(N00.getNode()))
19637 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19638 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19640 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19646 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19647 TargetLowering::DAGCombinerInfo &DCI,
19648 const X86Subtarget *Subtarget) {
19649 if (!DCI.isBeforeLegalizeOps())
19652 if (!Subtarget->hasFp256())
19655 EVT VT = N->getValueType(0);
19656 if (VT.isVector() && VT.getSizeInBits() == 256) {
19657 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19665 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19666 const X86Subtarget* Subtarget) {
19668 EVT VT = N->getValueType(0);
19670 // Let legalize expand this if it isn't a legal type yet.
19671 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19674 EVT ScalarVT = VT.getScalarType();
19675 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19676 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19679 SDValue A = N->getOperand(0);
19680 SDValue B = N->getOperand(1);
19681 SDValue C = N->getOperand(2);
19683 bool NegA = (A.getOpcode() == ISD::FNEG);
19684 bool NegB = (B.getOpcode() == ISD::FNEG);
19685 bool NegC = (C.getOpcode() == ISD::FNEG);
19687 // Negative multiplication when NegA xor NegB
19688 bool NegMul = (NegA != NegB);
19690 A = A.getOperand(0);
19692 B = B.getOperand(0);
19694 C = C.getOperand(0);
19698 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19700 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19702 return DAG.getNode(Opcode, dl, VT, A, B, C);
19705 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19706 TargetLowering::DAGCombinerInfo &DCI,
19707 const X86Subtarget *Subtarget) {
19708 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19709 // (and (i32 x86isd::setcc_carry), 1)
19710 // This eliminates the zext. This transformation is necessary because
19711 // ISD::SETCC is always legalized to i8.
19713 SDValue N0 = N->getOperand(0);
19714 EVT VT = N->getValueType(0);
19716 if (N0.getOpcode() == ISD::AND &&
19718 N0.getOperand(0).hasOneUse()) {
19719 SDValue N00 = N0.getOperand(0);
19720 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19721 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19722 if (!C || C->getZExtValue() != 1)
19724 return DAG.getNode(ISD::AND, dl, VT,
19725 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19726 N00.getOperand(0), N00.getOperand(1)),
19727 DAG.getConstant(1, VT));
19731 if (N0.getOpcode() == ISD::TRUNCATE &&
19733 N0.getOperand(0).hasOneUse()) {
19734 SDValue N00 = N0.getOperand(0);
19735 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19736 return DAG.getNode(ISD::AND, dl, VT,
19737 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19738 N00.getOperand(0), N00.getOperand(1)),
19739 DAG.getConstant(1, VT));
19742 if (VT.is256BitVector()) {
19743 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19751 // Optimize x == -y --> x+y == 0
19752 // x != -y --> x+y != 0
19753 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19754 const X86Subtarget* Subtarget) {
19755 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19756 SDValue LHS = N->getOperand(0);
19757 SDValue RHS = N->getOperand(1);
19758 EVT VT = N->getValueType(0);
19761 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19762 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19763 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19764 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19765 LHS.getValueType(), RHS, LHS.getOperand(1));
19766 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19767 addV, DAG.getConstant(0, addV.getValueType()), CC);
19769 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19770 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19771 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19772 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19773 RHS.getValueType(), LHS, RHS.getOperand(1));
19774 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19775 addV, DAG.getConstant(0, addV.getValueType()), CC);
19778 if (VT.getScalarType() == MVT::i1) {
19779 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19780 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19781 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19782 if (!IsSEXT0 && !IsVZero0)
19784 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19785 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19786 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19788 if (!IsSEXT1 && !IsVZero1)
19791 if (IsSEXT0 && IsVZero1) {
19792 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19793 if (CC == ISD::SETEQ)
19794 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19795 return LHS.getOperand(0);
19797 if (IsSEXT1 && IsVZero0) {
19798 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19799 if (CC == ISD::SETEQ)
19800 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19801 return RHS.getOperand(0);
19808 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19809 // as "sbb reg,reg", since it can be extended without zext and produces
19810 // an all-ones bit which is more useful than 0/1 in some cases.
19811 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19814 return DAG.getNode(ISD::AND, DL, VT,
19815 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19816 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19817 DAG.getConstant(1, VT));
19818 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19819 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19820 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19821 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19824 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19825 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19826 TargetLowering::DAGCombinerInfo &DCI,
19827 const X86Subtarget *Subtarget) {
19829 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19830 SDValue EFLAGS = N->getOperand(1);
19832 if (CC == X86::COND_A) {
19833 // Try to convert COND_A into COND_B in an attempt to facilitate
19834 // materializing "setb reg".
19836 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19837 // cannot take an immediate as its first operand.
19839 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19840 EFLAGS.getValueType().isInteger() &&
19841 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19842 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19843 EFLAGS.getNode()->getVTList(),
19844 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19845 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19846 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19850 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19851 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19853 if (CC == X86::COND_B)
19854 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19858 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19859 if (Flags.getNode()) {
19860 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19861 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19867 // Optimize branch condition evaluation.
19869 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19870 TargetLowering::DAGCombinerInfo &DCI,
19871 const X86Subtarget *Subtarget) {
19873 SDValue Chain = N->getOperand(0);
19874 SDValue Dest = N->getOperand(1);
19875 SDValue EFLAGS = N->getOperand(3);
19876 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19880 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19881 if (Flags.getNode()) {
19882 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19883 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19890 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19891 const X86TargetLowering *XTLI) {
19892 SDValue Op0 = N->getOperand(0);
19893 EVT InVT = Op0->getValueType(0);
19895 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19896 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19898 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19899 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19900 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19903 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19904 // a 32-bit target where SSE doesn't support i64->FP operations.
19905 if (Op0.getOpcode() == ISD::LOAD) {
19906 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19907 EVT VT = Ld->getValueType(0);
19908 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19909 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19910 !XTLI->getSubtarget()->is64Bit() &&
19912 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19913 Ld->getChain(), Op0, DAG);
19914 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19921 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19922 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19923 X86TargetLowering::DAGCombinerInfo &DCI) {
19924 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19925 // the result is either zero or one (depending on the input carry bit).
19926 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19927 if (X86::isZeroNode(N->getOperand(0)) &&
19928 X86::isZeroNode(N->getOperand(1)) &&
19929 // We don't have a good way to replace an EFLAGS use, so only do this when
19931 SDValue(N, 1).use_empty()) {
19933 EVT VT = N->getValueType(0);
19934 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19935 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19936 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19937 DAG.getConstant(X86::COND_B,MVT::i8),
19939 DAG.getConstant(1, VT));
19940 return DCI.CombineTo(N, Res1, CarryOut);
19946 // fold (add Y, (sete X, 0)) -> adc 0, Y
19947 // (add Y, (setne X, 0)) -> sbb -1, Y
19948 // (sub (sete X, 0), Y) -> sbb 0, Y
19949 // (sub (setne X, 0), Y) -> adc -1, Y
19950 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19953 // Look through ZExts.
19954 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19955 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19958 SDValue SetCC = Ext.getOperand(0);
19959 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19962 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19963 if (CC != X86::COND_E && CC != X86::COND_NE)
19966 SDValue Cmp = SetCC.getOperand(1);
19967 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19968 !X86::isZeroNode(Cmp.getOperand(1)) ||
19969 !Cmp.getOperand(0).getValueType().isInteger())
19972 SDValue CmpOp0 = Cmp.getOperand(0);
19973 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19974 DAG.getConstant(1, CmpOp0.getValueType()));
19976 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19977 if (CC == X86::COND_NE)
19978 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19979 DL, OtherVal.getValueType(), OtherVal,
19980 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19981 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19982 DL, OtherVal.getValueType(), OtherVal,
19983 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19986 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19987 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19988 const X86Subtarget *Subtarget) {
19989 EVT VT = N->getValueType(0);
19990 SDValue Op0 = N->getOperand(0);
19991 SDValue Op1 = N->getOperand(1);
19993 // Try to synthesize horizontal adds from adds of shuffles.
19994 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19995 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19996 isHorizontalBinOp(Op0, Op1, true))
19997 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19999 return OptimizeConditionalInDecrement(N, DAG);
20002 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20003 const X86Subtarget *Subtarget) {
20004 SDValue Op0 = N->getOperand(0);
20005 SDValue Op1 = N->getOperand(1);
20007 // X86 can't encode an immediate LHS of a sub. See if we can push the
20008 // negation into a preceding instruction.
20009 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20010 // If the RHS of the sub is a XOR with one use and a constant, invert the
20011 // immediate. Then add one to the LHS of the sub so we can turn
20012 // X-Y -> X+~Y+1, saving one register.
20013 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20014 isa<ConstantSDNode>(Op1.getOperand(1))) {
20015 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20016 EVT VT = Op0.getValueType();
20017 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20019 DAG.getConstant(~XorC, VT));
20020 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20021 DAG.getConstant(C->getAPIntValue()+1, VT));
20025 // Try to synthesize horizontal adds from adds of shuffles.
20026 EVT VT = N->getValueType(0);
20027 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20028 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20029 isHorizontalBinOp(Op0, Op1, true))
20030 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20032 return OptimizeConditionalInDecrement(N, DAG);
20035 /// performVZEXTCombine - Performs build vector combines
20036 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20037 TargetLowering::DAGCombinerInfo &DCI,
20038 const X86Subtarget *Subtarget) {
20039 // (vzext (bitcast (vzext (x)) -> (vzext x)
20040 SDValue In = N->getOperand(0);
20041 while (In.getOpcode() == ISD::BITCAST)
20042 In = In.getOperand(0);
20044 if (In.getOpcode() != X86ISD::VZEXT)
20047 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20051 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20052 DAGCombinerInfo &DCI) const {
20053 SelectionDAG &DAG = DCI.DAG;
20054 switch (N->getOpcode()) {
20056 case ISD::EXTRACT_VECTOR_ELT:
20057 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20059 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20060 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20061 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20062 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20063 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20064 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20067 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20068 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20069 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20070 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20071 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20072 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20073 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20074 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20075 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20077 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20079 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20080 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20081 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20082 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20083 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20084 case ISD::ANY_EXTEND:
20085 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20086 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20087 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20088 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20089 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20090 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20091 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20092 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20093 case X86ISD::SHUFP: // Handle all target specific shuffles
20094 case X86ISD::PALIGNR:
20095 case X86ISD::UNPCKH:
20096 case X86ISD::UNPCKL:
20097 case X86ISD::MOVHLPS:
20098 case X86ISD::MOVLHPS:
20099 case X86ISD::PSHUFD:
20100 case X86ISD::PSHUFHW:
20101 case X86ISD::PSHUFLW:
20102 case X86ISD::MOVSS:
20103 case X86ISD::MOVSD:
20104 case X86ISD::VPERMILP:
20105 case X86ISD::VPERM2X128:
20106 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20107 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20113 /// isTypeDesirableForOp - Return true if the target has native support for
20114 /// the specified value type and it is 'desirable' to use the type for the
20115 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20116 /// instruction encodings are longer and some i16 instructions are slow.
20117 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20118 if (!isTypeLegal(VT))
20120 if (VT != MVT::i16)
20127 case ISD::SIGN_EXTEND:
20128 case ISD::ZERO_EXTEND:
20129 case ISD::ANY_EXTEND:
20142 /// IsDesirableToPromoteOp - This method query the target whether it is
20143 /// beneficial for dag combiner to promote the specified node. If true, it
20144 /// should return the desired promotion type by reference.
20145 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20146 EVT VT = Op.getValueType();
20147 if (VT != MVT::i16)
20150 bool Promote = false;
20151 bool Commute = false;
20152 switch (Op.getOpcode()) {
20155 LoadSDNode *LD = cast<LoadSDNode>(Op);
20156 // If the non-extending load has a single use and it's not live out, then it
20157 // might be folded.
20158 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20159 Op.hasOneUse()*/) {
20160 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20161 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20162 // The only case where we'd want to promote LOAD (rather then it being
20163 // promoted as an operand is when it's only use is liveout.
20164 if (UI->getOpcode() != ISD::CopyToReg)
20171 case ISD::SIGN_EXTEND:
20172 case ISD::ZERO_EXTEND:
20173 case ISD::ANY_EXTEND:
20178 SDValue N0 = Op.getOperand(0);
20179 // Look out for (store (shl (load), x)).
20180 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20193 SDValue N0 = Op.getOperand(0);
20194 SDValue N1 = Op.getOperand(1);
20195 if (!Commute && MayFoldLoad(N1))
20197 // Avoid disabling potential load folding opportunities.
20198 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20200 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20210 //===----------------------------------------------------------------------===//
20211 // X86 Inline Assembly Support
20212 //===----------------------------------------------------------------------===//
20215 // Helper to match a string separated by whitespace.
20216 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20217 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20219 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20220 StringRef piece(*args[i]);
20221 if (!s.startswith(piece)) // Check if the piece matches.
20224 s = s.substr(piece.size());
20225 StringRef::size_type pos = s.find_first_not_of(" \t");
20226 if (pos == 0) // We matched a prefix.
20234 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20237 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20239 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20240 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20241 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20242 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20244 if (AsmPieces.size() == 3)
20246 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20253 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20254 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20256 std::string AsmStr = IA->getAsmString();
20258 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20259 if (!Ty || Ty->getBitWidth() % 16 != 0)
20262 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20263 SmallVector<StringRef, 4> AsmPieces;
20264 SplitString(AsmStr, AsmPieces, ";\n");
20266 switch (AsmPieces.size()) {
20267 default: return false;
20269 // FIXME: this should verify that we are targeting a 486 or better. If not,
20270 // we will turn this bswap into something that will be lowered to logical
20271 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20272 // lower so don't worry about this.
20274 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20275 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20276 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20277 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20278 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20279 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20280 // No need to check constraints, nothing other than the equivalent of
20281 // "=r,0" would be valid here.
20282 return IntrinsicLowering::LowerToByteSwap(CI);
20285 // rorw $$8, ${0:w} --> llvm.bswap.i16
20286 if (CI->getType()->isIntegerTy(16) &&
20287 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20288 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20289 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20291 const std::string &ConstraintsStr = IA->getConstraintString();
20292 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20293 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20294 if (clobbersFlagRegisters(AsmPieces))
20295 return IntrinsicLowering::LowerToByteSwap(CI);
20299 if (CI->getType()->isIntegerTy(32) &&
20300 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20301 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20302 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20303 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20305 const std::string &ConstraintsStr = IA->getConstraintString();
20306 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20307 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20308 if (clobbersFlagRegisters(AsmPieces))
20309 return IntrinsicLowering::LowerToByteSwap(CI);
20312 if (CI->getType()->isIntegerTy(64)) {
20313 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20314 if (Constraints.size() >= 2 &&
20315 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20316 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20317 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20318 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20319 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20320 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20321 return IntrinsicLowering::LowerToByteSwap(CI);
20329 /// getConstraintType - Given a constraint letter, return the type of
20330 /// constraint it is for this target.
20331 X86TargetLowering::ConstraintType
20332 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20333 if (Constraint.size() == 1) {
20334 switch (Constraint[0]) {
20345 return C_RegisterClass;
20369 return TargetLowering::getConstraintType(Constraint);
20372 /// Examine constraint type and operand type and determine a weight value.
20373 /// This object must already have been set up with the operand type
20374 /// and the current alternative constraint selected.
20375 TargetLowering::ConstraintWeight
20376 X86TargetLowering::getSingleConstraintMatchWeight(
20377 AsmOperandInfo &info, const char *constraint) const {
20378 ConstraintWeight weight = CW_Invalid;
20379 Value *CallOperandVal = info.CallOperandVal;
20380 // If we don't have a value, we can't do a match,
20381 // but allow it at the lowest weight.
20382 if (!CallOperandVal)
20384 Type *type = CallOperandVal->getType();
20385 // Look at the constraint type.
20386 switch (*constraint) {
20388 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20399 if (CallOperandVal->getType()->isIntegerTy())
20400 weight = CW_SpecificReg;
20405 if (type->isFloatingPointTy())
20406 weight = CW_SpecificReg;
20409 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20410 weight = CW_SpecificReg;
20414 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20415 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20416 weight = CW_Register;
20419 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20420 if (C->getZExtValue() <= 31)
20421 weight = CW_Constant;
20425 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20426 if (C->getZExtValue() <= 63)
20427 weight = CW_Constant;
20431 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20432 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20433 weight = CW_Constant;
20437 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20438 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20439 weight = CW_Constant;
20443 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20444 if (C->getZExtValue() <= 3)
20445 weight = CW_Constant;
20449 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20450 if (C->getZExtValue() <= 0xff)
20451 weight = CW_Constant;
20456 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20457 weight = CW_Constant;
20461 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20462 if ((C->getSExtValue() >= -0x80000000LL) &&
20463 (C->getSExtValue() <= 0x7fffffffLL))
20464 weight = CW_Constant;
20468 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20469 if (C->getZExtValue() <= 0xffffffff)
20470 weight = CW_Constant;
20477 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20478 /// with another that has more specific requirements based on the type of the
20479 /// corresponding operand.
20480 const char *X86TargetLowering::
20481 LowerXConstraint(EVT ConstraintVT) const {
20482 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20483 // 'f' like normal targets.
20484 if (ConstraintVT.isFloatingPoint()) {
20485 if (Subtarget->hasSSE2())
20487 if (Subtarget->hasSSE1())
20491 return TargetLowering::LowerXConstraint(ConstraintVT);
20494 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20495 /// vector. If it is invalid, don't add anything to Ops.
20496 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20497 std::string &Constraint,
20498 std::vector<SDValue>&Ops,
20499 SelectionDAG &DAG) const {
20502 // Only support length 1 constraints for now.
20503 if (Constraint.length() > 1) return;
20505 char ConstraintLetter = Constraint[0];
20506 switch (ConstraintLetter) {
20509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20510 if (C->getZExtValue() <= 31) {
20511 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20517 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20518 if (C->getZExtValue() <= 63) {
20519 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20526 if (isInt<8>(C->getSExtValue())) {
20527 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20533 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20534 if (C->getZExtValue() <= 255) {
20535 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20541 // 32-bit signed value
20542 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20543 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20544 C->getSExtValue())) {
20545 // Widen to 64 bits here to get it sign extended.
20546 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20549 // FIXME gcc accepts some relocatable values here too, but only in certain
20550 // memory models; it's complicated.
20555 // 32-bit unsigned value
20556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20557 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20558 C->getZExtValue())) {
20559 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20563 // FIXME gcc accepts some relocatable values here too, but only in certain
20564 // memory models; it's complicated.
20568 // Literal immediates are always ok.
20569 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20570 // Widen to 64 bits here to get it sign extended.
20571 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20575 // In any sort of PIC mode addresses need to be computed at runtime by
20576 // adding in a register or some sort of table lookup. These can't
20577 // be used as immediates.
20578 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20581 // If we are in non-pic codegen mode, we allow the address of a global (with
20582 // an optional displacement) to be used with 'i'.
20583 GlobalAddressSDNode *GA = nullptr;
20584 int64_t Offset = 0;
20586 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20588 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20589 Offset += GA->getOffset();
20591 } else if (Op.getOpcode() == ISD::ADD) {
20592 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20593 Offset += C->getZExtValue();
20594 Op = Op.getOperand(0);
20597 } else if (Op.getOpcode() == ISD::SUB) {
20598 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20599 Offset += -C->getZExtValue();
20600 Op = Op.getOperand(0);
20605 // Otherwise, this isn't something we can handle, reject it.
20609 const GlobalValue *GV = GA->getGlobal();
20610 // If we require an extra load to get this address, as in PIC mode, we
20611 // can't accept it.
20612 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20613 getTargetMachine())))
20616 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20617 GA->getValueType(0), Offset);
20622 if (Result.getNode()) {
20623 Ops.push_back(Result);
20626 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20629 std::pair<unsigned, const TargetRegisterClass*>
20630 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20632 // First, see if this is a constraint that directly corresponds to an LLVM
20634 if (Constraint.size() == 1) {
20635 // GCC Constraint Letters
20636 switch (Constraint[0]) {
20638 // TODO: Slight differences here in allocation order and leaving
20639 // RIP in the class. Do they matter any more here than they do
20640 // in the normal allocation?
20641 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20642 if (Subtarget->is64Bit()) {
20643 if (VT == MVT::i32 || VT == MVT::f32)
20644 return std::make_pair(0U, &X86::GR32RegClass);
20645 if (VT == MVT::i16)
20646 return std::make_pair(0U, &X86::GR16RegClass);
20647 if (VT == MVT::i8 || VT == MVT::i1)
20648 return std::make_pair(0U, &X86::GR8RegClass);
20649 if (VT == MVT::i64 || VT == MVT::f64)
20650 return std::make_pair(0U, &X86::GR64RegClass);
20653 // 32-bit fallthrough
20654 case 'Q': // Q_REGS
20655 if (VT == MVT::i32 || VT == MVT::f32)
20656 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20657 if (VT == MVT::i16)
20658 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20659 if (VT == MVT::i8 || VT == MVT::i1)
20660 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20661 if (VT == MVT::i64)
20662 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20664 case 'r': // GENERAL_REGS
20665 case 'l': // INDEX_REGS
20666 if (VT == MVT::i8 || VT == MVT::i1)
20667 return std::make_pair(0U, &X86::GR8RegClass);
20668 if (VT == MVT::i16)
20669 return std::make_pair(0U, &X86::GR16RegClass);
20670 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20671 return std::make_pair(0U, &X86::GR32RegClass);
20672 return std::make_pair(0U, &X86::GR64RegClass);
20673 case 'R': // LEGACY_REGS
20674 if (VT == MVT::i8 || VT == MVT::i1)
20675 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20676 if (VT == MVT::i16)
20677 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20678 if (VT == MVT::i32 || !Subtarget->is64Bit())
20679 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20680 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20681 case 'f': // FP Stack registers.
20682 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20683 // value to the correct fpstack register class.
20684 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20685 return std::make_pair(0U, &X86::RFP32RegClass);
20686 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20687 return std::make_pair(0U, &X86::RFP64RegClass);
20688 return std::make_pair(0U, &X86::RFP80RegClass);
20689 case 'y': // MMX_REGS if MMX allowed.
20690 if (!Subtarget->hasMMX()) break;
20691 return std::make_pair(0U, &X86::VR64RegClass);
20692 case 'Y': // SSE_REGS if SSE2 allowed
20693 if (!Subtarget->hasSSE2()) break;
20695 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20696 if (!Subtarget->hasSSE1()) break;
20698 switch (VT.SimpleTy) {
20700 // Scalar SSE types.
20703 return std::make_pair(0U, &X86::FR32RegClass);
20706 return std::make_pair(0U, &X86::FR64RegClass);
20714 return std::make_pair(0U, &X86::VR128RegClass);
20722 return std::make_pair(0U, &X86::VR256RegClass);
20727 return std::make_pair(0U, &X86::VR512RegClass);
20733 // Use the default implementation in TargetLowering to convert the register
20734 // constraint into a member of a register class.
20735 std::pair<unsigned, const TargetRegisterClass*> Res;
20736 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20738 // Not found as a standard register?
20740 // Map st(0) -> st(7) -> ST0
20741 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20742 tolower(Constraint[1]) == 's' &&
20743 tolower(Constraint[2]) == 't' &&
20744 Constraint[3] == '(' &&
20745 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20746 Constraint[5] == ')' &&
20747 Constraint[6] == '}') {
20749 Res.first = X86::ST0+Constraint[4]-'0';
20750 Res.second = &X86::RFP80RegClass;
20754 // GCC allows "st(0)" to be called just plain "st".
20755 if (StringRef("{st}").equals_lower(Constraint)) {
20756 Res.first = X86::ST0;
20757 Res.second = &X86::RFP80RegClass;
20762 if (StringRef("{flags}").equals_lower(Constraint)) {
20763 Res.first = X86::EFLAGS;
20764 Res.second = &X86::CCRRegClass;
20768 // 'A' means EAX + EDX.
20769 if (Constraint == "A") {
20770 Res.first = X86::EAX;
20771 Res.second = &X86::GR32_ADRegClass;
20777 // Otherwise, check to see if this is a register class of the wrong value
20778 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20779 // turn into {ax},{dx}.
20780 if (Res.second->hasType(VT))
20781 return Res; // Correct type already, nothing to do.
20783 // All of the single-register GCC register classes map their values onto
20784 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20785 // really want an 8-bit or 32-bit register, map to the appropriate register
20786 // class and return the appropriate register.
20787 if (Res.second == &X86::GR16RegClass) {
20788 if (VT == MVT::i8 || VT == MVT::i1) {
20789 unsigned DestReg = 0;
20790 switch (Res.first) {
20792 case X86::AX: DestReg = X86::AL; break;
20793 case X86::DX: DestReg = X86::DL; break;
20794 case X86::CX: DestReg = X86::CL; break;
20795 case X86::BX: DestReg = X86::BL; break;
20798 Res.first = DestReg;
20799 Res.second = &X86::GR8RegClass;
20801 } else if (VT == MVT::i32 || VT == MVT::f32) {
20802 unsigned DestReg = 0;
20803 switch (Res.first) {
20805 case X86::AX: DestReg = X86::EAX; break;
20806 case X86::DX: DestReg = X86::EDX; break;
20807 case X86::CX: DestReg = X86::ECX; break;
20808 case X86::BX: DestReg = X86::EBX; break;
20809 case X86::SI: DestReg = X86::ESI; break;
20810 case X86::DI: DestReg = X86::EDI; break;
20811 case X86::BP: DestReg = X86::EBP; break;
20812 case X86::SP: DestReg = X86::ESP; break;
20815 Res.first = DestReg;
20816 Res.second = &X86::GR32RegClass;
20818 } else if (VT == MVT::i64 || VT == MVT::f64) {
20819 unsigned DestReg = 0;
20820 switch (Res.first) {
20822 case X86::AX: DestReg = X86::RAX; break;
20823 case X86::DX: DestReg = X86::RDX; break;
20824 case X86::CX: DestReg = X86::RCX; break;
20825 case X86::BX: DestReg = X86::RBX; break;
20826 case X86::SI: DestReg = X86::RSI; break;
20827 case X86::DI: DestReg = X86::RDI; break;
20828 case X86::BP: DestReg = X86::RBP; break;
20829 case X86::SP: DestReg = X86::RSP; break;
20832 Res.first = DestReg;
20833 Res.second = &X86::GR64RegClass;
20836 } else if (Res.second == &X86::FR32RegClass ||
20837 Res.second == &X86::FR64RegClass ||
20838 Res.second == &X86::VR128RegClass ||
20839 Res.second == &X86::VR256RegClass ||
20840 Res.second == &X86::FR32XRegClass ||
20841 Res.second == &X86::FR64XRegClass ||
20842 Res.second == &X86::VR128XRegClass ||
20843 Res.second == &X86::VR256XRegClass ||
20844 Res.second == &X86::VR512RegClass) {
20845 // Handle references to XMM physical registers that got mapped into the
20846 // wrong class. This can happen with constraints like {xmm0} where the
20847 // target independent register mapper will just pick the first match it can
20848 // find, ignoring the required type.
20850 if (VT == MVT::f32 || VT == MVT::i32)
20851 Res.second = &X86::FR32RegClass;
20852 else if (VT == MVT::f64 || VT == MVT::i64)
20853 Res.second = &X86::FR64RegClass;
20854 else if (X86::VR128RegClass.hasType(VT))
20855 Res.second = &X86::VR128RegClass;
20856 else if (X86::VR256RegClass.hasType(VT))
20857 Res.second = &X86::VR256RegClass;
20858 else if (X86::VR512RegClass.hasType(VT))
20859 Res.second = &X86::VR512RegClass;
20865 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20867 // Scaling factors are not free at all.
20868 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20869 // will take 2 allocations in the out of order engine instead of 1
20870 // for plain addressing mode, i.e. inst (reg1).
20872 // vaddps (%rsi,%drx), %ymm0, %ymm1
20873 // Requires two allocations (one for the load, one for the computation)
20875 // vaddps (%rsi), %ymm0, %ymm1
20876 // Requires just 1 allocation, i.e., freeing allocations for other operations
20877 // and having less micro operations to execute.
20879 // For some X86 architectures, this is even worse because for instance for
20880 // stores, the complex addressing mode forces the instruction to use the
20881 // "load" ports instead of the dedicated "store" port.
20882 // E.g., on Haswell:
20883 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
20884 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
20885 if (isLegalAddressingMode(AM, Ty))
20886 // Scale represents reg2 * scale, thus account for 1
20887 // as soon as we use a second register.
20888 return AM.Scale != 0;