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 makeArrayRef(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 makeArrayRef(&V[0], NumElems/2));
6144 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6145 makeArrayRef(&V[NumElems / 2], NumElems/2));
6147 // Recreate the wider vector with the lower and upper part.
6148 if (VT.is256BitVector())
6149 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6150 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6153 // Let legalizer expand 2-wide build_vectors.
6154 if (EVTBits == 64) {
6155 if (NumNonZero == 1) {
6156 // One half is zero or undef.
6157 unsigned Idx = countTrailingZeros(NonZeros);
6158 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6159 Op.getOperand(Idx));
6160 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6165 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6166 if (EVTBits == 8 && NumElems == 16) {
6167 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6169 if (V.getNode()) return V;
6172 if (EVTBits == 16 && NumElems == 8) {
6173 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6175 if (V.getNode()) return V;
6178 // If element VT is == 32 bits, turn it into a number of shuffles.
6179 SmallVector<SDValue, 8> V(NumElems);
6180 if (NumElems == 4 && NumZero > 0) {
6181 for (unsigned i = 0; i < 4; ++i) {
6182 bool isZero = !(NonZeros & (1 << i));
6184 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6186 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6189 for (unsigned i = 0; i < 2; ++i) {
6190 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6193 V[i] = V[i*2]; // Must be a zero vector.
6196 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6199 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6202 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6207 bool Reverse1 = (NonZeros & 0x3) == 2;
6208 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6212 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6213 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6215 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6218 if (Values.size() > 1 && VT.is128BitVector()) {
6219 // Check for a build vector of consecutive loads.
6220 for (unsigned i = 0; i < NumElems; ++i)
6221 V[i] = Op.getOperand(i);
6223 // Check for elements which are consecutive loads.
6224 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6228 // Check for a build vector from mostly shuffle plus few inserting.
6229 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6233 // For SSE 4.1, use insertps to put the high elements into the low element.
6234 if (getSubtarget()->hasSSE41()) {
6236 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6237 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6239 Result = DAG.getUNDEF(VT);
6241 for (unsigned i = 1; i < NumElems; ++i) {
6242 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6243 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6244 Op.getOperand(i), DAG.getIntPtrConstant(i));
6249 // Otherwise, expand into a number of unpckl*, start by extending each of
6250 // our (non-undef) elements to the full vector width with the element in the
6251 // bottom slot of the vector (which generates no code for SSE).
6252 for (unsigned i = 0; i < NumElems; ++i) {
6253 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6254 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6256 V[i] = DAG.getUNDEF(VT);
6259 // Next, we iteratively mix elements, e.g. for v4f32:
6260 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6261 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6262 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6263 unsigned EltStride = NumElems >> 1;
6264 while (EltStride != 0) {
6265 for (unsigned i = 0; i < EltStride; ++i) {
6266 // If V[i+EltStride] is undef and this is the first round of mixing,
6267 // then it is safe to just drop this shuffle: V[i] is already in the
6268 // right place, the one element (since it's the first round) being
6269 // inserted as undef can be dropped. This isn't safe for successive
6270 // rounds because they will permute elements within both vectors.
6271 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6272 EltStride == NumElems/2)
6275 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6284 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6285 // to create 256-bit vectors from two other 128-bit ones.
6286 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6288 MVT ResVT = Op.getSimpleValueType();
6290 assert((ResVT.is256BitVector() ||
6291 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6293 SDValue V1 = Op.getOperand(0);
6294 SDValue V2 = Op.getOperand(1);
6295 unsigned NumElems = ResVT.getVectorNumElements();
6296 if(ResVT.is256BitVector())
6297 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6299 if (Op.getNumOperands() == 4) {
6300 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6301 ResVT.getVectorNumElements()/2);
6302 SDValue V3 = Op.getOperand(2);
6303 SDValue V4 = Op.getOperand(3);
6304 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6305 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6307 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6310 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6311 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6312 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6313 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6314 Op.getNumOperands() == 4)));
6316 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6317 // from two other 128-bit ones.
6319 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6320 return LowerAVXCONCAT_VECTORS(Op, DAG);
6323 // Try to lower a shuffle node into a simple blend instruction.
6325 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6326 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6327 SDValue V1 = SVOp->getOperand(0);
6328 SDValue V2 = SVOp->getOperand(1);
6330 MVT VT = SVOp->getSimpleValueType(0);
6331 MVT EltVT = VT.getVectorElementType();
6332 unsigned NumElems = VT.getVectorNumElements();
6334 // There is no blend with immediate in AVX-512.
6335 if (VT.is512BitVector())
6338 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6340 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6343 // Check the mask for BLEND and build the value.
6344 unsigned MaskValue = 0;
6345 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6346 unsigned NumLanes = (NumElems-1)/8 + 1;
6347 unsigned NumElemsInLane = NumElems / NumLanes;
6349 // Blend for v16i16 should be symetric for the both lanes.
6350 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6352 int SndLaneEltIdx = (NumLanes == 2) ?
6353 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6354 int EltIdx = SVOp->getMaskElt(i);
6356 if ((EltIdx < 0 || EltIdx == (int)i) &&
6357 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6360 if (((unsigned)EltIdx == (i + NumElems)) &&
6361 (SndLaneEltIdx < 0 ||
6362 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6363 MaskValue |= (1<<i);
6368 // Convert i32 vectors to floating point if it is not AVX2.
6369 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6371 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6372 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6374 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6375 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6378 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6379 DAG.getConstant(MaskValue, MVT::i32));
6380 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6383 /// In vector type \p VT, return true if the element at index \p InputIdx
6384 /// falls on a different 128-bit lane than \p OutputIdx.
6385 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6386 unsigned OutputIdx) {
6387 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6388 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6391 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6392 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6393 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6394 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6396 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6397 SelectionDAG &DAG) {
6398 MVT VT = V1.getSimpleValueType();
6399 assert(VT.is128BitVector() || VT.is256BitVector());
6401 MVT EltVT = VT.getVectorElementType();
6402 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6403 unsigned NumElts = VT.getVectorNumElements();
6405 SmallVector<SDValue, 32> PshufbMask;
6406 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6407 int InputIdx = MaskVals[OutputIdx];
6408 unsigned InputByteIdx;
6410 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6411 InputByteIdx = 0x80;
6413 // Cross lane is not allowed.
6414 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6416 InputByteIdx = InputIdx * EltSizeInBytes;
6417 // Index is an byte offset within the 128-bit lane.
6418 InputByteIdx &= 0xf;
6421 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6422 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6423 if (InputByteIdx != 0x80)
6428 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6430 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6431 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6432 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6435 // v8i16 shuffles - Prefer shuffles in the following order:
6436 // 1. [all] pshuflw, pshufhw, optional move
6437 // 2. [ssse3] 1 x pshufb
6438 // 3. [ssse3] 2 x pshufb + 1 x por
6439 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6441 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6442 SelectionDAG &DAG) {
6443 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6444 SDValue V1 = SVOp->getOperand(0);
6445 SDValue V2 = SVOp->getOperand(1);
6447 SmallVector<int, 8> MaskVals;
6449 // Determine if more than 1 of the words in each of the low and high quadwords
6450 // of the result come from the same quadword of one of the two inputs. Undef
6451 // mask values count as coming from any quadword, for better codegen.
6453 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6454 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6455 unsigned LoQuad[] = { 0, 0, 0, 0 };
6456 unsigned HiQuad[] = { 0, 0, 0, 0 };
6457 // Indices of quads used.
6458 std::bitset<4> InputQuads;
6459 for (unsigned i = 0; i < 8; ++i) {
6460 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6461 int EltIdx = SVOp->getMaskElt(i);
6462 MaskVals.push_back(EltIdx);
6471 InputQuads.set(EltIdx / 4);
6474 int BestLoQuad = -1;
6475 unsigned MaxQuad = 1;
6476 for (unsigned i = 0; i < 4; ++i) {
6477 if (LoQuad[i] > MaxQuad) {
6479 MaxQuad = LoQuad[i];
6483 int BestHiQuad = -1;
6485 for (unsigned i = 0; i < 4; ++i) {
6486 if (HiQuad[i] > MaxQuad) {
6488 MaxQuad = HiQuad[i];
6492 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6493 // of the two input vectors, shuffle them into one input vector so only a
6494 // single pshufb instruction is necessary. If there are more than 2 input
6495 // quads, disable the next transformation since it does not help SSSE3.
6496 bool V1Used = InputQuads[0] || InputQuads[1];
6497 bool V2Used = InputQuads[2] || InputQuads[3];
6498 if (Subtarget->hasSSSE3()) {
6499 if (InputQuads.count() == 2 && V1Used && V2Used) {
6500 BestLoQuad = InputQuads[0] ? 0 : 1;
6501 BestHiQuad = InputQuads[2] ? 2 : 3;
6503 if (InputQuads.count() > 2) {
6509 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6510 // the shuffle mask. If a quad is scored as -1, that means that it contains
6511 // words from all 4 input quadwords.
6513 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6515 BestLoQuad < 0 ? 0 : BestLoQuad,
6516 BestHiQuad < 0 ? 1 : BestHiQuad
6518 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6519 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6520 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6521 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6523 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6524 // source words for the shuffle, to aid later transformations.
6525 bool AllWordsInNewV = true;
6526 bool InOrder[2] = { true, true };
6527 for (unsigned i = 0; i != 8; ++i) {
6528 int idx = MaskVals[i];
6530 InOrder[i/4] = false;
6531 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6533 AllWordsInNewV = false;
6537 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6538 if (AllWordsInNewV) {
6539 for (int i = 0; i != 8; ++i) {
6540 int idx = MaskVals[i];
6543 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6544 if ((idx != i) && idx < 4)
6546 if ((idx != i) && idx > 3)
6555 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6556 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6557 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6558 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6559 unsigned TargetMask = 0;
6560 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6561 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6562 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6563 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6564 getShufflePSHUFLWImmediate(SVOp);
6565 V1 = NewV.getOperand(0);
6566 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6570 // Promote splats to a larger type which usually leads to more efficient code.
6571 // FIXME: Is this true if pshufb is available?
6572 if (SVOp->isSplat())
6573 return PromoteSplat(SVOp, DAG);
6575 // If we have SSSE3, and all words of the result are from 1 input vector,
6576 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6577 // is present, fall back to case 4.
6578 if (Subtarget->hasSSSE3()) {
6579 SmallVector<SDValue,16> pshufbMask;
6581 // If we have elements from both input vectors, set the high bit of the
6582 // shuffle mask element to zero out elements that come from V2 in the V1
6583 // mask, and elements that come from V1 in the V2 mask, so that the two
6584 // results can be OR'd together.
6585 bool TwoInputs = V1Used && V2Used;
6586 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6588 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6590 // Calculate the shuffle mask for the second input, shuffle it, and
6591 // OR it with the first shuffled input.
6592 CommuteVectorShuffleMask(MaskVals, 8);
6593 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6594 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6595 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6598 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6599 // and update MaskVals with new element order.
6600 std::bitset<8> InOrder;
6601 if (BestLoQuad >= 0) {
6602 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6603 for (int i = 0; i != 4; ++i) {
6604 int idx = MaskVals[i];
6607 } else if ((idx / 4) == BestLoQuad) {
6612 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6615 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6616 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6617 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6619 getShufflePSHUFLWImmediate(SVOp), DAG);
6623 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6624 // and update MaskVals with the new element order.
6625 if (BestHiQuad >= 0) {
6626 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6627 for (unsigned i = 4; i != 8; ++i) {
6628 int idx = MaskVals[i];
6631 } else if ((idx / 4) == BestHiQuad) {
6632 MaskV[i] = (idx & 3) + 4;
6636 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6639 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6640 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6641 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6643 getShufflePSHUFHWImmediate(SVOp), DAG);
6647 // In case BestHi & BestLo were both -1, which means each quadword has a word
6648 // from each of the four input quadwords, calculate the InOrder bitvector now
6649 // before falling through to the insert/extract cleanup.
6650 if (BestLoQuad == -1 && BestHiQuad == -1) {
6652 for (int i = 0; i != 8; ++i)
6653 if (MaskVals[i] < 0 || MaskVals[i] == i)
6657 // The other elements are put in the right place using pextrw and pinsrw.
6658 for (unsigned i = 0; i != 8; ++i) {
6661 int EltIdx = MaskVals[i];
6664 SDValue ExtOp = (EltIdx < 8) ?
6665 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6666 DAG.getIntPtrConstant(EltIdx)) :
6667 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6668 DAG.getIntPtrConstant(EltIdx - 8));
6669 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6670 DAG.getIntPtrConstant(i));
6675 /// \brief v16i16 shuffles
6677 /// FIXME: We only support generation of a single pshufb currently. We can
6678 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6679 /// well (e.g 2 x pshufb + 1 x por).
6681 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6682 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6683 SDValue V1 = SVOp->getOperand(0);
6684 SDValue V2 = SVOp->getOperand(1);
6687 if (V2.getOpcode() != ISD::UNDEF)
6690 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6691 return getPSHUFB(MaskVals, V1, dl, DAG);
6694 // v16i8 shuffles - Prefer shuffles in the following order:
6695 // 1. [ssse3] 1 x pshufb
6696 // 2. [ssse3] 2 x pshufb + 1 x por
6697 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6698 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6699 const X86Subtarget* Subtarget,
6700 SelectionDAG &DAG) {
6701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6702 SDValue V1 = SVOp->getOperand(0);
6703 SDValue V2 = SVOp->getOperand(1);
6705 ArrayRef<int> MaskVals = SVOp->getMask();
6707 // Promote splats to a larger type which usually leads to more efficient code.
6708 // FIXME: Is this true if pshufb is available?
6709 if (SVOp->isSplat())
6710 return PromoteSplat(SVOp, DAG);
6712 // If we have SSSE3, case 1 is generated when all result bytes come from
6713 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6714 // present, fall back to case 3.
6716 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6717 if (Subtarget->hasSSSE3()) {
6718 SmallVector<SDValue,16> pshufbMask;
6720 // If all result elements are from one input vector, then only translate
6721 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6723 // Otherwise, we have elements from both input vectors, and must zero out
6724 // elements that come from V2 in the first mask, and V1 in the second mask
6725 // so that we can OR them together.
6726 for (unsigned i = 0; i != 16; ++i) {
6727 int EltIdx = MaskVals[i];
6728 if (EltIdx < 0 || EltIdx >= 16)
6730 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6732 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6733 DAG.getNode(ISD::BUILD_VECTOR, dl,
6734 MVT::v16i8, pshufbMask));
6736 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6737 // the 2nd operand if it's undefined or zero.
6738 if (V2.getOpcode() == ISD::UNDEF ||
6739 ISD::isBuildVectorAllZeros(V2.getNode()))
6742 // Calculate the shuffle mask for the second input, shuffle it, and
6743 // OR it with the first shuffled input.
6745 for (unsigned i = 0; i != 16; ++i) {
6746 int EltIdx = MaskVals[i];
6747 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6748 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6750 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6751 DAG.getNode(ISD::BUILD_VECTOR, dl,
6752 MVT::v16i8, pshufbMask));
6753 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6756 // No SSSE3 - Calculate in place words and then fix all out of place words
6757 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6758 // the 16 different words that comprise the two doublequadword input vectors.
6759 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6760 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6762 for (int i = 0; i != 8; ++i) {
6763 int Elt0 = MaskVals[i*2];
6764 int Elt1 = MaskVals[i*2+1];
6766 // This word of the result is all undef, skip it.
6767 if (Elt0 < 0 && Elt1 < 0)
6770 // This word of the result is already in the correct place, skip it.
6771 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6774 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6775 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6778 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6779 // using a single extract together, load it and store it.
6780 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6781 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6782 DAG.getIntPtrConstant(Elt1 / 2));
6783 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6784 DAG.getIntPtrConstant(i));
6788 // If Elt1 is defined, extract it from the appropriate source. If the
6789 // source byte is not also odd, shift the extracted word left 8 bits
6790 // otherwise clear the bottom 8 bits if we need to do an or.
6792 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6793 DAG.getIntPtrConstant(Elt1 / 2));
6794 if ((Elt1 & 1) == 0)
6795 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6797 TLI.getShiftAmountTy(InsElt.getValueType())));
6799 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6800 DAG.getConstant(0xFF00, MVT::i16));
6802 // If Elt0 is defined, extract it from the appropriate source. If the
6803 // source byte is not also even, shift the extracted word right 8 bits. If
6804 // Elt1 was also defined, OR the extracted values together before
6805 // inserting them in the result.
6807 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6808 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6809 if ((Elt0 & 1) != 0)
6810 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6812 TLI.getShiftAmountTy(InsElt0.getValueType())));
6814 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6815 DAG.getConstant(0x00FF, MVT::i16));
6816 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6819 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6820 DAG.getIntPtrConstant(i));
6822 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6825 // v32i8 shuffles - Translate to VPSHUFB if possible.
6827 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6828 const X86Subtarget *Subtarget,
6829 SelectionDAG &DAG) {
6830 MVT VT = SVOp->getSimpleValueType(0);
6831 SDValue V1 = SVOp->getOperand(0);
6832 SDValue V2 = SVOp->getOperand(1);
6834 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6836 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6837 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6838 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6840 // VPSHUFB may be generated if
6841 // (1) one of input vector is undefined or zeroinitializer.
6842 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6843 // And (2) the mask indexes don't cross the 128-bit lane.
6844 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6845 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6848 if (V1IsAllZero && !V2IsAllZero) {
6849 CommuteVectorShuffleMask(MaskVals, 32);
6852 return getPSHUFB(MaskVals, V1, dl, DAG);
6855 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6856 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6857 /// done when every pair / quad of shuffle mask elements point to elements in
6858 /// the right sequence. e.g.
6859 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6861 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6862 SelectionDAG &DAG) {
6863 MVT VT = SVOp->getSimpleValueType(0);
6865 unsigned NumElems = VT.getVectorNumElements();
6868 switch (VT.SimpleTy) {
6869 default: llvm_unreachable("Unexpected!");
6870 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6871 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6872 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6873 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6874 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6875 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6878 SmallVector<int, 8> MaskVec;
6879 for (unsigned i = 0; i != NumElems; i += Scale) {
6881 for (unsigned j = 0; j != Scale; ++j) {
6882 int EltIdx = SVOp->getMaskElt(i+j);
6886 StartIdx = (EltIdx / Scale);
6887 if (EltIdx != (int)(StartIdx*Scale + j))
6890 MaskVec.push_back(StartIdx);
6893 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6894 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6895 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6898 /// getVZextMovL - Return a zero-extending vector move low node.
6900 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6901 SDValue SrcOp, SelectionDAG &DAG,
6902 const X86Subtarget *Subtarget, SDLoc dl) {
6903 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6904 LoadSDNode *LD = nullptr;
6905 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6906 LD = dyn_cast<LoadSDNode>(SrcOp);
6908 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6910 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6911 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6912 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6913 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6914 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6916 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6917 return DAG.getNode(ISD::BITCAST, dl, VT,
6918 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6919 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6927 return DAG.getNode(ISD::BITCAST, dl, VT,
6928 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6929 DAG.getNode(ISD::BITCAST, dl,
6933 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6934 /// which could not be matched by any known target speficic shuffle
6936 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6938 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6939 if (NewOp.getNode())
6942 MVT VT = SVOp->getSimpleValueType(0);
6944 unsigned NumElems = VT.getVectorNumElements();
6945 unsigned NumLaneElems = NumElems / 2;
6948 MVT EltVT = VT.getVectorElementType();
6949 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6952 SmallVector<int, 16> Mask;
6953 for (unsigned l = 0; l < 2; ++l) {
6954 // Build a shuffle mask for the output, discovering on the fly which
6955 // input vectors to use as shuffle operands (recorded in InputUsed).
6956 // If building a suitable shuffle vector proves too hard, then bail
6957 // out with UseBuildVector set.
6958 bool UseBuildVector = false;
6959 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6960 unsigned LaneStart = l * NumLaneElems;
6961 for (unsigned i = 0; i != NumLaneElems; ++i) {
6962 // The mask element. This indexes into the input.
6963 int Idx = SVOp->getMaskElt(i+LaneStart);
6965 // the mask element does not index into any input vector.
6970 // The input vector this mask element indexes into.
6971 int Input = Idx / NumLaneElems;
6973 // Turn the index into an offset from the start of the input vector.
6974 Idx -= Input * NumLaneElems;
6976 // Find or create a shuffle vector operand to hold this input.
6978 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6979 if (InputUsed[OpNo] == Input)
6980 // This input vector is already an operand.
6982 if (InputUsed[OpNo] < 0) {
6983 // Create a new operand for this input vector.
6984 InputUsed[OpNo] = Input;
6989 if (OpNo >= array_lengthof(InputUsed)) {
6990 // More than two input vectors used! Give up on trying to create a
6991 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6992 UseBuildVector = true;
6996 // Add the mask index for the new shuffle vector.
6997 Mask.push_back(Idx + OpNo * NumLaneElems);
7000 if (UseBuildVector) {
7001 SmallVector<SDValue, 16> SVOps;
7002 for (unsigned i = 0; i != NumLaneElems; ++i) {
7003 // The mask element. This indexes into the input.
7004 int Idx = SVOp->getMaskElt(i+LaneStart);
7006 SVOps.push_back(DAG.getUNDEF(EltVT));
7010 // The input vector this mask element indexes into.
7011 int Input = Idx / NumElems;
7013 // Turn the index into an offset from the start of the input vector.
7014 Idx -= Input * NumElems;
7016 // Extract the vector element by hand.
7017 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7018 SVOp->getOperand(Input),
7019 DAG.getIntPtrConstant(Idx)));
7022 // Construct the output using a BUILD_VECTOR.
7023 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7024 } else if (InputUsed[0] < 0) {
7025 // No input vectors were used! The result is undefined.
7026 Output[l] = DAG.getUNDEF(NVT);
7028 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7029 (InputUsed[0] % 2) * NumLaneElems,
7031 // If only one input was used, use an undefined vector for the other.
7032 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7033 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7034 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7035 // At least one input vector was used. Create a new shuffle vector.
7036 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7042 // Concatenate the result back
7043 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7046 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7047 /// 4 elements, and match them with several different shuffle types.
7049 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7050 SDValue V1 = SVOp->getOperand(0);
7051 SDValue V2 = SVOp->getOperand(1);
7053 MVT VT = SVOp->getSimpleValueType(0);
7055 assert(VT.is128BitVector() && "Unsupported vector size");
7057 std::pair<int, int> Locs[4];
7058 int Mask1[] = { -1, -1, -1, -1 };
7059 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7063 for (unsigned i = 0; i != 4; ++i) {
7064 int Idx = PermMask[i];
7066 Locs[i] = std::make_pair(-1, -1);
7068 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7070 Locs[i] = std::make_pair(0, NumLo);
7074 Locs[i] = std::make_pair(1, NumHi);
7076 Mask1[2+NumHi] = Idx;
7082 if (NumLo <= 2 && NumHi <= 2) {
7083 // If no more than two elements come from either vector. This can be
7084 // implemented with two shuffles. First shuffle gather the elements.
7085 // The second shuffle, which takes the first shuffle as both of its
7086 // vector operands, put the elements into the right order.
7087 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7089 int Mask2[] = { -1, -1, -1, -1 };
7091 for (unsigned i = 0; i != 4; ++i)
7092 if (Locs[i].first != -1) {
7093 unsigned Idx = (i < 2) ? 0 : 4;
7094 Idx += Locs[i].first * 2 + Locs[i].second;
7098 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7101 if (NumLo == 3 || NumHi == 3) {
7102 // Otherwise, we must have three elements from one vector, call it X, and
7103 // one element from the other, call it Y. First, use a shufps to build an
7104 // intermediate vector with the one element from Y and the element from X
7105 // that will be in the same half in the final destination (the indexes don't
7106 // matter). Then, use a shufps to build the final vector, taking the half
7107 // containing the element from Y from the intermediate, and the other half
7110 // Normalize it so the 3 elements come from V1.
7111 CommuteVectorShuffleMask(PermMask, 4);
7115 // Find the element from V2.
7117 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7118 int Val = PermMask[HiIndex];
7125 Mask1[0] = PermMask[HiIndex];
7127 Mask1[2] = PermMask[HiIndex^1];
7129 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7132 Mask1[0] = PermMask[0];
7133 Mask1[1] = PermMask[1];
7134 Mask1[2] = HiIndex & 1 ? 6 : 4;
7135 Mask1[3] = HiIndex & 1 ? 4 : 6;
7136 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7139 Mask1[0] = HiIndex & 1 ? 2 : 0;
7140 Mask1[1] = HiIndex & 1 ? 0 : 2;
7141 Mask1[2] = PermMask[2];
7142 Mask1[3] = PermMask[3];
7147 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7150 // Break it into (shuffle shuffle_hi, shuffle_lo).
7151 int LoMask[] = { -1, -1, -1, -1 };
7152 int HiMask[] = { -1, -1, -1, -1 };
7154 int *MaskPtr = LoMask;
7155 unsigned MaskIdx = 0;
7158 for (unsigned i = 0; i != 4; ++i) {
7165 int Idx = PermMask[i];
7167 Locs[i] = std::make_pair(-1, -1);
7168 } else if (Idx < 4) {
7169 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7170 MaskPtr[LoIdx] = Idx;
7173 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7174 MaskPtr[HiIdx] = Idx;
7179 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7180 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7181 int MaskOps[] = { -1, -1, -1, -1 };
7182 for (unsigned i = 0; i != 4; ++i)
7183 if (Locs[i].first != -1)
7184 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7185 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7188 static bool MayFoldVectorLoad(SDValue V) {
7189 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7190 V = V.getOperand(0);
7192 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7193 V = V.getOperand(0);
7194 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7195 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7196 // BUILD_VECTOR (load), undef
7197 V = V.getOperand(0);
7199 return MayFoldLoad(V);
7203 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7204 MVT VT = Op.getSimpleValueType();
7206 // Canonizalize to v2f64.
7207 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7208 return DAG.getNode(ISD::BITCAST, dl, VT,
7209 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7214 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7216 SDValue V1 = Op.getOperand(0);
7217 SDValue V2 = Op.getOperand(1);
7218 MVT VT = Op.getSimpleValueType();
7220 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7222 if (HasSSE2 && VT == MVT::v2f64)
7223 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7225 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7226 return DAG.getNode(ISD::BITCAST, dl, VT,
7227 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7228 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7229 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7233 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7234 SDValue V1 = Op.getOperand(0);
7235 SDValue V2 = Op.getOperand(1);
7236 MVT VT = Op.getSimpleValueType();
7238 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7239 "unsupported shuffle type");
7241 if (V2.getOpcode() == ISD::UNDEF)
7245 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7249 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7250 SDValue V1 = Op.getOperand(0);
7251 SDValue V2 = Op.getOperand(1);
7252 MVT VT = Op.getSimpleValueType();
7253 unsigned NumElems = VT.getVectorNumElements();
7255 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7256 // operand of these instructions is only memory, so check if there's a
7257 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7259 bool CanFoldLoad = false;
7261 // Trivial case, when V2 comes from a load.
7262 if (MayFoldVectorLoad(V2))
7265 // When V1 is a load, it can be folded later into a store in isel, example:
7266 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7268 // (MOVLPSmr addr:$src1, VR128:$src2)
7269 // So, recognize this potential and also use MOVLPS or MOVLPD
7270 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7273 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7275 if (HasSSE2 && NumElems == 2)
7276 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7279 // If we don't care about the second element, proceed to use movss.
7280 if (SVOp->getMaskElt(1) != -1)
7281 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7284 // movl and movlp will both match v2i64, but v2i64 is never matched by
7285 // movl earlier because we make it strict to avoid messing with the movlp load
7286 // folding logic (see the code above getMOVLP call). Match it here then,
7287 // this is horrible, but will stay like this until we move all shuffle
7288 // matching to x86 specific nodes. Note that for the 1st condition all
7289 // types are matched with movsd.
7291 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7292 // as to remove this logic from here, as much as possible
7293 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7294 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7295 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7298 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7300 // Invert the operand order and use SHUFPS to match it.
7301 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7302 getShuffleSHUFImmediate(SVOp), DAG);
7305 // It is only safe to call this function if isINSERTPSMask is true for
7306 // this shufflevector mask.
7307 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7308 SelectionDAG &DAG) {
7309 // Generate an insertps instruction when inserting an f32 from memory onto a
7310 // v4f32 or when copying a member from one v4f32 to another.
7311 // We also use it for transferring i32 from one register to another,
7312 // since it simply copies the same bits.
7313 // If we're transfering an i32 from memory to a specific element in a
7314 // register, we output a generic DAG that will match the PINSRD
7316 // TODO: Optimize for AVX cases too (VINSERTPS)
7317 MVT VT = SVOp->getSimpleValueType(0);
7318 MVT EVT = VT.getVectorElementType();
7319 SDValue V1 = SVOp->getOperand(0);
7320 SDValue V2 = SVOp->getOperand(1);
7321 auto Mask = SVOp->getMask();
7322 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7323 "unsupported vector type for insertps/pinsrd");
7325 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7326 [](const int &i) { return i < 4; });
7334 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7335 [](const int &i) { return i < 4; }) -
7340 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7341 [](const int &i) { return i >= 4; }) -
7345 if (MayFoldLoad(From)) {
7346 // Trivial case, when From comes from a load and is only used by the
7347 // shuffle. Make it use insertps from the vector that we need from that
7349 SDValue Addr = From.getOperand(1);
7351 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7352 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7353 Addr.getSimpleValueType()));
7355 LoadSDNode *Load = cast<LoadSDNode>(From);
7357 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7358 DAG.getMachineFunction().getMachineMemOperand(
7359 Load->getMemOperand(), 0, EVT.getStoreSize()));
7361 if (EVT == MVT::f32) {
7362 // Create this as a scalar to vector to match the instruction pattern.
7363 SDValue LoadScalarToVector =
7364 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7365 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7366 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7368 } else { // EVT == MVT::i32
7369 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7370 // instruction, to match the PINSRD instruction, which loads an i32 to a
7371 // certain vector element.
7372 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7373 DAG.getConstant(DestIndex, MVT::i32));
7377 // Vector-element-to-vector
7378 unsigned SrcIndex = Mask[DestIndex] % 4;
7379 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7380 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7383 // Reduce a vector shuffle to zext.
7384 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7385 SelectionDAG &DAG) {
7386 // PMOVZX is only available from SSE41.
7387 if (!Subtarget->hasSSE41())
7390 MVT VT = Op.getSimpleValueType();
7392 // Only AVX2 support 256-bit vector integer extending.
7393 if (!Subtarget->hasInt256() && VT.is256BitVector())
7396 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7398 SDValue V1 = Op.getOperand(0);
7399 SDValue V2 = Op.getOperand(1);
7400 unsigned NumElems = VT.getVectorNumElements();
7402 // Extending is an unary operation and the element type of the source vector
7403 // won't be equal to or larger than i64.
7404 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7405 VT.getVectorElementType() == MVT::i64)
7408 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7409 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7410 while ((1U << Shift) < NumElems) {
7411 if (SVOp->getMaskElt(1U << Shift) == 1)
7414 // The maximal ratio is 8, i.e. from i8 to i64.
7419 // Check the shuffle mask.
7420 unsigned Mask = (1U << Shift) - 1;
7421 for (unsigned i = 0; i != NumElems; ++i) {
7422 int EltIdx = SVOp->getMaskElt(i);
7423 if ((i & Mask) != 0 && EltIdx != -1)
7425 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7429 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7430 MVT NeVT = MVT::getIntegerVT(NBits);
7431 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7433 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7436 // Simplify the operand as it's prepared to be fed into shuffle.
7437 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7438 if (V1.getOpcode() == ISD::BITCAST &&
7439 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7440 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7441 V1.getOperand(0).getOperand(0)
7442 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7443 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7444 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7445 ConstantSDNode *CIdx =
7446 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7447 // If it's foldable, i.e. normal load with single use, we will let code
7448 // selection to fold it. Otherwise, we will short the conversion sequence.
7449 if (CIdx && CIdx->getZExtValue() == 0 &&
7450 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7451 MVT FullVT = V.getSimpleValueType();
7452 MVT V1VT = V1.getSimpleValueType();
7453 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7454 // The "ext_vec_elt" node is wider than the result node.
7455 // In this case we should extract subvector from V.
7456 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7457 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7458 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7459 FullVT.getVectorNumElements()/Ratio);
7460 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7461 DAG.getIntPtrConstant(0));
7463 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7467 return DAG.getNode(ISD::BITCAST, DL, VT,
7468 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7472 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7473 SelectionDAG &DAG) {
7474 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7475 MVT VT = Op.getSimpleValueType();
7477 SDValue V1 = Op.getOperand(0);
7478 SDValue V2 = Op.getOperand(1);
7480 if (isZeroShuffle(SVOp))
7481 return getZeroVector(VT, Subtarget, DAG, dl);
7483 // Handle splat operations
7484 if (SVOp->isSplat()) {
7485 // Use vbroadcast whenever the splat comes from a foldable load
7486 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7487 if (Broadcast.getNode())
7491 // Check integer expanding shuffles.
7492 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7493 if (NewOp.getNode())
7496 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7498 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7499 VT == MVT::v16i16 || VT == MVT::v32i8) {
7500 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7501 if (NewOp.getNode())
7502 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7503 } else if ((VT == MVT::v4i32 ||
7504 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7505 // FIXME: Figure out a cleaner way to do this.
7506 // Try to make use of movq to zero out the top part.
7507 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7508 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7509 if (NewOp.getNode()) {
7510 MVT NewVT = NewOp.getSimpleValueType();
7511 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7512 NewVT, true, false))
7513 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7514 DAG, Subtarget, dl);
7516 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7517 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7518 if (NewOp.getNode()) {
7519 MVT NewVT = NewOp.getSimpleValueType();
7520 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7521 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7522 DAG, Subtarget, dl);
7530 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7531 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7532 SDValue V1 = Op.getOperand(0);
7533 SDValue V2 = Op.getOperand(1);
7534 MVT VT = Op.getSimpleValueType();
7536 unsigned NumElems = VT.getVectorNumElements();
7537 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7538 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7539 bool V1IsSplat = false;
7540 bool V2IsSplat = false;
7541 bool HasSSE2 = Subtarget->hasSSE2();
7542 bool HasFp256 = Subtarget->hasFp256();
7543 bool HasInt256 = Subtarget->hasInt256();
7544 MachineFunction &MF = DAG.getMachineFunction();
7545 bool OptForSize = MF.getFunction()->getAttributes().
7546 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7548 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7550 if (V1IsUndef && V2IsUndef)
7551 return DAG.getUNDEF(VT);
7553 // When we create a shuffle node we put the UNDEF node to second operand,
7554 // but in some cases the first operand may be transformed to UNDEF.
7555 // In this case we should just commute the node.
7557 return CommuteVectorShuffle(SVOp, DAG);
7559 // Vector shuffle lowering takes 3 steps:
7561 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7562 // narrowing and commutation of operands should be handled.
7563 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7565 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7566 // so the shuffle can be broken into other shuffles and the legalizer can
7567 // try the lowering again.
7569 // The general idea is that no vector_shuffle operation should be left to
7570 // be matched during isel, all of them must be converted to a target specific
7573 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7574 // narrowing and commutation of operands should be handled. The actual code
7575 // doesn't include all of those, work in progress...
7576 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7577 if (NewOp.getNode())
7580 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7582 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7583 // unpckh_undef). Only use pshufd if speed is more important than size.
7584 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7585 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7586 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7587 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7589 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7590 V2IsUndef && MayFoldVectorLoad(V1))
7591 return getMOVDDup(Op, dl, V1, DAG);
7593 if (isMOVHLPS_v_undef_Mask(M, VT))
7594 return getMOVHighToLow(Op, dl, DAG);
7596 // Use to match splats
7597 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7598 (VT == MVT::v2f64 || VT == MVT::v2i64))
7599 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7601 if (isPSHUFDMask(M, VT)) {
7602 // The actual implementation will match the mask in the if above and then
7603 // during isel it can match several different instructions, not only pshufd
7604 // as its name says, sad but true, emulate the behavior for now...
7605 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7606 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7608 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7610 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7611 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7613 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7614 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7617 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7621 if (isPALIGNRMask(M, VT, Subtarget))
7622 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7623 getShufflePALIGNRImmediate(SVOp),
7626 // Check if this can be converted into a logical shift.
7627 bool isLeft = false;
7630 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7631 if (isShift && ShVal.hasOneUse()) {
7632 // If the shifted value has multiple uses, it may be cheaper to use
7633 // v_set0 + movlhps or movhlps, etc.
7634 MVT EltVT = VT.getVectorElementType();
7635 ShAmt *= EltVT.getSizeInBits();
7636 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7639 if (isMOVLMask(M, VT)) {
7640 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7641 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7642 if (!isMOVLPMask(M, VT)) {
7643 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7644 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7646 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7647 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7651 // FIXME: fold these into legal mask.
7652 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7653 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7655 if (isMOVHLPSMask(M, VT))
7656 return getMOVHighToLow(Op, dl, DAG);
7658 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7659 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7661 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7662 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7664 if (isMOVLPMask(M, VT))
7665 return getMOVLP(Op, dl, DAG, HasSSE2);
7667 if (ShouldXformToMOVHLPS(M, VT) ||
7668 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7669 return CommuteVectorShuffle(SVOp, DAG);
7672 // No better options. Use a vshldq / vsrldq.
7673 MVT EltVT = VT.getVectorElementType();
7674 ShAmt *= EltVT.getSizeInBits();
7675 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7678 bool Commuted = false;
7679 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7680 // 1,1,1,1 -> v8i16 though.
7681 V1IsSplat = isSplatVector(V1.getNode());
7682 V2IsSplat = isSplatVector(V2.getNode());
7684 // Canonicalize the splat or undef, if present, to be on the RHS.
7685 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7686 CommuteVectorShuffleMask(M, NumElems);
7688 std::swap(V1IsSplat, V2IsSplat);
7692 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7693 // Shuffling low element of v1 into undef, just return v1.
7696 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7697 // the instruction selector will not match, so get a canonical MOVL with
7698 // swapped operands to undo the commute.
7699 return getMOVL(DAG, dl, VT, V2, V1);
7702 if (isUNPCKLMask(M, VT, HasInt256))
7703 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7705 if (isUNPCKHMask(M, VT, HasInt256))
7706 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7709 // Normalize mask so all entries that point to V2 points to its first
7710 // element then try to match unpck{h|l} again. If match, return a
7711 // new vector_shuffle with the corrected mask.p
7712 SmallVector<int, 8> NewMask(M.begin(), M.end());
7713 NormalizeMask(NewMask, NumElems);
7714 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7715 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7716 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7717 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7721 // Commute is back and try unpck* again.
7722 // FIXME: this seems wrong.
7723 CommuteVectorShuffleMask(M, NumElems);
7725 std::swap(V1IsSplat, V2IsSplat);
7727 if (isUNPCKLMask(M, VT, HasInt256))
7728 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7730 if (isUNPCKHMask(M, VT, HasInt256))
7731 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7734 // Normalize the node to match x86 shuffle ops if needed
7735 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7736 return CommuteVectorShuffle(SVOp, DAG);
7738 // The checks below are all present in isShuffleMaskLegal, but they are
7739 // inlined here right now to enable us to directly emit target specific
7740 // nodes, and remove one by one until they don't return Op anymore.
7742 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7743 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7744 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7745 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7748 if (isPSHUFHWMask(M, VT, HasInt256))
7749 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7750 getShufflePSHUFHWImmediate(SVOp),
7753 if (isPSHUFLWMask(M, VT, HasInt256))
7754 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7755 getShufflePSHUFLWImmediate(SVOp),
7758 if (isSHUFPMask(M, VT))
7759 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7760 getShuffleSHUFImmediate(SVOp), DAG);
7762 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7763 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7764 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7765 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7767 //===--------------------------------------------------------------------===//
7768 // Generate target specific nodes for 128 or 256-bit shuffles only
7769 // supported in the AVX instruction set.
7772 // Handle VMOVDDUPY permutations
7773 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7774 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7776 // Handle VPERMILPS/D* permutations
7777 if (isVPERMILPMask(M, VT)) {
7778 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7779 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7780 getShuffleSHUFImmediate(SVOp), DAG);
7781 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7782 getShuffleSHUFImmediate(SVOp), DAG);
7786 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7787 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7788 Idx*(NumElems/2), DAG, dl);
7790 // Handle VPERM2F128/VPERM2I128 permutations
7791 if (isVPERM2X128Mask(M, VT, HasFp256))
7792 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7793 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7795 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7796 if (BlendOp.getNode())
7799 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7800 return getINSERTPS(SVOp, dl, DAG);
7803 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7804 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7806 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7807 VT.is512BitVector()) {
7808 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7809 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7810 SmallVector<SDValue, 16> permclMask;
7811 for (unsigned i = 0; i != NumElems; ++i) {
7812 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7815 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7817 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7818 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7819 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7820 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7821 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7824 //===--------------------------------------------------------------------===//
7825 // Since no target specific shuffle was selected for this generic one,
7826 // lower it into other known shuffles. FIXME: this isn't true yet, but
7827 // this is the plan.
7830 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7831 if (VT == MVT::v8i16) {
7832 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7833 if (NewOp.getNode())
7837 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7838 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7839 if (NewOp.getNode())
7843 if (VT == MVT::v16i8) {
7844 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7845 if (NewOp.getNode())
7849 if (VT == MVT::v32i8) {
7850 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7851 if (NewOp.getNode())
7855 // Handle all 128-bit wide vectors with 4 elements, and match them with
7856 // several different shuffle types.
7857 if (NumElems == 4 && VT.is128BitVector())
7858 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7860 // Handle general 256-bit shuffles
7861 if (VT.is256BitVector())
7862 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7867 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7868 MVT VT = Op.getSimpleValueType();
7871 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7874 if (VT.getSizeInBits() == 8) {
7875 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7876 Op.getOperand(0), Op.getOperand(1));
7877 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7878 DAG.getValueType(VT));
7879 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7882 if (VT.getSizeInBits() == 16) {
7883 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7884 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7886 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7887 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7888 DAG.getNode(ISD::BITCAST, dl,
7892 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7893 Op.getOperand(0), Op.getOperand(1));
7894 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7895 DAG.getValueType(VT));
7896 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7899 if (VT == MVT::f32) {
7900 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7901 // the result back to FR32 register. It's only worth matching if the
7902 // result has a single use which is a store or a bitcast to i32. And in
7903 // the case of a store, it's not worth it if the index is a constant 0,
7904 // because a MOVSSmr can be used instead, which is smaller and faster.
7905 if (!Op.hasOneUse())
7907 SDNode *User = *Op.getNode()->use_begin();
7908 if ((User->getOpcode() != ISD::STORE ||
7909 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7910 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7911 (User->getOpcode() != ISD::BITCAST ||
7912 User->getValueType(0) != MVT::i32))
7914 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7915 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7918 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7921 if (VT == MVT::i32 || VT == MVT::i64) {
7922 // ExtractPS/pextrq works with constant index.
7923 if (isa<ConstantSDNode>(Op.getOperand(1)))
7929 /// Extract one bit from mask vector, like v16i1 or v8i1.
7930 /// AVX-512 feature.
7932 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7933 SDValue Vec = Op.getOperand(0);
7935 MVT VecVT = Vec.getSimpleValueType();
7936 SDValue Idx = Op.getOperand(1);
7937 MVT EltVT = Op.getSimpleValueType();
7939 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7941 // variable index can't be handled in mask registers,
7942 // extend vector to VR512
7943 if (!isa<ConstantSDNode>(Idx)) {
7944 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7945 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7946 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7947 ExtVT.getVectorElementType(), Ext, Idx);
7948 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7951 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7952 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7953 unsigned MaxSift = rc->getSize()*8 - 1;
7954 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7955 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7956 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7957 DAG.getConstant(MaxSift, MVT::i8));
7958 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7959 DAG.getIntPtrConstant(0));
7963 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7964 SelectionDAG &DAG) const {
7966 SDValue Vec = Op.getOperand(0);
7967 MVT VecVT = Vec.getSimpleValueType();
7968 SDValue Idx = Op.getOperand(1);
7970 if (Op.getSimpleValueType() == MVT::i1)
7971 return ExtractBitFromMaskVector(Op, DAG);
7973 if (!isa<ConstantSDNode>(Idx)) {
7974 if (VecVT.is512BitVector() ||
7975 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7976 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7979 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7980 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7981 MaskEltVT.getSizeInBits());
7983 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7984 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7985 getZeroVector(MaskVT, Subtarget, DAG, dl),
7986 Idx, DAG.getConstant(0, getPointerTy()));
7987 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7988 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7989 Perm, DAG.getConstant(0, getPointerTy()));
7994 // If this is a 256-bit vector result, first extract the 128-bit vector and
7995 // then extract the element from the 128-bit vector.
7996 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7998 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7999 // Get the 128-bit vector.
8000 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8001 MVT EltVT = VecVT.getVectorElementType();
8003 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8005 //if (IdxVal >= NumElems/2)
8006 // IdxVal -= NumElems/2;
8007 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8008 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8009 DAG.getConstant(IdxVal, MVT::i32));
8012 assert(VecVT.is128BitVector() && "Unexpected vector length");
8014 if (Subtarget->hasSSE41()) {
8015 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8020 MVT VT = Op.getSimpleValueType();
8021 // TODO: handle v16i8.
8022 if (VT.getSizeInBits() == 16) {
8023 SDValue Vec = Op.getOperand(0);
8024 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8026 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8027 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8028 DAG.getNode(ISD::BITCAST, dl,
8031 // Transform it so it match pextrw which produces a 32-bit result.
8032 MVT EltVT = MVT::i32;
8033 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8034 Op.getOperand(0), Op.getOperand(1));
8035 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8036 DAG.getValueType(VT));
8037 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8040 if (VT.getSizeInBits() == 32) {
8041 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8045 // SHUFPS the element to the lowest double word, then movss.
8046 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8047 MVT VVT = Op.getOperand(0).getSimpleValueType();
8048 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8049 DAG.getUNDEF(VVT), Mask);
8050 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8051 DAG.getIntPtrConstant(0));
8054 if (VT.getSizeInBits() == 64) {
8055 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8056 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8057 // to match extract_elt for f64.
8058 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8062 // UNPCKHPD the element to the lowest double word, then movsd.
8063 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8064 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8065 int Mask[2] = { 1, -1 };
8066 MVT VVT = Op.getOperand(0).getSimpleValueType();
8067 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8068 DAG.getUNDEF(VVT), Mask);
8069 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8070 DAG.getIntPtrConstant(0));
8076 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8077 MVT VT = Op.getSimpleValueType();
8078 MVT EltVT = VT.getVectorElementType();
8081 SDValue N0 = Op.getOperand(0);
8082 SDValue N1 = Op.getOperand(1);
8083 SDValue N2 = Op.getOperand(2);
8085 if (!VT.is128BitVector())
8088 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8089 isa<ConstantSDNode>(N2)) {
8091 if (VT == MVT::v8i16)
8092 Opc = X86ISD::PINSRW;
8093 else if (VT == MVT::v16i8)
8094 Opc = X86ISD::PINSRB;
8096 Opc = X86ISD::PINSRB;
8098 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8100 if (N1.getValueType() != MVT::i32)
8101 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8102 if (N2.getValueType() != MVT::i32)
8103 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8104 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8107 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8108 // Bits [7:6] of the constant are the source select. This will always be
8109 // zero here. The DAG Combiner may combine an extract_elt index into these
8110 // bits. For example (insert (extract, 3), 2) could be matched by putting
8111 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8112 // Bits [5:4] of the constant are the destination select. This is the
8113 // value of the incoming immediate.
8114 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8115 // combine either bitwise AND or insert of float 0.0 to set these bits.
8116 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8117 // Create this as a scalar to vector..
8118 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8119 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8122 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8123 // PINSR* works with constant index.
8129 /// Insert one bit to mask vector, like v16i1 or v8i1.
8130 /// AVX-512 feature.
8132 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8134 SDValue Vec = Op.getOperand(0);
8135 SDValue Elt = Op.getOperand(1);
8136 SDValue Idx = Op.getOperand(2);
8137 MVT VecVT = Vec.getSimpleValueType();
8139 if (!isa<ConstantSDNode>(Idx)) {
8140 // Non constant index. Extend source and destination,
8141 // insert element and then truncate the result.
8142 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8143 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8144 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8145 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8146 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8147 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8150 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8151 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8152 if (Vec.getOpcode() == ISD::UNDEF)
8153 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8154 DAG.getConstant(IdxVal, MVT::i8));
8155 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8156 unsigned MaxSift = rc->getSize()*8 - 1;
8157 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8158 DAG.getConstant(MaxSift, MVT::i8));
8159 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8160 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8161 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8164 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8165 MVT VT = Op.getSimpleValueType();
8166 MVT EltVT = VT.getVectorElementType();
8168 if (EltVT == MVT::i1)
8169 return InsertBitToMaskVector(Op, DAG);
8172 SDValue N0 = Op.getOperand(0);
8173 SDValue N1 = Op.getOperand(1);
8174 SDValue N2 = Op.getOperand(2);
8176 // If this is a 256-bit vector result, first extract the 128-bit vector,
8177 // insert the element into the extracted half and then place it back.
8178 if (VT.is256BitVector() || VT.is512BitVector()) {
8179 if (!isa<ConstantSDNode>(N2))
8182 // Get the desired 128-bit vector half.
8183 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8184 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8186 // Insert the element into the desired half.
8187 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8188 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8190 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8191 DAG.getConstant(IdxIn128, MVT::i32));
8193 // Insert the changed part back to the 256-bit vector
8194 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8197 if (Subtarget->hasSSE41())
8198 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8200 if (EltVT == MVT::i8)
8203 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8204 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8205 // as its second argument.
8206 if (N1.getValueType() != MVT::i32)
8207 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8208 if (N2.getValueType() != MVT::i32)
8209 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8210 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8215 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8217 MVT OpVT = Op.getSimpleValueType();
8219 // If this is a 256-bit vector result, first insert into a 128-bit
8220 // vector and then insert into the 256-bit vector.
8221 if (!OpVT.is128BitVector()) {
8222 // Insert into a 128-bit vector.
8223 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8224 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8225 OpVT.getVectorNumElements() / SizeFactor);
8227 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8229 // Insert the 128-bit vector.
8230 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8233 if (OpVT == MVT::v1i64 &&
8234 Op.getOperand(0).getValueType() == MVT::i64)
8235 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8237 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8238 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8239 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8240 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8243 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8244 // a simple subregister reference or explicit instructions to grab
8245 // upper bits of a vector.
8246 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8247 SelectionDAG &DAG) {
8249 SDValue In = Op.getOperand(0);
8250 SDValue Idx = Op.getOperand(1);
8251 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8252 MVT ResVT = Op.getSimpleValueType();
8253 MVT InVT = In.getSimpleValueType();
8255 if (Subtarget->hasFp256()) {
8256 if (ResVT.is128BitVector() &&
8257 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8258 isa<ConstantSDNode>(Idx)) {
8259 return Extract128BitVector(In, IdxVal, DAG, dl);
8261 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8262 isa<ConstantSDNode>(Idx)) {
8263 return Extract256BitVector(In, IdxVal, DAG, dl);
8269 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8270 // simple superregister reference or explicit instructions to insert
8271 // the upper bits of a vector.
8272 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8273 SelectionDAG &DAG) {
8274 if (Subtarget->hasFp256()) {
8275 SDLoc dl(Op.getNode());
8276 SDValue Vec = Op.getNode()->getOperand(0);
8277 SDValue SubVec = Op.getNode()->getOperand(1);
8278 SDValue Idx = Op.getNode()->getOperand(2);
8280 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8281 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8282 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8283 isa<ConstantSDNode>(Idx)) {
8284 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8285 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8288 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8289 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8290 isa<ConstantSDNode>(Idx)) {
8291 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8292 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8298 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8299 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8300 // one of the above mentioned nodes. It has to be wrapped because otherwise
8301 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8302 // be used to form addressing mode. These wrapped nodes will be selected
8305 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8306 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8308 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8310 unsigned char OpFlag = 0;
8311 unsigned WrapperKind = X86ISD::Wrapper;
8312 CodeModel::Model M = getTargetMachine().getCodeModel();
8314 if (Subtarget->isPICStyleRIPRel() &&
8315 (M == CodeModel::Small || M == CodeModel::Kernel))
8316 WrapperKind = X86ISD::WrapperRIP;
8317 else if (Subtarget->isPICStyleGOT())
8318 OpFlag = X86II::MO_GOTOFF;
8319 else if (Subtarget->isPICStyleStubPIC())
8320 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8322 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8324 CP->getOffset(), OpFlag);
8326 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8327 // With PIC, the address is actually $g + Offset.
8329 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8330 DAG.getNode(X86ISD::GlobalBaseReg,
8331 SDLoc(), getPointerTy()),
8338 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8339 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8341 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8343 unsigned char OpFlag = 0;
8344 unsigned WrapperKind = X86ISD::Wrapper;
8345 CodeModel::Model M = getTargetMachine().getCodeModel();
8347 if (Subtarget->isPICStyleRIPRel() &&
8348 (M == CodeModel::Small || M == CodeModel::Kernel))
8349 WrapperKind = X86ISD::WrapperRIP;
8350 else if (Subtarget->isPICStyleGOT())
8351 OpFlag = X86II::MO_GOTOFF;
8352 else if (Subtarget->isPICStyleStubPIC())
8353 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8355 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8358 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8360 // With PIC, the address is actually $g + Offset.
8362 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8363 DAG.getNode(X86ISD::GlobalBaseReg,
8364 SDLoc(), getPointerTy()),
8371 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8372 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8374 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8376 unsigned char OpFlag = 0;
8377 unsigned WrapperKind = X86ISD::Wrapper;
8378 CodeModel::Model M = getTargetMachine().getCodeModel();
8380 if (Subtarget->isPICStyleRIPRel() &&
8381 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8382 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8383 OpFlag = X86II::MO_GOTPCREL;
8384 WrapperKind = X86ISD::WrapperRIP;
8385 } else if (Subtarget->isPICStyleGOT()) {
8386 OpFlag = X86II::MO_GOT;
8387 } else if (Subtarget->isPICStyleStubPIC()) {
8388 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8389 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8390 OpFlag = X86II::MO_DARWIN_NONLAZY;
8393 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8396 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8398 // With PIC, the address is actually $g + Offset.
8399 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8400 !Subtarget->is64Bit()) {
8401 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8402 DAG.getNode(X86ISD::GlobalBaseReg,
8403 SDLoc(), getPointerTy()),
8407 // For symbols that require a load from a stub to get the address, emit the
8409 if (isGlobalStubReference(OpFlag))
8410 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8411 MachinePointerInfo::getGOT(), false, false, false, 0);
8417 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8418 // Create the TargetBlockAddressAddress node.
8419 unsigned char OpFlags =
8420 Subtarget->ClassifyBlockAddressReference();
8421 CodeModel::Model M = getTargetMachine().getCodeModel();
8422 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8423 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8425 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8428 if (Subtarget->isPICStyleRIPRel() &&
8429 (M == CodeModel::Small || M == CodeModel::Kernel))
8430 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8432 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8434 // With PIC, the address is actually $g + Offset.
8435 if (isGlobalRelativeToPICBase(OpFlags)) {
8436 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8437 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8445 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8446 int64_t Offset, SelectionDAG &DAG) const {
8447 // Create the TargetGlobalAddress node, folding in the constant
8448 // offset if it is legal.
8449 unsigned char OpFlags =
8450 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8451 CodeModel::Model M = getTargetMachine().getCodeModel();
8453 if (OpFlags == X86II::MO_NO_FLAG &&
8454 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8455 // A direct static reference to a global.
8456 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8459 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8462 if (Subtarget->isPICStyleRIPRel() &&
8463 (M == CodeModel::Small || M == CodeModel::Kernel))
8464 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8466 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8468 // With PIC, the address is actually $g + Offset.
8469 if (isGlobalRelativeToPICBase(OpFlags)) {
8470 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8471 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8475 // For globals that require a load from a stub to get the address, emit the
8477 if (isGlobalStubReference(OpFlags))
8478 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8479 MachinePointerInfo::getGOT(), false, false, false, 0);
8481 // If there was a non-zero offset that we didn't fold, create an explicit
8484 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8485 DAG.getConstant(Offset, getPointerTy()));
8491 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8492 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8493 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8494 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8498 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8499 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8500 unsigned char OperandFlags, bool LocalDynamic = false) {
8501 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8502 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8504 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8505 GA->getValueType(0),
8509 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8513 SDValue Ops[] = { Chain, TGA, *InFlag };
8514 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8516 SDValue Ops[] = { Chain, TGA };
8517 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8520 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8521 MFI->setAdjustsStack(true);
8523 SDValue Flag = Chain.getValue(1);
8524 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8527 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8529 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8532 SDLoc dl(GA); // ? function entry point might be better
8533 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8534 DAG.getNode(X86ISD::GlobalBaseReg,
8535 SDLoc(), PtrVT), InFlag);
8536 InFlag = Chain.getValue(1);
8538 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8541 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8543 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8545 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8546 X86::RAX, X86II::MO_TLSGD);
8549 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8555 // Get the start address of the TLS block for this module.
8556 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8557 .getInfo<X86MachineFunctionInfo>();
8558 MFI->incNumLocalDynamicTLSAccesses();
8562 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8563 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8566 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8567 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8568 InFlag = Chain.getValue(1);
8569 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8570 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8573 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8577 unsigned char OperandFlags = X86II::MO_DTPOFF;
8578 unsigned WrapperKind = X86ISD::Wrapper;
8579 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8580 GA->getValueType(0),
8581 GA->getOffset(), OperandFlags);
8582 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8584 // Add x@dtpoff with the base.
8585 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8588 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8589 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8590 const EVT PtrVT, TLSModel::Model model,
8591 bool is64Bit, bool isPIC) {
8594 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8595 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8596 is64Bit ? 257 : 256));
8598 SDValue ThreadPointer =
8599 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8600 MachinePointerInfo(Ptr), false, false, false, 0);
8602 unsigned char OperandFlags = 0;
8603 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8605 unsigned WrapperKind = X86ISD::Wrapper;
8606 if (model == TLSModel::LocalExec) {
8607 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8608 } else if (model == TLSModel::InitialExec) {
8610 OperandFlags = X86II::MO_GOTTPOFF;
8611 WrapperKind = X86ISD::WrapperRIP;
8613 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8616 llvm_unreachable("Unexpected model");
8619 // emit "addl x@ntpoff,%eax" (local exec)
8620 // or "addl x@indntpoff,%eax" (initial exec)
8621 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8623 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8624 GA->getOffset(), OperandFlags);
8625 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8627 if (model == TLSModel::InitialExec) {
8628 if (isPIC && !is64Bit) {
8629 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8630 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8634 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8635 MachinePointerInfo::getGOT(), false, false, false, 0);
8638 // The address of the thread local variable is the add of the thread
8639 // pointer with the offset of the variable.
8640 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8644 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8646 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8647 const GlobalValue *GV = GA->getGlobal();
8649 if (Subtarget->isTargetELF()) {
8650 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8653 case TLSModel::GeneralDynamic:
8654 if (Subtarget->is64Bit())
8655 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8656 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8657 case TLSModel::LocalDynamic:
8658 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8659 Subtarget->is64Bit());
8660 case TLSModel::InitialExec:
8661 case TLSModel::LocalExec:
8662 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8663 Subtarget->is64Bit(),
8664 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8666 llvm_unreachable("Unknown TLS model.");
8669 if (Subtarget->isTargetDarwin()) {
8670 // Darwin only has one model of TLS. Lower to that.
8671 unsigned char OpFlag = 0;
8672 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8673 X86ISD::WrapperRIP : X86ISD::Wrapper;
8675 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8677 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8678 !Subtarget->is64Bit();
8680 OpFlag = X86II::MO_TLVP_PIC_BASE;
8682 OpFlag = X86II::MO_TLVP;
8684 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8685 GA->getValueType(0),
8686 GA->getOffset(), OpFlag);
8687 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8689 // With PIC32, the address is actually $g + Offset.
8691 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8692 DAG.getNode(X86ISD::GlobalBaseReg,
8693 SDLoc(), getPointerTy()),
8696 // Lowering the machine isd will make sure everything is in the right
8698 SDValue Chain = DAG.getEntryNode();
8699 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8700 SDValue Args[] = { Chain, Offset };
8701 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8703 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8704 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8705 MFI->setAdjustsStack(true);
8707 // And our return value (tls address) is in the standard call return value
8709 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8710 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8714 if (Subtarget->isTargetKnownWindowsMSVC() ||
8715 Subtarget->isTargetWindowsGNU()) {
8716 // Just use the implicit TLS architecture
8717 // Need to generate someting similar to:
8718 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8720 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8721 // mov rcx, qword [rdx+rcx*8]
8722 // mov eax, .tls$:tlsvar
8723 // [rax+rcx] contains the address
8724 // Windows 64bit: gs:0x58
8725 // Windows 32bit: fs:__tls_array
8727 // If GV is an alias then use the aliasee for determining
8728 // thread-localness.
8729 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8730 GV = GA->getAliasedGlobal();
8732 SDValue Chain = DAG.getEntryNode();
8734 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8735 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8736 // use its literal value of 0x2C.
8737 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8738 ? Type::getInt8PtrTy(*DAG.getContext(),
8740 : Type::getInt32PtrTy(*DAG.getContext(),
8744 Subtarget->is64Bit()
8745 ? DAG.getIntPtrConstant(0x58)
8746 : (Subtarget->isTargetWindowsGNU()
8747 ? DAG.getIntPtrConstant(0x2C)
8748 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8750 SDValue ThreadPointer =
8751 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8752 MachinePointerInfo(Ptr), false, false, false, 0);
8754 // Load the _tls_index variable
8755 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8756 if (Subtarget->is64Bit())
8757 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8758 IDX, MachinePointerInfo(), MVT::i32,
8761 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8762 false, false, false, 0);
8764 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8766 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8768 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8769 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8770 false, false, false, 0);
8772 // Get the offset of start of .tls section
8773 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8774 GA->getValueType(0),
8775 GA->getOffset(), X86II::MO_SECREL);
8776 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8778 // The address of the thread local variable is the add of the thread
8779 // pointer with the offset of the variable.
8780 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8783 llvm_unreachable("TLS not implemented for this target.");
8786 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8787 /// and take a 2 x i32 value to shift plus a shift amount.
8788 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8789 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8790 MVT VT = Op.getSimpleValueType();
8791 unsigned VTBits = VT.getSizeInBits();
8793 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8794 SDValue ShOpLo = Op.getOperand(0);
8795 SDValue ShOpHi = Op.getOperand(1);
8796 SDValue ShAmt = Op.getOperand(2);
8797 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8798 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8800 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8801 DAG.getConstant(VTBits - 1, MVT::i8));
8802 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8803 DAG.getConstant(VTBits - 1, MVT::i8))
8804 : DAG.getConstant(0, VT);
8807 if (Op.getOpcode() == ISD::SHL_PARTS) {
8808 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8809 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8811 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8812 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8815 // If the shift amount is larger or equal than the width of a part we can't
8816 // rely on the results of shld/shrd. Insert a test and select the appropriate
8817 // values for large shift amounts.
8818 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8819 DAG.getConstant(VTBits, MVT::i8));
8820 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8821 AndNode, DAG.getConstant(0, MVT::i8));
8824 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8825 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8826 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8828 if (Op.getOpcode() == ISD::SHL_PARTS) {
8829 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8830 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8832 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8833 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8836 SDValue Ops[2] = { Lo, Hi };
8837 return DAG.getMergeValues(Ops, dl);
8840 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8841 SelectionDAG &DAG) const {
8842 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8844 if (SrcVT.isVector())
8847 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8848 "Unknown SINT_TO_FP to lower!");
8850 // These are really Legal; return the operand so the caller accepts it as
8852 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8854 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8855 Subtarget->is64Bit()) {
8860 unsigned Size = SrcVT.getSizeInBits()/8;
8861 MachineFunction &MF = DAG.getMachineFunction();
8862 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8863 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8864 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8866 MachinePointerInfo::getFixedStack(SSFI),
8868 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8871 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8873 SelectionDAG &DAG) const {
8877 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8879 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8881 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8883 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8885 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8886 MachineMemOperand *MMO;
8888 int SSFI = FI->getIndex();
8890 DAG.getMachineFunction()
8891 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8892 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8894 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8895 StackSlot = StackSlot.getOperand(1);
8897 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8898 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8900 Tys, Ops, SrcVT, MMO);
8903 Chain = Result.getValue(1);
8904 SDValue InFlag = Result.getValue(2);
8906 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8907 // shouldn't be necessary except that RFP cannot be live across
8908 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8909 MachineFunction &MF = DAG.getMachineFunction();
8910 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8911 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8912 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8913 Tys = DAG.getVTList(MVT::Other);
8915 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8917 MachineMemOperand *MMO =
8918 DAG.getMachineFunction()
8919 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8920 MachineMemOperand::MOStore, SSFISize, SSFISize);
8922 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8923 Ops, Op.getValueType(), MMO);
8924 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8925 MachinePointerInfo::getFixedStack(SSFI),
8926 false, false, false, 0);
8932 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8933 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8934 SelectionDAG &DAG) const {
8935 // This algorithm is not obvious. Here it is what we're trying to output:
8938 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8939 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8943 pshufd $0x4e, %xmm0, %xmm1
8949 LLVMContext *Context = DAG.getContext();
8951 // Build some magic constants.
8952 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8953 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8954 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8956 SmallVector<Constant*,2> CV1;
8958 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8959 APInt(64, 0x4330000000000000ULL))));
8961 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8962 APInt(64, 0x4530000000000000ULL))));
8963 Constant *C1 = ConstantVector::get(CV1);
8964 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8966 // Load the 64-bit value into an XMM register.
8967 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8969 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8970 MachinePointerInfo::getConstantPool(),
8971 false, false, false, 16);
8972 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8973 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8976 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8977 MachinePointerInfo::getConstantPool(),
8978 false, false, false, 16);
8979 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8980 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8983 if (Subtarget->hasSSE3()) {
8984 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8985 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8987 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8988 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8990 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8991 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8995 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8996 DAG.getIntPtrConstant(0));
8999 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9000 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9001 SelectionDAG &DAG) const {
9003 // FP constant to bias correct the final result.
9004 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9007 // Load the 32-bit value into an XMM register.
9008 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9011 // Zero out the upper parts of the register.
9012 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9014 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9015 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9016 DAG.getIntPtrConstant(0));
9018 // Or the load with the bias.
9019 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9020 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9021 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9023 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9024 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9025 MVT::v2f64, Bias)));
9026 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9027 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9028 DAG.getIntPtrConstant(0));
9030 // Subtract the bias.
9031 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9033 // Handle final rounding.
9034 EVT DestVT = Op.getValueType();
9036 if (DestVT.bitsLT(MVT::f64))
9037 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9038 DAG.getIntPtrConstant(0));
9039 if (DestVT.bitsGT(MVT::f64))
9040 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9042 // Handle final rounding.
9046 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9047 SelectionDAG &DAG) const {
9048 SDValue N0 = Op.getOperand(0);
9049 MVT SVT = N0.getSimpleValueType();
9052 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9053 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9054 "Custom UINT_TO_FP is not supported!");
9056 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9057 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9058 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9061 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9062 SelectionDAG &DAG) const {
9063 SDValue N0 = Op.getOperand(0);
9066 if (Op.getValueType().isVector())
9067 return lowerUINT_TO_FP_vec(Op, DAG);
9069 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9070 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9071 // the optimization here.
9072 if (DAG.SignBitIsZero(N0))
9073 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9075 MVT SrcVT = N0.getSimpleValueType();
9076 MVT DstVT = Op.getSimpleValueType();
9077 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9078 return LowerUINT_TO_FP_i64(Op, DAG);
9079 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9080 return LowerUINT_TO_FP_i32(Op, DAG);
9081 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9084 // Make a 64-bit buffer, and use it to build an FILD.
9085 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9086 if (SrcVT == MVT::i32) {
9087 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9088 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9089 getPointerTy(), StackSlot, WordOff);
9090 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9091 StackSlot, MachinePointerInfo(),
9093 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9094 OffsetSlot, MachinePointerInfo(),
9096 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9100 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9101 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9102 StackSlot, MachinePointerInfo(),
9104 // For i64 source, we need to add the appropriate power of 2 if the input
9105 // was negative. This is the same as the optimization in
9106 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9107 // we must be careful to do the computation in x87 extended precision, not
9108 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9109 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9110 MachineMemOperand *MMO =
9111 DAG.getMachineFunction()
9112 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9113 MachineMemOperand::MOLoad, 8, 8);
9115 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9116 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9117 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9120 APInt FF(32, 0x5F800000ULL);
9122 // Check whether the sign bit is set.
9123 SDValue SignSet = DAG.getSetCC(dl,
9124 getSetCCResultType(*DAG.getContext(), MVT::i64),
9125 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9128 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9129 SDValue FudgePtr = DAG.getConstantPool(
9130 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9133 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9134 SDValue Zero = DAG.getIntPtrConstant(0);
9135 SDValue Four = DAG.getIntPtrConstant(4);
9136 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9138 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9140 // Load the value out, extending it from f32 to f80.
9141 // FIXME: Avoid the extend by constructing the right constant pool?
9142 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9143 FudgePtr, MachinePointerInfo::getConstantPool(),
9144 MVT::f32, false, false, 4);
9145 // Extend everything to 80 bits to force it to be done on x87.
9146 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9147 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9150 std::pair<SDValue,SDValue>
9151 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9152 bool IsSigned, bool IsReplace) const {
9155 EVT DstTy = Op.getValueType();
9157 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9158 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9162 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9163 DstTy.getSimpleVT() >= MVT::i16 &&
9164 "Unknown FP_TO_INT to lower!");
9166 // These are really Legal.
9167 if (DstTy == MVT::i32 &&
9168 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9169 return std::make_pair(SDValue(), SDValue());
9170 if (Subtarget->is64Bit() &&
9171 DstTy == MVT::i64 &&
9172 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9173 return std::make_pair(SDValue(), SDValue());
9175 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9176 // stack slot, or into the FTOL runtime function.
9177 MachineFunction &MF = DAG.getMachineFunction();
9178 unsigned MemSize = DstTy.getSizeInBits()/8;
9179 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9180 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9183 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9184 Opc = X86ISD::WIN_FTOL;
9186 switch (DstTy.getSimpleVT().SimpleTy) {
9187 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9188 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9189 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9190 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9193 SDValue Chain = DAG.getEntryNode();
9194 SDValue Value = Op.getOperand(0);
9195 EVT TheVT = Op.getOperand(0).getValueType();
9196 // FIXME This causes a redundant load/store if the SSE-class value is already
9197 // in memory, such as if it is on the callstack.
9198 if (isScalarFPTypeInSSEReg(TheVT)) {
9199 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9200 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9201 MachinePointerInfo::getFixedStack(SSFI),
9203 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9205 Chain, StackSlot, DAG.getValueType(TheVT)
9208 MachineMemOperand *MMO =
9209 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9210 MachineMemOperand::MOLoad, MemSize, MemSize);
9211 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9212 Chain = Value.getValue(1);
9213 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9214 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9217 MachineMemOperand *MMO =
9218 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9219 MachineMemOperand::MOStore, MemSize, MemSize);
9221 if (Opc != X86ISD::WIN_FTOL) {
9222 // Build the FP_TO_INT*_IN_MEM
9223 SDValue Ops[] = { Chain, Value, StackSlot };
9224 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9226 return std::make_pair(FIST, StackSlot);
9228 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9229 DAG.getVTList(MVT::Other, MVT::Glue),
9231 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9232 MVT::i32, ftol.getValue(1));
9233 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9234 MVT::i32, eax.getValue(2));
9235 SDValue Ops[] = { eax, edx };
9236 SDValue pair = IsReplace
9237 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9238 : DAG.getMergeValues(Ops, DL);
9239 return std::make_pair(pair, SDValue());
9243 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9244 const X86Subtarget *Subtarget) {
9245 MVT VT = Op->getSimpleValueType(0);
9246 SDValue In = Op->getOperand(0);
9247 MVT InVT = In.getSimpleValueType();
9250 // Optimize vectors in AVX mode:
9253 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9254 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9255 // Concat upper and lower parts.
9258 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9259 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9260 // Concat upper and lower parts.
9263 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9264 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9265 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9268 if (Subtarget->hasInt256())
9269 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9271 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9272 SDValue Undef = DAG.getUNDEF(InVT);
9273 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9274 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9275 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9277 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9278 VT.getVectorNumElements()/2);
9280 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9281 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9283 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9286 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9287 SelectionDAG &DAG) {
9288 MVT VT = Op->getSimpleValueType(0);
9289 SDValue In = Op->getOperand(0);
9290 MVT InVT = In.getSimpleValueType();
9292 unsigned int NumElts = VT.getVectorNumElements();
9293 if (NumElts != 8 && NumElts != 16)
9296 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9297 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9299 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9300 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9301 // Now we have only mask extension
9302 assert(InVT.getVectorElementType() == MVT::i1);
9303 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9304 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9305 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9306 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9307 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9308 MachinePointerInfo::getConstantPool(),
9309 false, false, false, Alignment);
9311 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9312 if (VT.is512BitVector())
9314 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9317 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9318 SelectionDAG &DAG) {
9319 if (Subtarget->hasFp256()) {
9320 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9328 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9329 SelectionDAG &DAG) {
9331 MVT VT = Op.getSimpleValueType();
9332 SDValue In = Op.getOperand(0);
9333 MVT SVT = In.getSimpleValueType();
9335 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9336 return LowerZERO_EXTEND_AVX512(Op, DAG);
9338 if (Subtarget->hasFp256()) {
9339 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9344 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9345 VT.getVectorNumElements() != SVT.getVectorNumElements());
9349 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9351 MVT VT = Op.getSimpleValueType();
9352 SDValue In = Op.getOperand(0);
9353 MVT InVT = In.getSimpleValueType();
9355 if (VT == MVT::i1) {
9356 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9357 "Invalid scalar TRUNCATE operation");
9358 if (InVT == MVT::i32)
9360 if (InVT.getSizeInBits() == 64)
9361 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9362 else if (InVT.getSizeInBits() < 32)
9363 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9364 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9366 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9367 "Invalid TRUNCATE operation");
9369 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9370 if (VT.getVectorElementType().getSizeInBits() >=8)
9371 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9373 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9374 unsigned NumElts = InVT.getVectorNumElements();
9375 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9376 if (InVT.getSizeInBits() < 512) {
9377 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9378 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9382 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9383 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9384 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9385 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9386 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9387 MachinePointerInfo::getConstantPool(),
9388 false, false, false, Alignment);
9389 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9390 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9391 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9394 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9395 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9396 if (Subtarget->hasInt256()) {
9397 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9398 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9399 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9401 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9402 DAG.getIntPtrConstant(0));
9405 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9406 DAG.getIntPtrConstant(0));
9407 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9408 DAG.getIntPtrConstant(2));
9409 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9410 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9411 static const int ShufMask[] = {0, 2, 4, 6};
9412 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9415 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9416 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9417 if (Subtarget->hasInt256()) {
9418 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9420 SmallVector<SDValue,32> pshufbMask;
9421 for (unsigned i = 0; i < 2; ++i) {
9422 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9423 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9424 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9425 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9426 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9427 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9428 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9429 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9430 for (unsigned j = 0; j < 8; ++j)
9431 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9433 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9434 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9435 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9437 static const int ShufMask[] = {0, 2, -1, -1};
9438 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9440 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9441 DAG.getIntPtrConstant(0));
9442 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9445 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9446 DAG.getIntPtrConstant(0));
9448 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9449 DAG.getIntPtrConstant(4));
9451 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9452 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9455 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9456 -1, -1, -1, -1, -1, -1, -1, -1};
9458 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9459 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9460 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9462 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9463 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9465 // The MOVLHPS Mask:
9466 static const int ShufMask2[] = {0, 1, 4, 5};
9467 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9468 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9471 // Handle truncation of V256 to V128 using shuffles.
9472 if (!VT.is128BitVector() || !InVT.is256BitVector())
9475 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9477 unsigned NumElems = VT.getVectorNumElements();
9478 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9480 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9481 // Prepare truncation shuffle mask
9482 for (unsigned i = 0; i != NumElems; ++i)
9484 SDValue V = DAG.getVectorShuffle(NVT, DL,
9485 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9486 DAG.getUNDEF(NVT), &MaskVec[0]);
9487 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9488 DAG.getIntPtrConstant(0));
9491 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9492 SelectionDAG &DAG) const {
9493 assert(!Op.getSimpleValueType().isVector());
9495 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9496 /*IsSigned=*/ true, /*IsReplace=*/ false);
9497 SDValue FIST = Vals.first, StackSlot = Vals.second;
9498 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9499 if (!FIST.getNode()) return Op;
9501 if (StackSlot.getNode())
9503 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9504 FIST, StackSlot, MachinePointerInfo(),
9505 false, false, false, 0);
9507 // The node is the result.
9511 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9512 SelectionDAG &DAG) const {
9513 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9514 /*IsSigned=*/ false, /*IsReplace=*/ false);
9515 SDValue FIST = Vals.first, StackSlot = Vals.second;
9516 assert(FIST.getNode() && "Unexpected failure");
9518 if (StackSlot.getNode())
9520 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9521 FIST, StackSlot, MachinePointerInfo(),
9522 false, false, false, 0);
9524 // The node is the result.
9528 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9530 MVT VT = Op.getSimpleValueType();
9531 SDValue In = Op.getOperand(0);
9532 MVT SVT = In.getSimpleValueType();
9534 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9536 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9537 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9538 In, DAG.getUNDEF(SVT)));
9541 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9542 LLVMContext *Context = DAG.getContext();
9544 MVT VT = Op.getSimpleValueType();
9546 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9547 if (VT.isVector()) {
9548 EltVT = VT.getVectorElementType();
9549 NumElts = VT.getVectorNumElements();
9552 if (EltVT == MVT::f64)
9553 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9554 APInt(64, ~(1ULL << 63))));
9556 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9557 APInt(32, ~(1U << 31))));
9558 C = ConstantVector::getSplat(NumElts, C);
9559 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9560 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9561 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9562 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9563 MachinePointerInfo::getConstantPool(),
9564 false, false, false, Alignment);
9565 if (VT.isVector()) {
9566 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9567 return DAG.getNode(ISD::BITCAST, dl, VT,
9568 DAG.getNode(ISD::AND, dl, ANDVT,
9569 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9571 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9573 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9576 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9577 LLVMContext *Context = DAG.getContext();
9579 MVT VT = Op.getSimpleValueType();
9581 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9582 if (VT.isVector()) {
9583 EltVT = VT.getVectorElementType();
9584 NumElts = VT.getVectorNumElements();
9587 if (EltVT == MVT::f64)
9588 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9589 APInt(64, 1ULL << 63)));
9591 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9592 APInt(32, 1U << 31)));
9593 C = ConstantVector::getSplat(NumElts, C);
9594 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9595 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9596 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9597 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9598 MachinePointerInfo::getConstantPool(),
9599 false, false, false, Alignment);
9600 if (VT.isVector()) {
9601 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9602 return DAG.getNode(ISD::BITCAST, dl, VT,
9603 DAG.getNode(ISD::XOR, dl, XORVT,
9604 DAG.getNode(ISD::BITCAST, dl, XORVT,
9606 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9609 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9612 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9613 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9614 LLVMContext *Context = DAG.getContext();
9615 SDValue Op0 = Op.getOperand(0);
9616 SDValue Op1 = Op.getOperand(1);
9618 MVT VT = Op.getSimpleValueType();
9619 MVT SrcVT = Op1.getSimpleValueType();
9621 // If second operand is smaller, extend it first.
9622 if (SrcVT.bitsLT(VT)) {
9623 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9626 // And if it is bigger, shrink it first.
9627 if (SrcVT.bitsGT(VT)) {
9628 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9632 // At this point the operands and the result should have the same
9633 // type, and that won't be f80 since that is not custom lowered.
9635 // First get the sign bit of second operand.
9636 SmallVector<Constant*,4> CV;
9637 if (SrcVT == MVT::f64) {
9638 const fltSemantics &Sem = APFloat::IEEEdouble;
9639 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9640 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9642 const fltSemantics &Sem = APFloat::IEEEsingle;
9643 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9644 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9645 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9646 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9648 Constant *C = ConstantVector::get(CV);
9649 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9650 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9651 MachinePointerInfo::getConstantPool(),
9652 false, false, false, 16);
9653 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9655 // Shift sign bit right or left if the two operands have different types.
9656 if (SrcVT.bitsGT(VT)) {
9657 // Op0 is MVT::f32, Op1 is MVT::f64.
9658 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9659 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9660 DAG.getConstant(32, MVT::i32));
9661 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9662 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9663 DAG.getIntPtrConstant(0));
9666 // Clear first operand sign bit.
9668 if (VT == MVT::f64) {
9669 const fltSemantics &Sem = APFloat::IEEEdouble;
9670 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9671 APInt(64, ~(1ULL << 63)))));
9672 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9674 const fltSemantics &Sem = APFloat::IEEEsingle;
9675 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9676 APInt(32, ~(1U << 31)))));
9677 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9678 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9679 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9681 C = ConstantVector::get(CV);
9682 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9683 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9684 MachinePointerInfo::getConstantPool(),
9685 false, false, false, 16);
9686 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9688 // Or the value with the sign bit.
9689 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9692 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9693 SDValue N0 = Op.getOperand(0);
9695 MVT VT = Op.getSimpleValueType();
9697 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9698 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9699 DAG.getConstant(1, VT));
9700 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9703 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9705 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9706 SelectionDAG &DAG) {
9707 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9709 if (!Subtarget->hasSSE41())
9712 if (!Op->hasOneUse())
9715 SDNode *N = Op.getNode();
9718 SmallVector<SDValue, 8> Opnds;
9719 DenseMap<SDValue, unsigned> VecInMap;
9720 SmallVector<SDValue, 8> VecIns;
9721 EVT VT = MVT::Other;
9723 // Recognize a special case where a vector is casted into wide integer to
9725 Opnds.push_back(N->getOperand(0));
9726 Opnds.push_back(N->getOperand(1));
9728 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9729 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9730 // BFS traverse all OR'd operands.
9731 if (I->getOpcode() == ISD::OR) {
9732 Opnds.push_back(I->getOperand(0));
9733 Opnds.push_back(I->getOperand(1));
9734 // Re-evaluate the number of nodes to be traversed.
9735 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9739 // Quit if a non-EXTRACT_VECTOR_ELT
9740 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9743 // Quit if without a constant index.
9744 SDValue Idx = I->getOperand(1);
9745 if (!isa<ConstantSDNode>(Idx))
9748 SDValue ExtractedFromVec = I->getOperand(0);
9749 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9750 if (M == VecInMap.end()) {
9751 VT = ExtractedFromVec.getValueType();
9752 // Quit if not 128/256-bit vector.
9753 if (!VT.is128BitVector() && !VT.is256BitVector())
9755 // Quit if not the same type.
9756 if (VecInMap.begin() != VecInMap.end() &&
9757 VT != VecInMap.begin()->first.getValueType())
9759 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9760 VecIns.push_back(ExtractedFromVec);
9762 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9765 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9766 "Not extracted from 128-/256-bit vector.");
9768 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9770 for (DenseMap<SDValue, unsigned>::const_iterator
9771 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9772 // Quit if not all elements are used.
9773 if (I->second != FullMask)
9777 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9779 // Cast all vectors into TestVT for PTEST.
9780 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9781 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9783 // If more than one full vectors are evaluated, OR them first before PTEST.
9784 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9785 // Each iteration will OR 2 nodes and append the result until there is only
9786 // 1 node left, i.e. the final OR'd value of all vectors.
9787 SDValue LHS = VecIns[Slot];
9788 SDValue RHS = VecIns[Slot + 1];
9789 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9792 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9793 VecIns.back(), VecIns.back());
9796 /// \brief return true if \c Op has a use that doesn't just read flags.
9797 static bool hasNonFlagsUse(SDValue Op) {
9798 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9801 unsigned UOpNo = UI.getOperandNo();
9802 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9803 // Look pass truncate.
9804 UOpNo = User->use_begin().getOperandNo();
9805 User = *User->use_begin();
9808 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9809 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9815 /// Emit nodes that will be selected as "test Op0,Op0", or something
9817 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9818 SelectionDAG &DAG) const {
9819 if (Op.getValueType() == MVT::i1)
9820 // KORTEST instruction should be selected
9821 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9822 DAG.getConstant(0, Op.getValueType()));
9824 // CF and OF aren't always set the way we want. Determine which
9825 // of these we need.
9826 bool NeedCF = false;
9827 bool NeedOF = false;
9830 case X86::COND_A: case X86::COND_AE:
9831 case X86::COND_B: case X86::COND_BE:
9834 case X86::COND_G: case X86::COND_GE:
9835 case X86::COND_L: case X86::COND_LE:
9836 case X86::COND_O: case X86::COND_NO:
9840 // See if we can use the EFLAGS value from the operand instead of
9841 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9842 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9843 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9844 // Emit a CMP with 0, which is the TEST pattern.
9845 //if (Op.getValueType() == MVT::i1)
9846 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9847 // DAG.getConstant(0, MVT::i1));
9848 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9849 DAG.getConstant(0, Op.getValueType()));
9851 unsigned Opcode = 0;
9852 unsigned NumOperands = 0;
9854 // Truncate operations may prevent the merge of the SETCC instruction
9855 // and the arithmetic instruction before it. Attempt to truncate the operands
9856 // of the arithmetic instruction and use a reduced bit-width instruction.
9857 bool NeedTruncation = false;
9858 SDValue ArithOp = Op;
9859 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9860 SDValue Arith = Op->getOperand(0);
9861 // Both the trunc and the arithmetic op need to have one user each.
9862 if (Arith->hasOneUse())
9863 switch (Arith.getOpcode()) {
9870 NeedTruncation = true;
9876 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9877 // which may be the result of a CAST. We use the variable 'Op', which is the
9878 // non-casted variable when we check for possible users.
9879 switch (ArithOp.getOpcode()) {
9881 // Due to an isel shortcoming, be conservative if this add is likely to be
9882 // selected as part of a load-modify-store instruction. When the root node
9883 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9884 // uses of other nodes in the match, such as the ADD in this case. This
9885 // leads to the ADD being left around and reselected, with the result being
9886 // two adds in the output. Alas, even if none our users are stores, that
9887 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9888 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9889 // climbing the DAG back to the root, and it doesn't seem to be worth the
9891 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9892 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9893 if (UI->getOpcode() != ISD::CopyToReg &&
9894 UI->getOpcode() != ISD::SETCC &&
9895 UI->getOpcode() != ISD::STORE)
9898 if (ConstantSDNode *C =
9899 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9900 // An add of one will be selected as an INC.
9901 if (C->getAPIntValue() == 1) {
9902 Opcode = X86ISD::INC;
9907 // An add of negative one (subtract of one) will be selected as a DEC.
9908 if (C->getAPIntValue().isAllOnesValue()) {
9909 Opcode = X86ISD::DEC;
9915 // Otherwise use a regular EFLAGS-setting add.
9916 Opcode = X86ISD::ADD;
9921 // If we have a constant logical shift that's only used in a comparison
9922 // against zero turn it into an equivalent AND. This allows turning it into
9923 // a TEST instruction later.
9924 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9925 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9926 EVT VT = Op.getValueType();
9927 unsigned BitWidth = VT.getSizeInBits();
9928 unsigned ShAmt = Op->getConstantOperandVal(1);
9929 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9931 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9932 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9933 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9934 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9936 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9937 DAG.getConstant(Mask, VT));
9938 DAG.ReplaceAllUsesWith(Op, New);
9944 // If the primary and result isn't used, don't bother using X86ISD::AND,
9945 // because a TEST instruction will be better.
9946 if (!hasNonFlagsUse(Op))
9952 // Due to the ISEL shortcoming noted above, be conservative if this op is
9953 // likely to be selected as part of a load-modify-store instruction.
9954 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9955 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9956 if (UI->getOpcode() == ISD::STORE)
9959 // Otherwise use a regular EFLAGS-setting instruction.
9960 switch (ArithOp.getOpcode()) {
9961 default: llvm_unreachable("unexpected operator!");
9962 case ISD::SUB: Opcode = X86ISD::SUB; break;
9963 case ISD::XOR: Opcode = X86ISD::XOR; break;
9964 case ISD::AND: Opcode = X86ISD::AND; break;
9966 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9967 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9968 if (EFLAGS.getNode())
9971 Opcode = X86ISD::OR;
9985 return SDValue(Op.getNode(), 1);
9991 // If we found that truncation is beneficial, perform the truncation and
9993 if (NeedTruncation) {
9994 EVT VT = Op.getValueType();
9995 SDValue WideVal = Op->getOperand(0);
9996 EVT WideVT = WideVal.getValueType();
9997 unsigned ConvertedOp = 0;
9998 // Use a target machine opcode to prevent further DAGCombine
9999 // optimizations that may separate the arithmetic operations
10000 // from the setcc node.
10001 switch (WideVal.getOpcode()) {
10003 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10004 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10005 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10006 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10007 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10011 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10012 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10013 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10014 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10015 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10021 // Emit a CMP with 0, which is the TEST pattern.
10022 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10023 DAG.getConstant(0, Op.getValueType()));
10025 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10026 SmallVector<SDValue, 4> Ops;
10027 for (unsigned i = 0; i != NumOperands; ++i)
10028 Ops.push_back(Op.getOperand(i));
10030 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10031 DAG.ReplaceAllUsesWith(Op, New);
10032 return SDValue(New.getNode(), 1);
10035 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10037 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10038 SDLoc dl, SelectionDAG &DAG) const {
10039 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10040 if (C->getAPIntValue() == 0)
10041 return EmitTest(Op0, X86CC, dl, DAG);
10043 if (Op0.getValueType() == MVT::i1)
10044 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10047 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10048 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10049 // Do the comparison at i32 if it's smaller, besides the Atom case.
10050 // This avoids subregister aliasing issues. Keep the smaller reference
10051 // if we're optimizing for size, however, as that'll allow better folding
10052 // of memory operations.
10053 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10054 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10055 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10056 !Subtarget->isAtom()) {
10057 unsigned ExtendOp =
10058 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10059 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10060 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10062 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10063 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10064 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10066 return SDValue(Sub.getNode(), 1);
10068 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10071 /// Convert a comparison if required by the subtarget.
10072 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10073 SelectionDAG &DAG) const {
10074 // If the subtarget does not support the FUCOMI instruction, floating-point
10075 // comparisons have to be converted.
10076 if (Subtarget->hasCMov() ||
10077 Cmp.getOpcode() != X86ISD::CMP ||
10078 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10079 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10082 // The instruction selector will select an FUCOM instruction instead of
10083 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10084 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10085 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10087 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10088 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10089 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10090 DAG.getConstant(8, MVT::i8));
10091 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10092 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10095 static bool isAllOnes(SDValue V) {
10096 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10097 return C && C->isAllOnesValue();
10100 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10101 /// if it's possible.
10102 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10103 SDLoc dl, SelectionDAG &DAG) const {
10104 SDValue Op0 = And.getOperand(0);
10105 SDValue Op1 = And.getOperand(1);
10106 if (Op0.getOpcode() == ISD::TRUNCATE)
10107 Op0 = Op0.getOperand(0);
10108 if (Op1.getOpcode() == ISD::TRUNCATE)
10109 Op1 = Op1.getOperand(0);
10112 if (Op1.getOpcode() == ISD::SHL)
10113 std::swap(Op0, Op1);
10114 if (Op0.getOpcode() == ISD::SHL) {
10115 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10116 if (And00C->getZExtValue() == 1) {
10117 // If we looked past a truncate, check that it's only truncating away
10119 unsigned BitWidth = Op0.getValueSizeInBits();
10120 unsigned AndBitWidth = And.getValueSizeInBits();
10121 if (BitWidth > AndBitWidth) {
10123 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10124 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10128 RHS = Op0.getOperand(1);
10130 } else if (Op1.getOpcode() == ISD::Constant) {
10131 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10132 uint64_t AndRHSVal = AndRHS->getZExtValue();
10133 SDValue AndLHS = Op0;
10135 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10136 LHS = AndLHS.getOperand(0);
10137 RHS = AndLHS.getOperand(1);
10140 // Use BT if the immediate can't be encoded in a TEST instruction.
10141 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10143 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10147 if (LHS.getNode()) {
10148 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10149 // instruction. Since the shift amount is in-range-or-undefined, we know
10150 // that doing a bittest on the i32 value is ok. We extend to i32 because
10151 // the encoding for the i16 version is larger than the i32 version.
10152 // Also promote i16 to i32 for performance / code size reason.
10153 if (LHS.getValueType() == MVT::i8 ||
10154 LHS.getValueType() == MVT::i16)
10155 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10157 // If the operand types disagree, extend the shift amount to match. Since
10158 // BT ignores high bits (like shifts) we can use anyextend.
10159 if (LHS.getValueType() != RHS.getValueType())
10160 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10162 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10163 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10164 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10165 DAG.getConstant(Cond, MVT::i8), BT);
10171 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10173 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10178 // SSE Condition code mapping:
10187 switch (SetCCOpcode) {
10188 default: llvm_unreachable("Unexpected SETCC condition");
10190 case ISD::SETEQ: SSECC = 0; break;
10192 case ISD::SETGT: Swap = true; // Fallthrough
10194 case ISD::SETOLT: SSECC = 1; break;
10196 case ISD::SETGE: Swap = true; // Fallthrough
10198 case ISD::SETOLE: SSECC = 2; break;
10199 case ISD::SETUO: SSECC = 3; break;
10201 case ISD::SETNE: SSECC = 4; break;
10202 case ISD::SETULE: Swap = true; // Fallthrough
10203 case ISD::SETUGE: SSECC = 5; break;
10204 case ISD::SETULT: Swap = true; // Fallthrough
10205 case ISD::SETUGT: SSECC = 6; break;
10206 case ISD::SETO: SSECC = 7; break;
10208 case ISD::SETONE: SSECC = 8; break;
10211 std::swap(Op0, Op1);
10216 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10217 // ones, and then concatenate the result back.
10218 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10219 MVT VT = Op.getSimpleValueType();
10221 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10222 "Unsupported value type for operation");
10224 unsigned NumElems = VT.getVectorNumElements();
10226 SDValue CC = Op.getOperand(2);
10228 // Extract the LHS vectors
10229 SDValue LHS = Op.getOperand(0);
10230 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10231 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10233 // Extract the RHS vectors
10234 SDValue RHS = Op.getOperand(1);
10235 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10236 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10238 // Issue the operation on the smaller types and concatenate the result back
10239 MVT EltVT = VT.getVectorElementType();
10240 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10241 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10242 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10243 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10246 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10247 const X86Subtarget *Subtarget) {
10248 SDValue Op0 = Op.getOperand(0);
10249 SDValue Op1 = Op.getOperand(1);
10250 SDValue CC = Op.getOperand(2);
10251 MVT VT = Op.getSimpleValueType();
10254 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10255 Op.getValueType().getScalarType() == MVT::i1 &&
10256 "Cannot set masked compare for this operation");
10258 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10260 bool Unsigned = false;
10263 switch (SetCCOpcode) {
10264 default: llvm_unreachable("Unexpected SETCC condition");
10265 case ISD::SETNE: SSECC = 4; break;
10266 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10267 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10268 case ISD::SETLT: Swap = true; //fall-through
10269 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10270 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10271 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10272 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10273 case ISD::SETULE: Unsigned = true; //fall-through
10274 case ISD::SETLE: SSECC = 2; break;
10278 std::swap(Op0, Op1);
10280 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10281 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10282 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10283 DAG.getConstant(SSECC, MVT::i8));
10286 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10287 /// operand \p Op1. If non-trivial (for example because it's not constant)
10288 /// return an empty value.
10289 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10291 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10295 MVT VT = Op1.getSimpleValueType();
10296 MVT EVT = VT.getVectorElementType();
10297 unsigned n = VT.getVectorNumElements();
10298 SmallVector<SDValue, 8> ULTOp1;
10300 for (unsigned i = 0; i < n; ++i) {
10301 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10302 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10305 // Avoid underflow.
10306 APInt Val = Elt->getAPIntValue();
10310 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10313 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10316 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10317 SelectionDAG &DAG) {
10318 SDValue Op0 = Op.getOperand(0);
10319 SDValue Op1 = Op.getOperand(1);
10320 SDValue CC = Op.getOperand(2);
10321 MVT VT = Op.getSimpleValueType();
10322 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10323 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10328 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10329 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10332 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10333 unsigned Opc = X86ISD::CMPP;
10334 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10335 assert(VT.getVectorNumElements() <= 16);
10336 Opc = X86ISD::CMPM;
10338 // In the two special cases we can't handle, emit two comparisons.
10341 unsigned CombineOpc;
10342 if (SetCCOpcode == ISD::SETUEQ) {
10343 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10345 assert(SetCCOpcode == ISD::SETONE);
10346 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10349 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10350 DAG.getConstant(CC0, MVT::i8));
10351 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10352 DAG.getConstant(CC1, MVT::i8));
10353 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10355 // Handle all other FP comparisons here.
10356 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10357 DAG.getConstant(SSECC, MVT::i8));
10360 // Break 256-bit integer vector compare into smaller ones.
10361 if (VT.is256BitVector() && !Subtarget->hasInt256())
10362 return Lower256IntVSETCC(Op, DAG);
10364 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10365 EVT OpVT = Op1.getValueType();
10366 if (Subtarget->hasAVX512()) {
10367 if (Op1.getValueType().is512BitVector() ||
10368 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10369 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10371 // In AVX-512 architecture setcc returns mask with i1 elements,
10372 // But there is no compare instruction for i8 and i16 elements.
10373 // We are not talking about 512-bit operands in this case, these
10374 // types are illegal.
10376 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10377 OpVT.getVectorElementType().getSizeInBits() >= 8))
10378 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10379 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10382 // We are handling one of the integer comparisons here. Since SSE only has
10383 // GT and EQ comparisons for integer, swapping operands and multiple
10384 // operations may be required for some comparisons.
10386 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10387 bool Subus = false;
10389 switch (SetCCOpcode) {
10390 default: llvm_unreachable("Unexpected SETCC condition");
10391 case ISD::SETNE: Invert = true;
10392 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10393 case ISD::SETLT: Swap = true;
10394 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10395 case ISD::SETGE: Swap = true;
10396 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10397 Invert = true; break;
10398 case ISD::SETULT: Swap = true;
10399 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10400 FlipSigns = true; break;
10401 case ISD::SETUGE: Swap = true;
10402 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10403 FlipSigns = true; Invert = true; break;
10406 // Special case: Use min/max operations for SETULE/SETUGE
10407 MVT VET = VT.getVectorElementType();
10409 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10410 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10413 switch (SetCCOpcode) {
10415 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10416 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10419 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10422 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10423 if (!MinMax && hasSubus) {
10424 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10426 // t = psubus Op0, Op1
10427 // pcmpeq t, <0..0>
10428 switch (SetCCOpcode) {
10430 case ISD::SETULT: {
10431 // If the comparison is against a constant we can turn this into a
10432 // setule. With psubus, setule does not require a swap. This is
10433 // beneficial because the constant in the register is no longer
10434 // destructed as the destination so it can be hoisted out of a loop.
10435 // Only do this pre-AVX since vpcmp* is no longer destructive.
10436 if (Subtarget->hasAVX())
10438 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10439 if (ULEOp1.getNode()) {
10441 Subus = true; Invert = false; Swap = false;
10445 // Psubus is better than flip-sign because it requires no inversion.
10446 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10447 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10451 Opc = X86ISD::SUBUS;
10457 std::swap(Op0, Op1);
10459 // Check that the operation in question is available (most are plain SSE2,
10460 // but PCMPGTQ and PCMPEQQ have different requirements).
10461 if (VT == MVT::v2i64) {
10462 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10463 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10465 // First cast everything to the right type.
10466 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10467 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10469 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10470 // bits of the inputs before performing those operations. The lower
10471 // compare is always unsigned.
10474 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10476 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10477 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10478 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10479 Sign, Zero, Sign, Zero);
10481 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10482 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10484 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10485 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10486 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10488 // Create masks for only the low parts/high parts of the 64 bit integers.
10489 static const int MaskHi[] = { 1, 1, 3, 3 };
10490 static const int MaskLo[] = { 0, 0, 2, 2 };
10491 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10492 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10493 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10495 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10496 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10499 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10501 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10504 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10505 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10506 // pcmpeqd + pshufd + pand.
10507 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10509 // First cast everything to the right type.
10510 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10511 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10514 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10516 // Make sure the lower and upper halves are both all-ones.
10517 static const int Mask[] = { 1, 0, 3, 2 };
10518 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10519 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10522 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10524 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10528 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10529 // bits of the inputs before performing those operations.
10531 EVT EltVT = VT.getVectorElementType();
10532 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10533 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10534 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10537 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10539 // If the logical-not of the result is required, perform that now.
10541 Result = DAG.getNOT(dl, Result, VT);
10544 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10547 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10548 getZeroVector(VT, Subtarget, DAG, dl));
10553 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10555 MVT VT = Op.getSimpleValueType();
10557 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10559 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10560 && "SetCC type must be 8-bit or 1-bit integer");
10561 SDValue Op0 = Op.getOperand(0);
10562 SDValue Op1 = Op.getOperand(1);
10564 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10566 // Optimize to BT if possible.
10567 // Lower (X & (1 << N)) == 0 to BT(X, N).
10568 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10569 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10570 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10571 Op1.getOpcode() == ISD::Constant &&
10572 cast<ConstantSDNode>(Op1)->isNullValue() &&
10573 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10574 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10575 if (NewSetCC.getNode())
10579 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10581 if (Op1.getOpcode() == ISD::Constant &&
10582 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10583 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10584 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10586 // If the input is a setcc, then reuse the input setcc or use a new one with
10587 // the inverted condition.
10588 if (Op0.getOpcode() == X86ISD::SETCC) {
10589 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10590 bool Invert = (CC == ISD::SETNE) ^
10591 cast<ConstantSDNode>(Op1)->isNullValue();
10595 CCode = X86::GetOppositeBranchCondition(CCode);
10596 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10597 DAG.getConstant(CCode, MVT::i8),
10598 Op0.getOperand(1));
10600 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10604 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10605 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10606 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10608 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10609 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10612 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10613 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10614 if (X86CC == X86::COND_INVALID)
10617 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10618 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10619 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10620 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10622 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10626 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10627 static bool isX86LogicalCmp(SDValue Op) {
10628 unsigned Opc = Op.getNode()->getOpcode();
10629 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10630 Opc == X86ISD::SAHF)
10632 if (Op.getResNo() == 1 &&
10633 (Opc == X86ISD::ADD ||
10634 Opc == X86ISD::SUB ||
10635 Opc == X86ISD::ADC ||
10636 Opc == X86ISD::SBB ||
10637 Opc == X86ISD::SMUL ||
10638 Opc == X86ISD::UMUL ||
10639 Opc == X86ISD::INC ||
10640 Opc == X86ISD::DEC ||
10641 Opc == X86ISD::OR ||
10642 Opc == X86ISD::XOR ||
10643 Opc == X86ISD::AND))
10646 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10652 static bool isZero(SDValue V) {
10653 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10654 return C && C->isNullValue();
10657 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10658 if (V.getOpcode() != ISD::TRUNCATE)
10661 SDValue VOp0 = V.getOperand(0);
10662 unsigned InBits = VOp0.getValueSizeInBits();
10663 unsigned Bits = V.getValueSizeInBits();
10664 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10667 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10668 bool addTest = true;
10669 SDValue Cond = Op.getOperand(0);
10670 SDValue Op1 = Op.getOperand(1);
10671 SDValue Op2 = Op.getOperand(2);
10673 EVT VT = Op1.getValueType();
10676 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10677 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10678 // sequence later on.
10679 if (Cond.getOpcode() == ISD::SETCC &&
10680 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10681 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10682 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10683 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10684 int SSECC = translateX86FSETCC(
10685 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10688 if (Subtarget->hasAVX512()) {
10689 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10690 DAG.getConstant(SSECC, MVT::i8));
10691 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10693 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10694 DAG.getConstant(SSECC, MVT::i8));
10695 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10696 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10697 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10701 if (Cond.getOpcode() == ISD::SETCC) {
10702 SDValue NewCond = LowerSETCC(Cond, DAG);
10703 if (NewCond.getNode())
10707 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10708 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10709 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10710 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10711 if (Cond.getOpcode() == X86ISD::SETCC &&
10712 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10713 isZero(Cond.getOperand(1).getOperand(1))) {
10714 SDValue Cmp = Cond.getOperand(1);
10716 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10718 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10719 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10720 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10722 SDValue CmpOp0 = Cmp.getOperand(0);
10723 // Apply further optimizations for special cases
10724 // (select (x != 0), -1, 0) -> neg & sbb
10725 // (select (x == 0), 0, -1) -> neg & sbb
10726 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10727 if (YC->isNullValue() &&
10728 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10729 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10730 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10731 DAG.getConstant(0, CmpOp0.getValueType()),
10733 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10734 DAG.getConstant(X86::COND_B, MVT::i8),
10735 SDValue(Neg.getNode(), 1));
10739 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10740 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10741 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10743 SDValue Res = // Res = 0 or -1.
10744 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10745 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10747 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10748 Res = DAG.getNOT(DL, Res, Res.getValueType());
10750 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10751 if (!N2C || !N2C->isNullValue())
10752 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10757 // Look past (and (setcc_carry (cmp ...)), 1).
10758 if (Cond.getOpcode() == ISD::AND &&
10759 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10760 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10761 if (C && C->getAPIntValue() == 1)
10762 Cond = Cond.getOperand(0);
10765 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10766 // setting operand in place of the X86ISD::SETCC.
10767 unsigned CondOpcode = Cond.getOpcode();
10768 if (CondOpcode == X86ISD::SETCC ||
10769 CondOpcode == X86ISD::SETCC_CARRY) {
10770 CC = Cond.getOperand(0);
10772 SDValue Cmp = Cond.getOperand(1);
10773 unsigned Opc = Cmp.getOpcode();
10774 MVT VT = Op.getSimpleValueType();
10776 bool IllegalFPCMov = false;
10777 if (VT.isFloatingPoint() && !VT.isVector() &&
10778 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10779 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10781 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10782 Opc == X86ISD::BT) { // FIXME
10786 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10787 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10788 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10789 Cond.getOperand(0).getValueType() != MVT::i8)) {
10790 SDValue LHS = Cond.getOperand(0);
10791 SDValue RHS = Cond.getOperand(1);
10792 unsigned X86Opcode;
10795 switch (CondOpcode) {
10796 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10797 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10798 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10799 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10800 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10801 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10802 default: llvm_unreachable("unexpected overflowing operator");
10804 if (CondOpcode == ISD::UMULO)
10805 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10808 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10810 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10812 if (CondOpcode == ISD::UMULO)
10813 Cond = X86Op.getValue(2);
10815 Cond = X86Op.getValue(1);
10817 CC = DAG.getConstant(X86Cond, MVT::i8);
10822 // Look pass the truncate if the high bits are known zero.
10823 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10824 Cond = Cond.getOperand(0);
10826 // We know the result of AND is compared against zero. Try to match
10828 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10829 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10830 if (NewSetCC.getNode()) {
10831 CC = NewSetCC.getOperand(0);
10832 Cond = NewSetCC.getOperand(1);
10839 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10840 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10843 // a < b ? -1 : 0 -> RES = ~setcc_carry
10844 // a < b ? 0 : -1 -> RES = setcc_carry
10845 // a >= b ? -1 : 0 -> RES = setcc_carry
10846 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10847 if (Cond.getOpcode() == X86ISD::SUB) {
10848 Cond = ConvertCmpIfNecessary(Cond, DAG);
10849 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10851 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10852 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10853 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10854 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10855 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10856 return DAG.getNOT(DL, Res, Res.getValueType());
10861 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10862 // widen the cmov and push the truncate through. This avoids introducing a new
10863 // branch during isel and doesn't add any extensions.
10864 if (Op.getValueType() == MVT::i8 &&
10865 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10866 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10867 if (T1.getValueType() == T2.getValueType() &&
10868 // Blacklist CopyFromReg to avoid partial register stalls.
10869 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10870 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10871 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10872 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10876 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10877 // condition is true.
10878 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10879 SDValue Ops[] = { Op2, Op1, CC, Cond };
10880 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10883 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10884 MVT VT = Op->getSimpleValueType(0);
10885 SDValue In = Op->getOperand(0);
10886 MVT InVT = In.getSimpleValueType();
10889 unsigned int NumElts = VT.getVectorNumElements();
10890 if (NumElts != 8 && NumElts != 16)
10893 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10894 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10897 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10899 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10900 Constant *C = ConstantInt::get(*DAG.getContext(),
10901 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10903 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10904 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10905 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10906 MachinePointerInfo::getConstantPool(),
10907 false, false, false, Alignment);
10908 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10909 if (VT.is512BitVector())
10911 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10914 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10915 SelectionDAG &DAG) {
10916 MVT VT = Op->getSimpleValueType(0);
10917 SDValue In = Op->getOperand(0);
10918 MVT InVT = In.getSimpleValueType();
10921 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10922 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10924 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10925 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10926 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10929 if (Subtarget->hasInt256())
10930 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10932 // Optimize vectors in AVX mode
10933 // Sign extend v8i16 to v8i32 and
10936 // Divide input vector into two parts
10937 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10938 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10939 // concat the vectors to original VT
10941 unsigned NumElems = InVT.getVectorNumElements();
10942 SDValue Undef = DAG.getUNDEF(InVT);
10944 SmallVector<int,8> ShufMask1(NumElems, -1);
10945 for (unsigned i = 0; i != NumElems/2; ++i)
10948 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10950 SmallVector<int,8> ShufMask2(NumElems, -1);
10951 for (unsigned i = 0; i != NumElems/2; ++i)
10952 ShufMask2[i] = i + NumElems/2;
10954 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10956 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10957 VT.getVectorNumElements()/2);
10959 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10960 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10962 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10965 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10966 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10967 // from the AND / OR.
10968 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10969 Opc = Op.getOpcode();
10970 if (Opc != ISD::OR && Opc != ISD::AND)
10972 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10973 Op.getOperand(0).hasOneUse() &&
10974 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10975 Op.getOperand(1).hasOneUse());
10978 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10979 // 1 and that the SETCC node has a single use.
10980 static bool isXor1OfSetCC(SDValue Op) {
10981 if (Op.getOpcode() != ISD::XOR)
10983 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10984 if (N1C && N1C->getAPIntValue() == 1) {
10985 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10986 Op.getOperand(0).hasOneUse();
10991 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10992 bool addTest = true;
10993 SDValue Chain = Op.getOperand(0);
10994 SDValue Cond = Op.getOperand(1);
10995 SDValue Dest = Op.getOperand(2);
10998 bool Inverted = false;
11000 if (Cond.getOpcode() == ISD::SETCC) {
11001 // Check for setcc([su]{add,sub,mul}o == 0).
11002 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11003 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11004 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11005 Cond.getOperand(0).getResNo() == 1 &&
11006 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11007 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11008 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11009 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11010 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11011 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11013 Cond = Cond.getOperand(0);
11015 SDValue NewCond = LowerSETCC(Cond, DAG);
11016 if (NewCond.getNode())
11021 // FIXME: LowerXALUO doesn't handle these!!
11022 else if (Cond.getOpcode() == X86ISD::ADD ||
11023 Cond.getOpcode() == X86ISD::SUB ||
11024 Cond.getOpcode() == X86ISD::SMUL ||
11025 Cond.getOpcode() == X86ISD::UMUL)
11026 Cond = LowerXALUO(Cond, DAG);
11029 // Look pass (and (setcc_carry (cmp ...)), 1).
11030 if (Cond.getOpcode() == ISD::AND &&
11031 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11032 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11033 if (C && C->getAPIntValue() == 1)
11034 Cond = Cond.getOperand(0);
11037 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11038 // setting operand in place of the X86ISD::SETCC.
11039 unsigned CondOpcode = Cond.getOpcode();
11040 if (CondOpcode == X86ISD::SETCC ||
11041 CondOpcode == X86ISD::SETCC_CARRY) {
11042 CC = Cond.getOperand(0);
11044 SDValue Cmp = Cond.getOperand(1);
11045 unsigned Opc = Cmp.getOpcode();
11046 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11047 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11051 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11055 // These can only come from an arithmetic instruction with overflow,
11056 // e.g. SADDO, UADDO.
11057 Cond = Cond.getNode()->getOperand(1);
11063 CondOpcode = Cond.getOpcode();
11064 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11065 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11066 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11067 Cond.getOperand(0).getValueType() != MVT::i8)) {
11068 SDValue LHS = Cond.getOperand(0);
11069 SDValue RHS = Cond.getOperand(1);
11070 unsigned X86Opcode;
11073 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11074 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11076 switch (CondOpcode) {
11077 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11079 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11081 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11084 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11085 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11089 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11092 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11093 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11094 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11095 default: llvm_unreachable("unexpected overflowing operator");
11098 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11099 if (CondOpcode == ISD::UMULO)
11100 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11103 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11105 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11107 if (CondOpcode == ISD::UMULO)
11108 Cond = X86Op.getValue(2);
11110 Cond = X86Op.getValue(1);
11112 CC = DAG.getConstant(X86Cond, MVT::i8);
11116 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11117 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11118 if (CondOpc == ISD::OR) {
11119 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11120 // two branches instead of an explicit OR instruction with a
11122 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11123 isX86LogicalCmp(Cmp)) {
11124 CC = Cond.getOperand(0).getOperand(0);
11125 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11126 Chain, Dest, CC, Cmp);
11127 CC = Cond.getOperand(1).getOperand(0);
11131 } else { // ISD::AND
11132 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11133 // two branches instead of an explicit AND instruction with a
11134 // separate test. However, we only do this if this block doesn't
11135 // have a fall-through edge, because this requires an explicit
11136 // jmp when the condition is false.
11137 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11138 isX86LogicalCmp(Cmp) &&
11139 Op.getNode()->hasOneUse()) {
11140 X86::CondCode CCode =
11141 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11142 CCode = X86::GetOppositeBranchCondition(CCode);
11143 CC = DAG.getConstant(CCode, MVT::i8);
11144 SDNode *User = *Op.getNode()->use_begin();
11145 // Look for an unconditional branch following this conditional branch.
11146 // We need this because we need to reverse the successors in order
11147 // to implement FCMP_OEQ.
11148 if (User->getOpcode() == ISD::BR) {
11149 SDValue FalseBB = User->getOperand(1);
11151 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11152 assert(NewBR == User);
11156 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11157 Chain, Dest, CC, Cmp);
11158 X86::CondCode CCode =
11159 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11160 CCode = X86::GetOppositeBranchCondition(CCode);
11161 CC = DAG.getConstant(CCode, MVT::i8);
11167 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11168 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11169 // It should be transformed during dag combiner except when the condition
11170 // is set by a arithmetics with overflow node.
11171 X86::CondCode CCode =
11172 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11173 CCode = X86::GetOppositeBranchCondition(CCode);
11174 CC = DAG.getConstant(CCode, MVT::i8);
11175 Cond = Cond.getOperand(0).getOperand(1);
11177 } else if (Cond.getOpcode() == ISD::SETCC &&
11178 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11179 // For FCMP_OEQ, we can emit
11180 // two branches instead of an explicit AND instruction with a
11181 // separate test. However, we only do this if this block doesn't
11182 // have a fall-through edge, because this requires an explicit
11183 // jmp when the condition is false.
11184 if (Op.getNode()->hasOneUse()) {
11185 SDNode *User = *Op.getNode()->use_begin();
11186 // Look for an unconditional branch following this conditional branch.
11187 // We need this because we need to reverse the successors in order
11188 // to implement FCMP_OEQ.
11189 if (User->getOpcode() == ISD::BR) {
11190 SDValue FalseBB = User->getOperand(1);
11192 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11193 assert(NewBR == User);
11197 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11198 Cond.getOperand(0), Cond.getOperand(1));
11199 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11200 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11201 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11202 Chain, Dest, CC, Cmp);
11203 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11208 } else if (Cond.getOpcode() == ISD::SETCC &&
11209 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11210 // For FCMP_UNE, we can emit
11211 // two branches instead of an explicit AND instruction with a
11212 // separate test. However, we only do this if this block doesn't
11213 // have a fall-through edge, because this requires an explicit
11214 // jmp when the condition is false.
11215 if (Op.getNode()->hasOneUse()) {
11216 SDNode *User = *Op.getNode()->use_begin();
11217 // Look for an unconditional branch following this conditional branch.
11218 // We need this because we need to reverse the successors in order
11219 // to implement FCMP_UNE.
11220 if (User->getOpcode() == ISD::BR) {
11221 SDValue FalseBB = User->getOperand(1);
11223 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11224 assert(NewBR == User);
11227 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11228 Cond.getOperand(0), Cond.getOperand(1));
11229 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11230 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11231 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11232 Chain, Dest, CC, Cmp);
11233 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11243 // Look pass the truncate if the high bits are known zero.
11244 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11245 Cond = Cond.getOperand(0);
11247 // We know the result of AND is compared against zero. Try to match
11249 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11250 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11251 if (NewSetCC.getNode()) {
11252 CC = NewSetCC.getOperand(0);
11253 Cond = NewSetCC.getOperand(1);
11260 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11261 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11263 Cond = ConvertCmpIfNecessary(Cond, DAG);
11264 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11265 Chain, Dest, CC, Cond);
11268 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11269 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11270 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11271 // that the guard pages used by the OS virtual memory manager are allocated in
11272 // correct sequence.
11274 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11275 SelectionDAG &DAG) const {
11276 MachineFunction &MF = DAG.getMachineFunction();
11277 bool SplitStack = MF.shouldSplitStack();
11278 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11283 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11284 SDNode* Node = Op.getNode();
11286 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11287 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11288 " not tell us which reg is the stack pointer!");
11289 EVT VT = Node->getValueType(0);
11290 SDValue Tmp1 = SDValue(Node, 0);
11291 SDValue Tmp2 = SDValue(Node, 1);
11292 SDValue Tmp3 = Node->getOperand(2);
11293 SDValue Chain = Tmp1.getOperand(0);
11295 // Chain the dynamic stack allocation so that it doesn't modify the stack
11296 // pointer when other instructions are using the stack.
11297 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11300 SDValue Size = Tmp2.getOperand(1);
11301 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11302 Chain = SP.getValue(1);
11303 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11304 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11305 unsigned StackAlign = TFI.getStackAlignment();
11306 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11307 if (Align > StackAlign)
11308 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11309 DAG.getConstant(-(uint64_t)Align, VT));
11310 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11312 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11313 DAG.getIntPtrConstant(0, true), SDValue(),
11316 SDValue Ops[2] = { Tmp1, Tmp2 };
11317 return DAG.getMergeValues(Ops, dl);
11321 SDValue Chain = Op.getOperand(0);
11322 SDValue Size = Op.getOperand(1);
11323 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11324 EVT VT = Op.getNode()->getValueType(0);
11326 bool Is64Bit = Subtarget->is64Bit();
11327 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11330 MachineRegisterInfo &MRI = MF.getRegInfo();
11333 // The 64 bit implementation of segmented stacks needs to clobber both r10
11334 // r11. This makes it impossible to use it along with nested parameters.
11335 const Function *F = MF.getFunction();
11337 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11339 if (I->hasNestAttr())
11340 report_fatal_error("Cannot use segmented stacks with functions that "
11341 "have nested arguments.");
11344 const TargetRegisterClass *AddrRegClass =
11345 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11346 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11347 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11348 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11349 DAG.getRegister(Vreg, SPTy));
11350 SDValue Ops1[2] = { Value, Chain };
11351 return DAG.getMergeValues(Ops1, dl);
11354 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11356 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11357 Flag = Chain.getValue(1);
11358 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11360 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11362 const X86RegisterInfo *RegInfo =
11363 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11364 unsigned SPReg = RegInfo->getStackRegister();
11365 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11366 Chain = SP.getValue(1);
11369 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11370 DAG.getConstant(-(uint64_t)Align, VT));
11371 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11374 SDValue Ops1[2] = { SP, Chain };
11375 return DAG.getMergeValues(Ops1, dl);
11379 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11380 MachineFunction &MF = DAG.getMachineFunction();
11381 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11383 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11386 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11387 // vastart just stores the address of the VarArgsFrameIndex slot into the
11388 // memory location argument.
11389 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11391 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11392 MachinePointerInfo(SV), false, false, 0);
11396 // gp_offset (0 - 6 * 8)
11397 // fp_offset (48 - 48 + 8 * 16)
11398 // overflow_arg_area (point to parameters coming in memory).
11400 SmallVector<SDValue, 8> MemOps;
11401 SDValue FIN = Op.getOperand(1);
11403 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11404 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11406 FIN, MachinePointerInfo(SV), false, false, 0);
11407 MemOps.push_back(Store);
11410 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11411 FIN, DAG.getIntPtrConstant(4));
11412 Store = DAG.getStore(Op.getOperand(0), DL,
11413 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11415 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11416 MemOps.push_back(Store);
11418 // Store ptr to overflow_arg_area
11419 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11420 FIN, DAG.getIntPtrConstant(4));
11421 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11423 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11424 MachinePointerInfo(SV, 8),
11426 MemOps.push_back(Store);
11428 // Store ptr to reg_save_area.
11429 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11430 FIN, DAG.getIntPtrConstant(8));
11431 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11433 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11434 MachinePointerInfo(SV, 16), false, false, 0);
11435 MemOps.push_back(Store);
11436 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11439 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11440 assert(Subtarget->is64Bit() &&
11441 "LowerVAARG only handles 64-bit va_arg!");
11442 assert((Subtarget->isTargetLinux() ||
11443 Subtarget->isTargetDarwin()) &&
11444 "Unhandled target in LowerVAARG");
11445 assert(Op.getNode()->getNumOperands() == 4);
11446 SDValue Chain = Op.getOperand(0);
11447 SDValue SrcPtr = Op.getOperand(1);
11448 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11449 unsigned Align = Op.getConstantOperandVal(3);
11452 EVT ArgVT = Op.getNode()->getValueType(0);
11453 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11454 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11457 // Decide which area this value should be read from.
11458 // TODO: Implement the AMD64 ABI in its entirety. This simple
11459 // selection mechanism works only for the basic types.
11460 if (ArgVT == MVT::f80) {
11461 llvm_unreachable("va_arg for f80 not yet implemented");
11462 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11463 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11464 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11465 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11467 llvm_unreachable("Unhandled argument type in LowerVAARG");
11470 if (ArgMode == 2) {
11471 // Sanity Check: Make sure using fp_offset makes sense.
11472 assert(!getTargetMachine().Options.UseSoftFloat &&
11473 !(DAG.getMachineFunction()
11474 .getFunction()->getAttributes()
11475 .hasAttribute(AttributeSet::FunctionIndex,
11476 Attribute::NoImplicitFloat)) &&
11477 Subtarget->hasSSE1());
11480 // Insert VAARG_64 node into the DAG
11481 // VAARG_64 returns two values: Variable Argument Address, Chain
11482 SmallVector<SDValue, 11> InstOps;
11483 InstOps.push_back(Chain);
11484 InstOps.push_back(SrcPtr);
11485 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11486 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11487 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11488 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11489 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11490 VTs, InstOps, MVT::i64,
11491 MachinePointerInfo(SV),
11493 /*Volatile=*/false,
11495 /*WriteMem=*/true);
11496 Chain = VAARG.getValue(1);
11498 // Load the next argument and return it
11499 return DAG.getLoad(ArgVT, dl,
11502 MachinePointerInfo(),
11503 false, false, false, 0);
11506 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11507 SelectionDAG &DAG) {
11508 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11509 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11510 SDValue Chain = Op.getOperand(0);
11511 SDValue DstPtr = Op.getOperand(1);
11512 SDValue SrcPtr = Op.getOperand(2);
11513 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11514 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11517 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11518 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11520 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11523 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11524 // amount is a constant. Takes immediate version of shift as input.
11525 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11526 SDValue SrcOp, uint64_t ShiftAmt,
11527 SelectionDAG &DAG) {
11528 MVT ElementType = VT.getVectorElementType();
11530 // Check for ShiftAmt >= element width
11531 if (ShiftAmt >= ElementType.getSizeInBits()) {
11532 if (Opc == X86ISD::VSRAI)
11533 ShiftAmt = ElementType.getSizeInBits() - 1;
11535 return DAG.getConstant(0, VT);
11538 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11539 && "Unknown target vector shift-by-constant node");
11541 // Fold this packed vector shift into a build vector if SrcOp is a
11542 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11543 if (VT == SrcOp.getSimpleValueType() &&
11544 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11545 SmallVector<SDValue, 8> Elts;
11546 unsigned NumElts = SrcOp->getNumOperands();
11547 ConstantSDNode *ND;
11550 default: llvm_unreachable(nullptr);
11551 case X86ISD::VSHLI:
11552 for (unsigned i=0; i!=NumElts; ++i) {
11553 SDValue CurrentOp = SrcOp->getOperand(i);
11554 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11555 Elts.push_back(CurrentOp);
11558 ND = cast<ConstantSDNode>(CurrentOp);
11559 const APInt &C = ND->getAPIntValue();
11560 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11563 case X86ISD::VSRLI:
11564 for (unsigned i=0; i!=NumElts; ++i) {
11565 SDValue CurrentOp = SrcOp->getOperand(i);
11566 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11567 Elts.push_back(CurrentOp);
11570 ND = cast<ConstantSDNode>(CurrentOp);
11571 const APInt &C = ND->getAPIntValue();
11572 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11575 case X86ISD::VSRAI:
11576 for (unsigned i=0; i!=NumElts; ++i) {
11577 SDValue CurrentOp = SrcOp->getOperand(i);
11578 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11579 Elts.push_back(CurrentOp);
11582 ND = cast<ConstantSDNode>(CurrentOp);
11583 const APInt &C = ND->getAPIntValue();
11584 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11589 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11592 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11595 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11596 // may or may not be a constant. Takes immediate version of shift as input.
11597 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11598 SDValue SrcOp, SDValue ShAmt,
11599 SelectionDAG &DAG) {
11600 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11602 // Catch shift-by-constant.
11603 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11604 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11605 CShAmt->getZExtValue(), DAG);
11607 // Change opcode to non-immediate version
11609 default: llvm_unreachable("Unknown target vector shift node");
11610 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11611 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11612 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11615 // Need to build a vector containing shift amount
11616 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11619 ShOps[1] = DAG.getConstant(0, MVT::i32);
11620 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11621 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11623 // The return type has to be a 128-bit type with the same element
11624 // type as the input type.
11625 MVT EltVT = VT.getVectorElementType();
11626 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11628 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11629 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11632 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11634 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11636 default: return SDValue(); // Don't custom lower most intrinsics.
11637 // Comparison intrinsics.
11638 case Intrinsic::x86_sse_comieq_ss:
11639 case Intrinsic::x86_sse_comilt_ss:
11640 case Intrinsic::x86_sse_comile_ss:
11641 case Intrinsic::x86_sse_comigt_ss:
11642 case Intrinsic::x86_sse_comige_ss:
11643 case Intrinsic::x86_sse_comineq_ss:
11644 case Intrinsic::x86_sse_ucomieq_ss:
11645 case Intrinsic::x86_sse_ucomilt_ss:
11646 case Intrinsic::x86_sse_ucomile_ss:
11647 case Intrinsic::x86_sse_ucomigt_ss:
11648 case Intrinsic::x86_sse_ucomige_ss:
11649 case Intrinsic::x86_sse_ucomineq_ss:
11650 case Intrinsic::x86_sse2_comieq_sd:
11651 case Intrinsic::x86_sse2_comilt_sd:
11652 case Intrinsic::x86_sse2_comile_sd:
11653 case Intrinsic::x86_sse2_comigt_sd:
11654 case Intrinsic::x86_sse2_comige_sd:
11655 case Intrinsic::x86_sse2_comineq_sd:
11656 case Intrinsic::x86_sse2_ucomieq_sd:
11657 case Intrinsic::x86_sse2_ucomilt_sd:
11658 case Intrinsic::x86_sse2_ucomile_sd:
11659 case Intrinsic::x86_sse2_ucomigt_sd:
11660 case Intrinsic::x86_sse2_ucomige_sd:
11661 case Intrinsic::x86_sse2_ucomineq_sd: {
11665 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11666 case Intrinsic::x86_sse_comieq_ss:
11667 case Intrinsic::x86_sse2_comieq_sd:
11668 Opc = X86ISD::COMI;
11671 case Intrinsic::x86_sse_comilt_ss:
11672 case Intrinsic::x86_sse2_comilt_sd:
11673 Opc = X86ISD::COMI;
11676 case Intrinsic::x86_sse_comile_ss:
11677 case Intrinsic::x86_sse2_comile_sd:
11678 Opc = X86ISD::COMI;
11681 case Intrinsic::x86_sse_comigt_ss:
11682 case Intrinsic::x86_sse2_comigt_sd:
11683 Opc = X86ISD::COMI;
11686 case Intrinsic::x86_sse_comige_ss:
11687 case Intrinsic::x86_sse2_comige_sd:
11688 Opc = X86ISD::COMI;
11691 case Intrinsic::x86_sse_comineq_ss:
11692 case Intrinsic::x86_sse2_comineq_sd:
11693 Opc = X86ISD::COMI;
11696 case Intrinsic::x86_sse_ucomieq_ss:
11697 case Intrinsic::x86_sse2_ucomieq_sd:
11698 Opc = X86ISD::UCOMI;
11701 case Intrinsic::x86_sse_ucomilt_ss:
11702 case Intrinsic::x86_sse2_ucomilt_sd:
11703 Opc = X86ISD::UCOMI;
11706 case Intrinsic::x86_sse_ucomile_ss:
11707 case Intrinsic::x86_sse2_ucomile_sd:
11708 Opc = X86ISD::UCOMI;
11711 case Intrinsic::x86_sse_ucomigt_ss:
11712 case Intrinsic::x86_sse2_ucomigt_sd:
11713 Opc = X86ISD::UCOMI;
11716 case Intrinsic::x86_sse_ucomige_ss:
11717 case Intrinsic::x86_sse2_ucomige_sd:
11718 Opc = X86ISD::UCOMI;
11721 case Intrinsic::x86_sse_ucomineq_ss:
11722 case Intrinsic::x86_sse2_ucomineq_sd:
11723 Opc = X86ISD::UCOMI;
11728 SDValue LHS = Op.getOperand(1);
11729 SDValue RHS = Op.getOperand(2);
11730 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11731 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11732 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11733 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11734 DAG.getConstant(X86CC, MVT::i8), Cond);
11735 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11738 // Arithmetic intrinsics.
11739 case Intrinsic::x86_sse2_pmulu_dq:
11740 case Intrinsic::x86_avx2_pmulu_dq:
11741 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11742 Op.getOperand(1), Op.getOperand(2));
11744 case Intrinsic::x86_sse41_pmuldq:
11745 case Intrinsic::x86_avx2_pmul_dq:
11746 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11747 Op.getOperand(1), Op.getOperand(2));
11749 case Intrinsic::x86_sse2_pmulhu_w:
11750 case Intrinsic::x86_avx2_pmulhu_w:
11751 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11752 Op.getOperand(1), Op.getOperand(2));
11754 case Intrinsic::x86_sse2_pmulh_w:
11755 case Intrinsic::x86_avx2_pmulh_w:
11756 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11757 Op.getOperand(1), Op.getOperand(2));
11759 // SSE2/AVX2 sub with unsigned saturation intrinsics
11760 case Intrinsic::x86_sse2_psubus_b:
11761 case Intrinsic::x86_sse2_psubus_w:
11762 case Intrinsic::x86_avx2_psubus_b:
11763 case Intrinsic::x86_avx2_psubus_w:
11764 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11765 Op.getOperand(1), Op.getOperand(2));
11767 // SSE3/AVX horizontal add/sub intrinsics
11768 case Intrinsic::x86_sse3_hadd_ps:
11769 case Intrinsic::x86_sse3_hadd_pd:
11770 case Intrinsic::x86_avx_hadd_ps_256:
11771 case Intrinsic::x86_avx_hadd_pd_256:
11772 case Intrinsic::x86_sse3_hsub_ps:
11773 case Intrinsic::x86_sse3_hsub_pd:
11774 case Intrinsic::x86_avx_hsub_ps_256:
11775 case Intrinsic::x86_avx_hsub_pd_256:
11776 case Intrinsic::x86_ssse3_phadd_w_128:
11777 case Intrinsic::x86_ssse3_phadd_d_128:
11778 case Intrinsic::x86_avx2_phadd_w:
11779 case Intrinsic::x86_avx2_phadd_d:
11780 case Intrinsic::x86_ssse3_phsub_w_128:
11781 case Intrinsic::x86_ssse3_phsub_d_128:
11782 case Intrinsic::x86_avx2_phsub_w:
11783 case Intrinsic::x86_avx2_phsub_d: {
11786 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11787 case Intrinsic::x86_sse3_hadd_ps:
11788 case Intrinsic::x86_sse3_hadd_pd:
11789 case Intrinsic::x86_avx_hadd_ps_256:
11790 case Intrinsic::x86_avx_hadd_pd_256:
11791 Opcode = X86ISD::FHADD;
11793 case Intrinsic::x86_sse3_hsub_ps:
11794 case Intrinsic::x86_sse3_hsub_pd:
11795 case Intrinsic::x86_avx_hsub_ps_256:
11796 case Intrinsic::x86_avx_hsub_pd_256:
11797 Opcode = X86ISD::FHSUB;
11799 case Intrinsic::x86_ssse3_phadd_w_128:
11800 case Intrinsic::x86_ssse3_phadd_d_128:
11801 case Intrinsic::x86_avx2_phadd_w:
11802 case Intrinsic::x86_avx2_phadd_d:
11803 Opcode = X86ISD::HADD;
11805 case Intrinsic::x86_ssse3_phsub_w_128:
11806 case Intrinsic::x86_ssse3_phsub_d_128:
11807 case Intrinsic::x86_avx2_phsub_w:
11808 case Intrinsic::x86_avx2_phsub_d:
11809 Opcode = X86ISD::HSUB;
11812 return DAG.getNode(Opcode, dl, Op.getValueType(),
11813 Op.getOperand(1), Op.getOperand(2));
11816 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11817 case Intrinsic::x86_sse2_pmaxu_b:
11818 case Intrinsic::x86_sse41_pmaxuw:
11819 case Intrinsic::x86_sse41_pmaxud:
11820 case Intrinsic::x86_avx2_pmaxu_b:
11821 case Intrinsic::x86_avx2_pmaxu_w:
11822 case Intrinsic::x86_avx2_pmaxu_d:
11823 case Intrinsic::x86_sse2_pminu_b:
11824 case Intrinsic::x86_sse41_pminuw:
11825 case Intrinsic::x86_sse41_pminud:
11826 case Intrinsic::x86_avx2_pminu_b:
11827 case Intrinsic::x86_avx2_pminu_w:
11828 case Intrinsic::x86_avx2_pminu_d:
11829 case Intrinsic::x86_sse41_pmaxsb:
11830 case Intrinsic::x86_sse2_pmaxs_w:
11831 case Intrinsic::x86_sse41_pmaxsd:
11832 case Intrinsic::x86_avx2_pmaxs_b:
11833 case Intrinsic::x86_avx2_pmaxs_w:
11834 case Intrinsic::x86_avx2_pmaxs_d:
11835 case Intrinsic::x86_sse41_pminsb:
11836 case Intrinsic::x86_sse2_pmins_w:
11837 case Intrinsic::x86_sse41_pminsd:
11838 case Intrinsic::x86_avx2_pmins_b:
11839 case Intrinsic::x86_avx2_pmins_w:
11840 case Intrinsic::x86_avx2_pmins_d: {
11843 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11844 case Intrinsic::x86_sse2_pmaxu_b:
11845 case Intrinsic::x86_sse41_pmaxuw:
11846 case Intrinsic::x86_sse41_pmaxud:
11847 case Intrinsic::x86_avx2_pmaxu_b:
11848 case Intrinsic::x86_avx2_pmaxu_w:
11849 case Intrinsic::x86_avx2_pmaxu_d:
11850 Opcode = X86ISD::UMAX;
11852 case Intrinsic::x86_sse2_pminu_b:
11853 case Intrinsic::x86_sse41_pminuw:
11854 case Intrinsic::x86_sse41_pminud:
11855 case Intrinsic::x86_avx2_pminu_b:
11856 case Intrinsic::x86_avx2_pminu_w:
11857 case Intrinsic::x86_avx2_pminu_d:
11858 Opcode = X86ISD::UMIN;
11860 case Intrinsic::x86_sse41_pmaxsb:
11861 case Intrinsic::x86_sse2_pmaxs_w:
11862 case Intrinsic::x86_sse41_pmaxsd:
11863 case Intrinsic::x86_avx2_pmaxs_b:
11864 case Intrinsic::x86_avx2_pmaxs_w:
11865 case Intrinsic::x86_avx2_pmaxs_d:
11866 Opcode = X86ISD::SMAX;
11868 case Intrinsic::x86_sse41_pminsb:
11869 case Intrinsic::x86_sse2_pmins_w:
11870 case Intrinsic::x86_sse41_pminsd:
11871 case Intrinsic::x86_avx2_pmins_b:
11872 case Intrinsic::x86_avx2_pmins_w:
11873 case Intrinsic::x86_avx2_pmins_d:
11874 Opcode = X86ISD::SMIN;
11877 return DAG.getNode(Opcode, dl, Op.getValueType(),
11878 Op.getOperand(1), Op.getOperand(2));
11881 // SSE/SSE2/AVX floating point max/min intrinsics.
11882 case Intrinsic::x86_sse_max_ps:
11883 case Intrinsic::x86_sse2_max_pd:
11884 case Intrinsic::x86_avx_max_ps_256:
11885 case Intrinsic::x86_avx_max_pd_256:
11886 case Intrinsic::x86_sse_min_ps:
11887 case Intrinsic::x86_sse2_min_pd:
11888 case Intrinsic::x86_avx_min_ps_256:
11889 case Intrinsic::x86_avx_min_pd_256: {
11892 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11893 case Intrinsic::x86_sse_max_ps:
11894 case Intrinsic::x86_sse2_max_pd:
11895 case Intrinsic::x86_avx_max_ps_256:
11896 case Intrinsic::x86_avx_max_pd_256:
11897 Opcode = X86ISD::FMAX;
11899 case Intrinsic::x86_sse_min_ps:
11900 case Intrinsic::x86_sse2_min_pd:
11901 case Intrinsic::x86_avx_min_ps_256:
11902 case Intrinsic::x86_avx_min_pd_256:
11903 Opcode = X86ISD::FMIN;
11906 return DAG.getNode(Opcode, dl, Op.getValueType(),
11907 Op.getOperand(1), Op.getOperand(2));
11910 // AVX2 variable shift intrinsics
11911 case Intrinsic::x86_avx2_psllv_d:
11912 case Intrinsic::x86_avx2_psllv_q:
11913 case Intrinsic::x86_avx2_psllv_d_256:
11914 case Intrinsic::x86_avx2_psllv_q_256:
11915 case Intrinsic::x86_avx2_psrlv_d:
11916 case Intrinsic::x86_avx2_psrlv_q:
11917 case Intrinsic::x86_avx2_psrlv_d_256:
11918 case Intrinsic::x86_avx2_psrlv_q_256:
11919 case Intrinsic::x86_avx2_psrav_d:
11920 case Intrinsic::x86_avx2_psrav_d_256: {
11923 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11924 case Intrinsic::x86_avx2_psllv_d:
11925 case Intrinsic::x86_avx2_psllv_q:
11926 case Intrinsic::x86_avx2_psllv_d_256:
11927 case Intrinsic::x86_avx2_psllv_q_256:
11930 case Intrinsic::x86_avx2_psrlv_d:
11931 case Intrinsic::x86_avx2_psrlv_q:
11932 case Intrinsic::x86_avx2_psrlv_d_256:
11933 case Intrinsic::x86_avx2_psrlv_q_256:
11936 case Intrinsic::x86_avx2_psrav_d:
11937 case Intrinsic::x86_avx2_psrav_d_256:
11941 return DAG.getNode(Opcode, dl, Op.getValueType(),
11942 Op.getOperand(1), Op.getOperand(2));
11945 case Intrinsic::x86_ssse3_pshuf_b_128:
11946 case Intrinsic::x86_avx2_pshuf_b:
11947 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11948 Op.getOperand(1), Op.getOperand(2));
11950 case Intrinsic::x86_ssse3_psign_b_128:
11951 case Intrinsic::x86_ssse3_psign_w_128:
11952 case Intrinsic::x86_ssse3_psign_d_128:
11953 case Intrinsic::x86_avx2_psign_b:
11954 case Intrinsic::x86_avx2_psign_w:
11955 case Intrinsic::x86_avx2_psign_d:
11956 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11957 Op.getOperand(1), Op.getOperand(2));
11959 case Intrinsic::x86_sse41_insertps:
11960 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11961 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11963 case Intrinsic::x86_avx_vperm2f128_ps_256:
11964 case Intrinsic::x86_avx_vperm2f128_pd_256:
11965 case Intrinsic::x86_avx_vperm2f128_si_256:
11966 case Intrinsic::x86_avx2_vperm2i128:
11967 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11968 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11970 case Intrinsic::x86_avx2_permd:
11971 case Intrinsic::x86_avx2_permps:
11972 // Operands intentionally swapped. Mask is last operand to intrinsic,
11973 // but second operand for node/instruction.
11974 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11975 Op.getOperand(2), Op.getOperand(1));
11977 case Intrinsic::x86_sse_sqrt_ps:
11978 case Intrinsic::x86_sse2_sqrt_pd:
11979 case Intrinsic::x86_avx_sqrt_ps_256:
11980 case Intrinsic::x86_avx_sqrt_pd_256:
11981 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11983 // ptest and testp intrinsics. The intrinsic these come from are designed to
11984 // return an integer value, not just an instruction so lower it to the ptest
11985 // or testp pattern and a setcc for the result.
11986 case Intrinsic::x86_sse41_ptestz:
11987 case Intrinsic::x86_sse41_ptestc:
11988 case Intrinsic::x86_sse41_ptestnzc:
11989 case Intrinsic::x86_avx_ptestz_256:
11990 case Intrinsic::x86_avx_ptestc_256:
11991 case Intrinsic::x86_avx_ptestnzc_256:
11992 case Intrinsic::x86_avx_vtestz_ps:
11993 case Intrinsic::x86_avx_vtestc_ps:
11994 case Intrinsic::x86_avx_vtestnzc_ps:
11995 case Intrinsic::x86_avx_vtestz_pd:
11996 case Intrinsic::x86_avx_vtestc_pd:
11997 case Intrinsic::x86_avx_vtestnzc_pd:
11998 case Intrinsic::x86_avx_vtestz_ps_256:
11999 case Intrinsic::x86_avx_vtestc_ps_256:
12000 case Intrinsic::x86_avx_vtestnzc_ps_256:
12001 case Intrinsic::x86_avx_vtestz_pd_256:
12002 case Intrinsic::x86_avx_vtestc_pd_256:
12003 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12004 bool IsTestPacked = false;
12007 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12008 case Intrinsic::x86_avx_vtestz_ps:
12009 case Intrinsic::x86_avx_vtestz_pd:
12010 case Intrinsic::x86_avx_vtestz_ps_256:
12011 case Intrinsic::x86_avx_vtestz_pd_256:
12012 IsTestPacked = true; // Fallthrough
12013 case Intrinsic::x86_sse41_ptestz:
12014 case Intrinsic::x86_avx_ptestz_256:
12016 X86CC = X86::COND_E;
12018 case Intrinsic::x86_avx_vtestc_ps:
12019 case Intrinsic::x86_avx_vtestc_pd:
12020 case Intrinsic::x86_avx_vtestc_ps_256:
12021 case Intrinsic::x86_avx_vtestc_pd_256:
12022 IsTestPacked = true; // Fallthrough
12023 case Intrinsic::x86_sse41_ptestc:
12024 case Intrinsic::x86_avx_ptestc_256:
12026 X86CC = X86::COND_B;
12028 case Intrinsic::x86_avx_vtestnzc_ps:
12029 case Intrinsic::x86_avx_vtestnzc_pd:
12030 case Intrinsic::x86_avx_vtestnzc_ps_256:
12031 case Intrinsic::x86_avx_vtestnzc_pd_256:
12032 IsTestPacked = true; // Fallthrough
12033 case Intrinsic::x86_sse41_ptestnzc:
12034 case Intrinsic::x86_avx_ptestnzc_256:
12036 X86CC = X86::COND_A;
12040 SDValue LHS = Op.getOperand(1);
12041 SDValue RHS = Op.getOperand(2);
12042 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12043 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12044 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12045 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12046 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12048 case Intrinsic::x86_avx512_kortestz_w:
12049 case Intrinsic::x86_avx512_kortestc_w: {
12050 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12051 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12052 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12053 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12054 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12055 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12056 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12059 // SSE/AVX shift intrinsics
12060 case Intrinsic::x86_sse2_psll_w:
12061 case Intrinsic::x86_sse2_psll_d:
12062 case Intrinsic::x86_sse2_psll_q:
12063 case Intrinsic::x86_avx2_psll_w:
12064 case Intrinsic::x86_avx2_psll_d:
12065 case Intrinsic::x86_avx2_psll_q:
12066 case Intrinsic::x86_sse2_psrl_w:
12067 case Intrinsic::x86_sse2_psrl_d:
12068 case Intrinsic::x86_sse2_psrl_q:
12069 case Intrinsic::x86_avx2_psrl_w:
12070 case Intrinsic::x86_avx2_psrl_d:
12071 case Intrinsic::x86_avx2_psrl_q:
12072 case Intrinsic::x86_sse2_psra_w:
12073 case Intrinsic::x86_sse2_psra_d:
12074 case Intrinsic::x86_avx2_psra_w:
12075 case Intrinsic::x86_avx2_psra_d: {
12078 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12079 case Intrinsic::x86_sse2_psll_w:
12080 case Intrinsic::x86_sse2_psll_d:
12081 case Intrinsic::x86_sse2_psll_q:
12082 case Intrinsic::x86_avx2_psll_w:
12083 case Intrinsic::x86_avx2_psll_d:
12084 case Intrinsic::x86_avx2_psll_q:
12085 Opcode = X86ISD::VSHL;
12087 case Intrinsic::x86_sse2_psrl_w:
12088 case Intrinsic::x86_sse2_psrl_d:
12089 case Intrinsic::x86_sse2_psrl_q:
12090 case Intrinsic::x86_avx2_psrl_w:
12091 case Intrinsic::x86_avx2_psrl_d:
12092 case Intrinsic::x86_avx2_psrl_q:
12093 Opcode = X86ISD::VSRL;
12095 case Intrinsic::x86_sse2_psra_w:
12096 case Intrinsic::x86_sse2_psra_d:
12097 case Intrinsic::x86_avx2_psra_w:
12098 case Intrinsic::x86_avx2_psra_d:
12099 Opcode = X86ISD::VSRA;
12102 return DAG.getNode(Opcode, dl, Op.getValueType(),
12103 Op.getOperand(1), Op.getOperand(2));
12106 // SSE/AVX immediate shift intrinsics
12107 case Intrinsic::x86_sse2_pslli_w:
12108 case Intrinsic::x86_sse2_pslli_d:
12109 case Intrinsic::x86_sse2_pslli_q:
12110 case Intrinsic::x86_avx2_pslli_w:
12111 case Intrinsic::x86_avx2_pslli_d:
12112 case Intrinsic::x86_avx2_pslli_q:
12113 case Intrinsic::x86_sse2_psrli_w:
12114 case Intrinsic::x86_sse2_psrli_d:
12115 case Intrinsic::x86_sse2_psrli_q:
12116 case Intrinsic::x86_avx2_psrli_w:
12117 case Intrinsic::x86_avx2_psrli_d:
12118 case Intrinsic::x86_avx2_psrli_q:
12119 case Intrinsic::x86_sse2_psrai_w:
12120 case Intrinsic::x86_sse2_psrai_d:
12121 case Intrinsic::x86_avx2_psrai_w:
12122 case Intrinsic::x86_avx2_psrai_d: {
12125 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12126 case Intrinsic::x86_sse2_pslli_w:
12127 case Intrinsic::x86_sse2_pslli_d:
12128 case Intrinsic::x86_sse2_pslli_q:
12129 case Intrinsic::x86_avx2_pslli_w:
12130 case Intrinsic::x86_avx2_pslli_d:
12131 case Intrinsic::x86_avx2_pslli_q:
12132 Opcode = X86ISD::VSHLI;
12134 case Intrinsic::x86_sse2_psrli_w:
12135 case Intrinsic::x86_sse2_psrli_d:
12136 case Intrinsic::x86_sse2_psrli_q:
12137 case Intrinsic::x86_avx2_psrli_w:
12138 case Intrinsic::x86_avx2_psrli_d:
12139 case Intrinsic::x86_avx2_psrli_q:
12140 Opcode = X86ISD::VSRLI;
12142 case Intrinsic::x86_sse2_psrai_w:
12143 case Intrinsic::x86_sse2_psrai_d:
12144 case Intrinsic::x86_avx2_psrai_w:
12145 case Intrinsic::x86_avx2_psrai_d:
12146 Opcode = X86ISD::VSRAI;
12149 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12150 Op.getOperand(1), Op.getOperand(2), DAG);
12153 case Intrinsic::x86_sse42_pcmpistria128:
12154 case Intrinsic::x86_sse42_pcmpestria128:
12155 case Intrinsic::x86_sse42_pcmpistric128:
12156 case Intrinsic::x86_sse42_pcmpestric128:
12157 case Intrinsic::x86_sse42_pcmpistrio128:
12158 case Intrinsic::x86_sse42_pcmpestrio128:
12159 case Intrinsic::x86_sse42_pcmpistris128:
12160 case Intrinsic::x86_sse42_pcmpestris128:
12161 case Intrinsic::x86_sse42_pcmpistriz128:
12162 case Intrinsic::x86_sse42_pcmpestriz128: {
12166 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12167 case Intrinsic::x86_sse42_pcmpistria128:
12168 Opcode = X86ISD::PCMPISTRI;
12169 X86CC = X86::COND_A;
12171 case Intrinsic::x86_sse42_pcmpestria128:
12172 Opcode = X86ISD::PCMPESTRI;
12173 X86CC = X86::COND_A;
12175 case Intrinsic::x86_sse42_pcmpistric128:
12176 Opcode = X86ISD::PCMPISTRI;
12177 X86CC = X86::COND_B;
12179 case Intrinsic::x86_sse42_pcmpestric128:
12180 Opcode = X86ISD::PCMPESTRI;
12181 X86CC = X86::COND_B;
12183 case Intrinsic::x86_sse42_pcmpistrio128:
12184 Opcode = X86ISD::PCMPISTRI;
12185 X86CC = X86::COND_O;
12187 case Intrinsic::x86_sse42_pcmpestrio128:
12188 Opcode = X86ISD::PCMPESTRI;
12189 X86CC = X86::COND_O;
12191 case Intrinsic::x86_sse42_pcmpistris128:
12192 Opcode = X86ISD::PCMPISTRI;
12193 X86CC = X86::COND_S;
12195 case Intrinsic::x86_sse42_pcmpestris128:
12196 Opcode = X86ISD::PCMPESTRI;
12197 X86CC = X86::COND_S;
12199 case Intrinsic::x86_sse42_pcmpistriz128:
12200 Opcode = X86ISD::PCMPISTRI;
12201 X86CC = X86::COND_E;
12203 case Intrinsic::x86_sse42_pcmpestriz128:
12204 Opcode = X86ISD::PCMPESTRI;
12205 X86CC = X86::COND_E;
12208 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12209 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12210 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12211 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12212 DAG.getConstant(X86CC, MVT::i8),
12213 SDValue(PCMP.getNode(), 1));
12214 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12217 case Intrinsic::x86_sse42_pcmpistri128:
12218 case Intrinsic::x86_sse42_pcmpestri128: {
12220 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12221 Opcode = X86ISD::PCMPISTRI;
12223 Opcode = X86ISD::PCMPESTRI;
12225 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12226 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12227 return DAG.getNode(Opcode, dl, VTs, NewOps);
12229 case Intrinsic::x86_fma_vfmadd_ps:
12230 case Intrinsic::x86_fma_vfmadd_pd:
12231 case Intrinsic::x86_fma_vfmsub_ps:
12232 case Intrinsic::x86_fma_vfmsub_pd:
12233 case Intrinsic::x86_fma_vfnmadd_ps:
12234 case Intrinsic::x86_fma_vfnmadd_pd:
12235 case Intrinsic::x86_fma_vfnmsub_ps:
12236 case Intrinsic::x86_fma_vfnmsub_pd:
12237 case Intrinsic::x86_fma_vfmaddsub_ps:
12238 case Intrinsic::x86_fma_vfmaddsub_pd:
12239 case Intrinsic::x86_fma_vfmsubadd_ps:
12240 case Intrinsic::x86_fma_vfmsubadd_pd:
12241 case Intrinsic::x86_fma_vfmadd_ps_256:
12242 case Intrinsic::x86_fma_vfmadd_pd_256:
12243 case Intrinsic::x86_fma_vfmsub_ps_256:
12244 case Intrinsic::x86_fma_vfmsub_pd_256:
12245 case Intrinsic::x86_fma_vfnmadd_ps_256:
12246 case Intrinsic::x86_fma_vfnmadd_pd_256:
12247 case Intrinsic::x86_fma_vfnmsub_ps_256:
12248 case Intrinsic::x86_fma_vfnmsub_pd_256:
12249 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12250 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12251 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12252 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12253 case Intrinsic::x86_fma_vfmadd_ps_512:
12254 case Intrinsic::x86_fma_vfmadd_pd_512:
12255 case Intrinsic::x86_fma_vfmsub_ps_512:
12256 case Intrinsic::x86_fma_vfmsub_pd_512:
12257 case Intrinsic::x86_fma_vfnmadd_ps_512:
12258 case Intrinsic::x86_fma_vfnmadd_pd_512:
12259 case Intrinsic::x86_fma_vfnmsub_ps_512:
12260 case Intrinsic::x86_fma_vfnmsub_pd_512:
12261 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12262 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12263 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12264 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12267 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12268 case Intrinsic::x86_fma_vfmadd_ps:
12269 case Intrinsic::x86_fma_vfmadd_pd:
12270 case Intrinsic::x86_fma_vfmadd_ps_256:
12271 case Intrinsic::x86_fma_vfmadd_pd_256:
12272 case Intrinsic::x86_fma_vfmadd_ps_512:
12273 case Intrinsic::x86_fma_vfmadd_pd_512:
12274 Opc = X86ISD::FMADD;
12276 case Intrinsic::x86_fma_vfmsub_ps:
12277 case Intrinsic::x86_fma_vfmsub_pd:
12278 case Intrinsic::x86_fma_vfmsub_ps_256:
12279 case Intrinsic::x86_fma_vfmsub_pd_256:
12280 case Intrinsic::x86_fma_vfmsub_ps_512:
12281 case Intrinsic::x86_fma_vfmsub_pd_512:
12282 Opc = X86ISD::FMSUB;
12284 case Intrinsic::x86_fma_vfnmadd_ps:
12285 case Intrinsic::x86_fma_vfnmadd_pd:
12286 case Intrinsic::x86_fma_vfnmadd_ps_256:
12287 case Intrinsic::x86_fma_vfnmadd_pd_256:
12288 case Intrinsic::x86_fma_vfnmadd_ps_512:
12289 case Intrinsic::x86_fma_vfnmadd_pd_512:
12290 Opc = X86ISD::FNMADD;
12292 case Intrinsic::x86_fma_vfnmsub_ps:
12293 case Intrinsic::x86_fma_vfnmsub_pd:
12294 case Intrinsic::x86_fma_vfnmsub_ps_256:
12295 case Intrinsic::x86_fma_vfnmsub_pd_256:
12296 case Intrinsic::x86_fma_vfnmsub_ps_512:
12297 case Intrinsic::x86_fma_vfnmsub_pd_512:
12298 Opc = X86ISD::FNMSUB;
12300 case Intrinsic::x86_fma_vfmaddsub_ps:
12301 case Intrinsic::x86_fma_vfmaddsub_pd:
12302 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12303 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12304 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12305 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12306 Opc = X86ISD::FMADDSUB;
12308 case Intrinsic::x86_fma_vfmsubadd_ps:
12309 case Intrinsic::x86_fma_vfmsubadd_pd:
12310 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12311 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12312 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12313 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12314 Opc = X86ISD::FMSUBADD;
12318 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12319 Op.getOperand(2), Op.getOperand(3));
12324 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12325 SDValue Base, SDValue Index,
12326 SDValue ScaleOp, SDValue Chain,
12327 const X86Subtarget * Subtarget) {
12329 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12330 assert(C && "Invalid scale type");
12331 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12332 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12333 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12334 Index.getSimpleValueType().getVectorNumElements());
12335 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12336 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12337 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12338 SDValue Segment = DAG.getRegister(0, MVT::i32);
12339 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12340 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12341 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12342 return DAG.getMergeValues(RetOps, dl);
12345 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12346 SDValue Src, SDValue Mask, SDValue Base,
12347 SDValue Index, SDValue ScaleOp, SDValue Chain,
12348 const X86Subtarget * Subtarget) {
12350 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12351 assert(C && "Invalid scale type");
12352 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12353 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12354 Index.getSimpleValueType().getVectorNumElements());
12355 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12356 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12357 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12358 SDValue Segment = DAG.getRegister(0, MVT::i32);
12359 if (Src.getOpcode() == ISD::UNDEF)
12360 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12361 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12362 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12363 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12364 return DAG.getMergeValues(RetOps, dl);
12367 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12368 SDValue Src, SDValue Base, SDValue Index,
12369 SDValue ScaleOp, SDValue Chain) {
12371 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12372 assert(C && "Invalid scale type");
12373 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12374 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12375 SDValue Segment = DAG.getRegister(0, MVT::i32);
12376 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12377 Index.getSimpleValueType().getVectorNumElements());
12378 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12379 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12380 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12381 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12382 return SDValue(Res, 1);
12385 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12386 SDValue Src, SDValue Mask, SDValue Base,
12387 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12389 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12390 assert(C && "Invalid scale type");
12391 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12392 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12393 SDValue Segment = DAG.getRegister(0, MVT::i32);
12394 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12395 Index.getSimpleValueType().getVectorNumElements());
12396 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12397 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12398 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12399 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12400 return SDValue(Res, 1);
12403 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12404 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12405 // also used to custom lower READCYCLECOUNTER nodes.
12406 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12407 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12408 SmallVectorImpl<SDValue> &Results) {
12409 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12410 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12413 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12414 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12415 // and the EAX register is loaded with the low-order 32 bits.
12416 if (Subtarget->is64Bit()) {
12417 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12418 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12421 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12422 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12425 SDValue Chain = HI.getValue(1);
12427 if (Opcode == X86ISD::RDTSCP_DAG) {
12428 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12430 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12431 // the ECX register. Add 'ecx' explicitly to the chain.
12432 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12434 // Explicitly store the content of ECX at the location passed in input
12435 // to the 'rdtscp' intrinsic.
12436 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12437 MachinePointerInfo(), false, false, 0);
12440 if (Subtarget->is64Bit()) {
12441 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12442 // the EAX register is loaded with the low-order 32 bits.
12443 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12444 DAG.getConstant(32, MVT::i8));
12445 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12446 Results.push_back(Chain);
12450 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12451 SDValue Ops[] = { LO, HI };
12452 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12453 Results.push_back(Pair);
12454 Results.push_back(Chain);
12457 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12458 SelectionDAG &DAG) {
12459 SmallVector<SDValue, 2> Results;
12461 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12463 return DAG.getMergeValues(Results, DL);
12466 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12467 SelectionDAG &DAG) {
12469 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12471 default: return SDValue(); // Don't custom lower most intrinsics.
12473 // RDRAND/RDSEED intrinsics.
12474 case Intrinsic::x86_rdrand_16:
12475 case Intrinsic::x86_rdrand_32:
12476 case Intrinsic::x86_rdrand_64:
12477 case Intrinsic::x86_rdseed_16:
12478 case Intrinsic::x86_rdseed_32:
12479 case Intrinsic::x86_rdseed_64: {
12480 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12481 IntNo == Intrinsic::x86_rdseed_32 ||
12482 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12484 // Emit the node with the right value type.
12485 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12486 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12488 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12489 // Otherwise return the value from Rand, which is always 0, casted to i32.
12490 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12491 DAG.getConstant(1, Op->getValueType(1)),
12492 DAG.getConstant(X86::COND_B, MVT::i32),
12493 SDValue(Result.getNode(), 1) };
12494 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12495 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12498 // Return { result, isValid, chain }.
12499 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12500 SDValue(Result.getNode(), 2));
12502 //int_gather(index, base, scale);
12503 case Intrinsic::x86_avx512_gather_qpd_512:
12504 case Intrinsic::x86_avx512_gather_qps_512:
12505 case Intrinsic::x86_avx512_gather_dpd_512:
12506 case Intrinsic::x86_avx512_gather_qpi_512:
12507 case Intrinsic::x86_avx512_gather_qpq_512:
12508 case Intrinsic::x86_avx512_gather_dpq_512:
12509 case Intrinsic::x86_avx512_gather_dps_512:
12510 case Intrinsic::x86_avx512_gather_dpi_512: {
12513 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12514 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12515 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12516 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12517 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12518 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12519 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12520 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12521 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12523 SDValue Chain = Op.getOperand(0);
12524 SDValue Index = Op.getOperand(2);
12525 SDValue Base = Op.getOperand(3);
12526 SDValue Scale = Op.getOperand(4);
12527 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12529 //int_gather_mask(v1, mask, index, base, scale);
12530 case Intrinsic::x86_avx512_gather_qps_mask_512:
12531 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12532 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12533 case Intrinsic::x86_avx512_gather_dps_mask_512:
12534 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12535 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12536 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12537 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12540 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12541 case Intrinsic::x86_avx512_gather_qps_mask_512:
12542 Opc = X86::VGATHERQPSZrm; break;
12543 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12544 Opc = X86::VGATHERQPDZrm; break;
12545 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12546 Opc = X86::VGATHERDPDZrm; break;
12547 case Intrinsic::x86_avx512_gather_dps_mask_512:
12548 Opc = X86::VGATHERDPSZrm; break;
12549 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12550 Opc = X86::VPGATHERQDZrm; break;
12551 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12552 Opc = X86::VPGATHERQQZrm; break;
12553 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12554 Opc = X86::VPGATHERDDZrm; break;
12555 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12556 Opc = X86::VPGATHERDQZrm; break;
12558 SDValue Chain = Op.getOperand(0);
12559 SDValue Src = Op.getOperand(2);
12560 SDValue Mask = Op.getOperand(3);
12561 SDValue Index = Op.getOperand(4);
12562 SDValue Base = Op.getOperand(5);
12563 SDValue Scale = Op.getOperand(6);
12564 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12567 //int_scatter(base, index, v1, scale);
12568 case Intrinsic::x86_avx512_scatter_qpd_512:
12569 case Intrinsic::x86_avx512_scatter_qps_512:
12570 case Intrinsic::x86_avx512_scatter_dpd_512:
12571 case Intrinsic::x86_avx512_scatter_qpi_512:
12572 case Intrinsic::x86_avx512_scatter_qpq_512:
12573 case Intrinsic::x86_avx512_scatter_dpq_512:
12574 case Intrinsic::x86_avx512_scatter_dps_512:
12575 case Intrinsic::x86_avx512_scatter_dpi_512: {
12578 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12579 case Intrinsic::x86_avx512_scatter_qpd_512:
12580 Opc = X86::VSCATTERQPDZmr; break;
12581 case Intrinsic::x86_avx512_scatter_qps_512:
12582 Opc = X86::VSCATTERQPSZmr; break;
12583 case Intrinsic::x86_avx512_scatter_dpd_512:
12584 Opc = X86::VSCATTERDPDZmr; break;
12585 case Intrinsic::x86_avx512_scatter_dps_512:
12586 Opc = X86::VSCATTERDPSZmr; break;
12587 case Intrinsic::x86_avx512_scatter_qpi_512:
12588 Opc = X86::VPSCATTERQDZmr; break;
12589 case Intrinsic::x86_avx512_scatter_qpq_512:
12590 Opc = X86::VPSCATTERQQZmr; break;
12591 case Intrinsic::x86_avx512_scatter_dpq_512:
12592 Opc = X86::VPSCATTERDQZmr; break;
12593 case Intrinsic::x86_avx512_scatter_dpi_512:
12594 Opc = X86::VPSCATTERDDZmr; break;
12596 SDValue Chain = Op.getOperand(0);
12597 SDValue Base = Op.getOperand(2);
12598 SDValue Index = Op.getOperand(3);
12599 SDValue Src = Op.getOperand(4);
12600 SDValue Scale = Op.getOperand(5);
12601 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12603 //int_scatter_mask(base, mask, index, v1, scale);
12604 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12605 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12606 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12607 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12608 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12609 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12610 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12611 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12614 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12615 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12616 Opc = X86::VSCATTERQPDZmr; break;
12617 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12618 Opc = X86::VSCATTERQPSZmr; break;
12619 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12620 Opc = X86::VSCATTERDPDZmr; break;
12621 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12622 Opc = X86::VSCATTERDPSZmr; break;
12623 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12624 Opc = X86::VPSCATTERQDZmr; break;
12625 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12626 Opc = X86::VPSCATTERQQZmr; break;
12627 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12628 Opc = X86::VPSCATTERDQZmr; break;
12629 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12630 Opc = X86::VPSCATTERDDZmr; break;
12632 SDValue Chain = Op.getOperand(0);
12633 SDValue Base = Op.getOperand(2);
12634 SDValue Mask = Op.getOperand(3);
12635 SDValue Index = Op.getOperand(4);
12636 SDValue Src = Op.getOperand(5);
12637 SDValue Scale = Op.getOperand(6);
12638 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12640 // Read Time Stamp Counter (RDTSC).
12641 case Intrinsic::x86_rdtsc:
12642 // Read Time Stamp Counter and Processor ID (RDTSCP).
12643 case Intrinsic::x86_rdtscp: {
12646 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12647 case Intrinsic::x86_rdtsc:
12648 Opc = X86ISD::RDTSC_DAG; break;
12649 case Intrinsic::x86_rdtscp:
12650 Opc = X86ISD::RDTSCP_DAG; break;
12652 SmallVector<SDValue, 2> Results;
12653 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12654 return DAG.getMergeValues(Results, dl);
12656 // XTEST intrinsics.
12657 case Intrinsic::x86_xtest: {
12658 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12659 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12660 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12661 DAG.getConstant(X86::COND_NE, MVT::i8),
12663 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12664 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12665 Ret, SDValue(InTrans.getNode(), 1));
12670 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12671 SelectionDAG &DAG) const {
12672 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12673 MFI->setReturnAddressIsTaken(true);
12675 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12678 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12680 EVT PtrVT = getPointerTy();
12683 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12684 const X86RegisterInfo *RegInfo =
12685 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12686 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12687 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12688 DAG.getNode(ISD::ADD, dl, PtrVT,
12689 FrameAddr, Offset),
12690 MachinePointerInfo(), false, false, false, 0);
12693 // Just load the return address.
12694 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12695 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12696 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12699 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12700 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12701 MFI->setFrameAddressIsTaken(true);
12703 EVT VT = Op.getValueType();
12704 SDLoc dl(Op); // FIXME probably not meaningful
12705 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12706 const X86RegisterInfo *RegInfo =
12707 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12708 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12709 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12710 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12711 "Invalid Frame Register!");
12712 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12714 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12715 MachinePointerInfo(),
12716 false, false, false, 0);
12720 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12721 SelectionDAG &DAG) const {
12722 const X86RegisterInfo *RegInfo =
12723 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12724 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12727 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12728 SDValue Chain = Op.getOperand(0);
12729 SDValue Offset = Op.getOperand(1);
12730 SDValue Handler = Op.getOperand(2);
12733 EVT PtrVT = getPointerTy();
12734 const X86RegisterInfo *RegInfo =
12735 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12736 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12737 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12738 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12739 "Invalid Frame Register!");
12740 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12741 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12743 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12744 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12745 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12746 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12748 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12750 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12751 DAG.getRegister(StoreAddrReg, PtrVT));
12754 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12755 SelectionDAG &DAG) const {
12757 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12758 DAG.getVTList(MVT::i32, MVT::Other),
12759 Op.getOperand(0), Op.getOperand(1));
12762 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12763 SelectionDAG &DAG) const {
12765 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12766 Op.getOperand(0), Op.getOperand(1));
12769 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12770 return Op.getOperand(0);
12773 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12774 SelectionDAG &DAG) const {
12775 SDValue Root = Op.getOperand(0);
12776 SDValue Trmp = Op.getOperand(1); // trampoline
12777 SDValue FPtr = Op.getOperand(2); // nested function
12778 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12781 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12782 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12784 if (Subtarget->is64Bit()) {
12785 SDValue OutChains[6];
12787 // Large code-model.
12788 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12789 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12791 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12792 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12794 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12796 // Load the pointer to the nested function into R11.
12797 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12798 SDValue Addr = Trmp;
12799 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12800 Addr, MachinePointerInfo(TrmpAddr),
12803 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12804 DAG.getConstant(2, MVT::i64));
12805 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12806 MachinePointerInfo(TrmpAddr, 2),
12809 // Load the 'nest' parameter value into R10.
12810 // R10 is specified in X86CallingConv.td
12811 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12812 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12813 DAG.getConstant(10, MVT::i64));
12814 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12815 Addr, MachinePointerInfo(TrmpAddr, 10),
12818 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12819 DAG.getConstant(12, MVT::i64));
12820 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12821 MachinePointerInfo(TrmpAddr, 12),
12824 // Jump to the nested function.
12825 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12826 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12827 DAG.getConstant(20, MVT::i64));
12828 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12829 Addr, MachinePointerInfo(TrmpAddr, 20),
12832 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12833 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12834 DAG.getConstant(22, MVT::i64));
12835 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12836 MachinePointerInfo(TrmpAddr, 22),
12839 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12841 const Function *Func =
12842 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12843 CallingConv::ID CC = Func->getCallingConv();
12848 llvm_unreachable("Unsupported calling convention");
12849 case CallingConv::C:
12850 case CallingConv::X86_StdCall: {
12851 // Pass 'nest' parameter in ECX.
12852 // Must be kept in sync with X86CallingConv.td
12853 NestReg = X86::ECX;
12855 // Check that ECX wasn't needed by an 'inreg' parameter.
12856 FunctionType *FTy = Func->getFunctionType();
12857 const AttributeSet &Attrs = Func->getAttributes();
12859 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12860 unsigned InRegCount = 0;
12863 for (FunctionType::param_iterator I = FTy->param_begin(),
12864 E = FTy->param_end(); I != E; ++I, ++Idx)
12865 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12866 // FIXME: should only count parameters that are lowered to integers.
12867 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12869 if (InRegCount > 2) {
12870 report_fatal_error("Nest register in use - reduce number of inreg"
12876 case CallingConv::X86_FastCall:
12877 case CallingConv::X86_ThisCall:
12878 case CallingConv::Fast:
12879 // Pass 'nest' parameter in EAX.
12880 // Must be kept in sync with X86CallingConv.td
12881 NestReg = X86::EAX;
12885 SDValue OutChains[4];
12886 SDValue Addr, Disp;
12888 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12889 DAG.getConstant(10, MVT::i32));
12890 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12892 // This is storing the opcode for MOV32ri.
12893 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12894 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12895 OutChains[0] = DAG.getStore(Root, dl,
12896 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12897 Trmp, MachinePointerInfo(TrmpAddr),
12900 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12901 DAG.getConstant(1, MVT::i32));
12902 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12903 MachinePointerInfo(TrmpAddr, 1),
12906 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12907 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12908 DAG.getConstant(5, MVT::i32));
12909 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12910 MachinePointerInfo(TrmpAddr, 5),
12913 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12914 DAG.getConstant(6, MVT::i32));
12915 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12916 MachinePointerInfo(TrmpAddr, 6),
12919 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12923 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12924 SelectionDAG &DAG) const {
12926 The rounding mode is in bits 11:10 of FPSR, and has the following
12928 00 Round to nearest
12933 FLT_ROUNDS, on the other hand, expects the following:
12940 To perform the conversion, we do:
12941 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12944 MachineFunction &MF = DAG.getMachineFunction();
12945 const TargetMachine &TM = MF.getTarget();
12946 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12947 unsigned StackAlignment = TFI.getStackAlignment();
12948 MVT VT = Op.getSimpleValueType();
12951 // Save FP Control Word to stack slot
12952 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12953 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12955 MachineMemOperand *MMO =
12956 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12957 MachineMemOperand::MOStore, 2, 2);
12959 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12960 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12961 DAG.getVTList(MVT::Other),
12962 Ops, MVT::i16, MMO);
12964 // Load FP Control Word from stack slot
12965 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12966 MachinePointerInfo(), false, false, false, 0);
12968 // Transform as necessary
12970 DAG.getNode(ISD::SRL, DL, MVT::i16,
12971 DAG.getNode(ISD::AND, DL, MVT::i16,
12972 CWD, DAG.getConstant(0x800, MVT::i16)),
12973 DAG.getConstant(11, MVT::i8));
12975 DAG.getNode(ISD::SRL, DL, MVT::i16,
12976 DAG.getNode(ISD::AND, DL, MVT::i16,
12977 CWD, DAG.getConstant(0x400, MVT::i16)),
12978 DAG.getConstant(9, MVT::i8));
12981 DAG.getNode(ISD::AND, DL, MVT::i16,
12982 DAG.getNode(ISD::ADD, DL, MVT::i16,
12983 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12984 DAG.getConstant(1, MVT::i16)),
12985 DAG.getConstant(3, MVT::i16));
12987 return DAG.getNode((VT.getSizeInBits() < 16 ?
12988 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12991 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12992 MVT VT = Op.getSimpleValueType();
12994 unsigned NumBits = VT.getSizeInBits();
12997 Op = Op.getOperand(0);
12998 if (VT == MVT::i8) {
12999 // Zero extend to i32 since there is not an i8 bsr.
13001 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13004 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13005 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13006 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13008 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13011 DAG.getConstant(NumBits+NumBits-1, OpVT),
13012 DAG.getConstant(X86::COND_E, MVT::i8),
13015 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13017 // Finally xor with NumBits-1.
13018 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13021 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13025 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13026 MVT VT = Op.getSimpleValueType();
13028 unsigned NumBits = VT.getSizeInBits();
13031 Op = Op.getOperand(0);
13032 if (VT == MVT::i8) {
13033 // Zero extend to i32 since there is not an i8 bsr.
13035 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13038 // Issue a bsr (scan bits in reverse).
13039 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13040 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13042 // And xor with NumBits-1.
13043 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13046 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13050 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13051 MVT VT = Op.getSimpleValueType();
13052 unsigned NumBits = VT.getSizeInBits();
13054 Op = Op.getOperand(0);
13056 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13057 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13058 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13060 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13063 DAG.getConstant(NumBits, VT),
13064 DAG.getConstant(X86::COND_E, MVT::i8),
13067 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13070 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13071 // ones, and then concatenate the result back.
13072 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13073 MVT VT = Op.getSimpleValueType();
13075 assert(VT.is256BitVector() && VT.isInteger() &&
13076 "Unsupported value type for operation");
13078 unsigned NumElems = VT.getVectorNumElements();
13081 // Extract the LHS vectors
13082 SDValue LHS = Op.getOperand(0);
13083 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13084 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13086 // Extract the RHS vectors
13087 SDValue RHS = Op.getOperand(1);
13088 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13089 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13091 MVT EltVT = VT.getVectorElementType();
13092 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13094 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13095 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13096 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13099 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13100 assert(Op.getSimpleValueType().is256BitVector() &&
13101 Op.getSimpleValueType().isInteger() &&
13102 "Only handle AVX 256-bit vector integer operation");
13103 return Lower256IntArith(Op, DAG);
13106 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13107 assert(Op.getSimpleValueType().is256BitVector() &&
13108 Op.getSimpleValueType().isInteger() &&
13109 "Only handle AVX 256-bit vector integer operation");
13110 return Lower256IntArith(Op, DAG);
13113 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13114 SelectionDAG &DAG) {
13116 MVT VT = Op.getSimpleValueType();
13118 // Decompose 256-bit ops into smaller 128-bit ops.
13119 if (VT.is256BitVector() && !Subtarget->hasInt256())
13120 return Lower256IntArith(Op, DAG);
13122 SDValue A = Op.getOperand(0);
13123 SDValue B = Op.getOperand(1);
13125 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13126 if (VT == MVT::v4i32) {
13127 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13128 "Should not custom lower when pmuldq is available!");
13130 // Extract the odd parts.
13131 static const int UnpackMask[] = { 1, -1, 3, -1 };
13132 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13133 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13135 // Multiply the even parts.
13136 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13137 // Now multiply odd parts.
13138 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13140 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13141 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13143 // Merge the two vectors back together with a shuffle. This expands into 2
13145 static const int ShufMask[] = { 0, 4, 2, 6 };
13146 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13149 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13150 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13152 // Ahi = psrlqi(a, 32);
13153 // Bhi = psrlqi(b, 32);
13155 // AloBlo = pmuludq(a, b);
13156 // AloBhi = pmuludq(a, Bhi);
13157 // AhiBlo = pmuludq(Ahi, b);
13159 // AloBhi = psllqi(AloBhi, 32);
13160 // AhiBlo = psllqi(AhiBlo, 32);
13161 // return AloBlo + AloBhi + AhiBlo;
13163 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13164 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13166 // Bit cast to 32-bit vectors for MULUDQ
13167 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13168 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13169 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13170 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13171 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13172 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13174 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13175 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13176 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13178 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13179 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13181 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13182 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13185 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13186 SelectionDAG &DAG) {
13187 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13188 EVT VT = Op0.getValueType();
13191 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13192 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13194 // Get the high parts.
13195 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13196 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13197 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13199 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13201 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13202 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13204 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13205 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13206 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13207 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13208 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13210 // Shuffle it back into the right order.
13211 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13212 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13213 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13214 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13216 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13217 // unsigned multiply.
13218 if (IsSigned && !Subtarget->hasSSE41()) {
13220 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13221 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13222 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13223 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13224 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13226 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13227 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13230 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13233 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13234 const X86Subtarget *Subtarget) {
13235 MVT VT = Op.getSimpleValueType();
13237 SDValue R = Op.getOperand(0);
13238 SDValue Amt = Op.getOperand(1);
13240 // Optimize shl/srl/sra with constant shift amount.
13241 if (isSplatVector(Amt.getNode())) {
13242 SDValue SclrAmt = Amt->getOperand(0);
13243 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13244 uint64_t ShiftAmt = C->getZExtValue();
13246 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13247 (Subtarget->hasInt256() &&
13248 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13249 (Subtarget->hasAVX512() &&
13250 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13251 if (Op.getOpcode() == ISD::SHL)
13252 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13254 if (Op.getOpcode() == ISD::SRL)
13255 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13257 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13258 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13262 if (VT == MVT::v16i8) {
13263 if (Op.getOpcode() == ISD::SHL) {
13264 // Make a large shift.
13265 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13266 MVT::v8i16, R, ShiftAmt,
13268 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13269 // Zero out the rightmost bits.
13270 SmallVector<SDValue, 16> V(16,
13271 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13273 return DAG.getNode(ISD::AND, dl, VT, SHL,
13274 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13276 if (Op.getOpcode() == ISD::SRL) {
13277 // Make a large shift.
13278 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13279 MVT::v8i16, R, ShiftAmt,
13281 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13282 // Zero out the leftmost bits.
13283 SmallVector<SDValue, 16> V(16,
13284 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13286 return DAG.getNode(ISD::AND, dl, VT, SRL,
13287 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13289 if (Op.getOpcode() == ISD::SRA) {
13290 if (ShiftAmt == 7) {
13291 // R s>> 7 === R s< 0
13292 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13293 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13296 // R s>> a === ((R u>> a) ^ m) - m
13297 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13298 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13300 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13301 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13302 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13305 llvm_unreachable("Unknown shift opcode.");
13308 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13309 if (Op.getOpcode() == ISD::SHL) {
13310 // Make a large shift.
13311 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13312 MVT::v16i16, R, ShiftAmt,
13314 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13315 // Zero out the rightmost bits.
13316 SmallVector<SDValue, 32> V(32,
13317 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13319 return DAG.getNode(ISD::AND, dl, VT, SHL,
13320 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13322 if (Op.getOpcode() == ISD::SRL) {
13323 // Make a large shift.
13324 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13325 MVT::v16i16, R, ShiftAmt,
13327 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13328 // Zero out the leftmost bits.
13329 SmallVector<SDValue, 32> V(32,
13330 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13332 return DAG.getNode(ISD::AND, dl, VT, SRL,
13333 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13335 if (Op.getOpcode() == ISD::SRA) {
13336 if (ShiftAmt == 7) {
13337 // R s>> 7 === R s< 0
13338 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13339 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13342 // R s>> a === ((R u>> a) ^ m) - m
13343 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13344 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13346 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13347 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13348 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13351 llvm_unreachable("Unknown shift opcode.");
13356 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13357 if (!Subtarget->is64Bit() &&
13358 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13359 Amt.getOpcode() == ISD::BITCAST &&
13360 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13361 Amt = Amt.getOperand(0);
13362 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13363 VT.getVectorNumElements();
13364 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13365 uint64_t ShiftAmt = 0;
13366 for (unsigned i = 0; i != Ratio; ++i) {
13367 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13371 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13373 // Check remaining shift amounts.
13374 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13375 uint64_t ShAmt = 0;
13376 for (unsigned j = 0; j != Ratio; ++j) {
13377 ConstantSDNode *C =
13378 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13382 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13384 if (ShAmt != ShiftAmt)
13387 switch (Op.getOpcode()) {
13389 llvm_unreachable("Unknown shift opcode!");
13391 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13394 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13397 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13405 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13406 const X86Subtarget* Subtarget) {
13407 MVT VT = Op.getSimpleValueType();
13409 SDValue R = Op.getOperand(0);
13410 SDValue Amt = Op.getOperand(1);
13412 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13413 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13414 (Subtarget->hasInt256() &&
13415 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13416 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13417 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13419 EVT EltVT = VT.getVectorElementType();
13421 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13422 unsigned NumElts = VT.getVectorNumElements();
13424 for (i = 0; i != NumElts; ++i) {
13425 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13429 for (j = i; j != NumElts; ++j) {
13430 SDValue Arg = Amt.getOperand(j);
13431 if (Arg.getOpcode() == ISD::UNDEF) continue;
13432 if (Arg != Amt.getOperand(i))
13435 if (i != NumElts && j == NumElts)
13436 BaseShAmt = Amt.getOperand(i);
13438 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13439 Amt = Amt.getOperand(0);
13440 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13441 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13442 SDValue InVec = Amt.getOperand(0);
13443 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13444 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13446 for (; i != NumElts; ++i) {
13447 SDValue Arg = InVec.getOperand(i);
13448 if (Arg.getOpcode() == ISD::UNDEF) continue;
13452 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13453 if (ConstantSDNode *C =
13454 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13455 unsigned SplatIdx =
13456 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13457 if (C->getZExtValue() == SplatIdx)
13458 BaseShAmt = InVec.getOperand(1);
13461 if (!BaseShAmt.getNode())
13462 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13463 DAG.getIntPtrConstant(0));
13467 if (BaseShAmt.getNode()) {
13468 if (EltVT.bitsGT(MVT::i32))
13469 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13470 else if (EltVT.bitsLT(MVT::i32))
13471 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13473 switch (Op.getOpcode()) {
13475 llvm_unreachable("Unknown shift opcode!");
13477 switch (VT.SimpleTy) {
13478 default: return SDValue();
13487 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13490 switch (VT.SimpleTy) {
13491 default: return SDValue();
13498 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13501 switch (VT.SimpleTy) {
13502 default: return SDValue();
13511 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13517 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13518 if (!Subtarget->is64Bit() &&
13519 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13520 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13521 Amt.getOpcode() == ISD::BITCAST &&
13522 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13523 Amt = Amt.getOperand(0);
13524 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13525 VT.getVectorNumElements();
13526 std::vector<SDValue> Vals(Ratio);
13527 for (unsigned i = 0; i != Ratio; ++i)
13528 Vals[i] = Amt.getOperand(i);
13529 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13530 for (unsigned j = 0; j != Ratio; ++j)
13531 if (Vals[j] != Amt.getOperand(i + j))
13534 switch (Op.getOpcode()) {
13536 llvm_unreachable("Unknown shift opcode!");
13538 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13540 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13542 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13549 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13550 SelectionDAG &DAG) {
13552 MVT VT = Op.getSimpleValueType();
13554 SDValue R = Op.getOperand(0);
13555 SDValue Amt = Op.getOperand(1);
13558 if (!Subtarget->hasSSE2())
13561 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13565 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13569 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13571 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13572 if (Subtarget->hasInt256()) {
13573 if (Op.getOpcode() == ISD::SRL &&
13574 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13575 VT == MVT::v4i64 || VT == MVT::v8i32))
13577 if (Op.getOpcode() == ISD::SHL &&
13578 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13579 VT == MVT::v4i64 || VT == MVT::v8i32))
13581 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13585 // If possible, lower this packed shift into a vector multiply instead of
13586 // expanding it into a sequence of scalar shifts.
13587 // Do this only if the vector shift count is a constant build_vector.
13588 if (Op.getOpcode() == ISD::SHL &&
13589 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13590 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13591 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13592 SmallVector<SDValue, 8> Elts;
13593 EVT SVT = VT.getScalarType();
13594 unsigned SVTBits = SVT.getSizeInBits();
13595 const APInt &One = APInt(SVTBits, 1);
13596 unsigned NumElems = VT.getVectorNumElements();
13598 for (unsigned i=0; i !=NumElems; ++i) {
13599 SDValue Op = Amt->getOperand(i);
13600 if (Op->getOpcode() == ISD::UNDEF) {
13601 Elts.push_back(Op);
13605 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13606 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13607 uint64_t ShAmt = C.getZExtValue();
13608 if (ShAmt >= SVTBits) {
13609 Elts.push_back(DAG.getUNDEF(SVT));
13612 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13614 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13615 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13618 // Lower SHL with variable shift amount.
13619 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13620 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13622 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13623 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13624 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13625 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13628 // If possible, lower this shift as a sequence of two shifts by
13629 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13631 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13633 // Could be rewritten as:
13634 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13636 // The advantage is that the two shifts from the example would be
13637 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13638 // the vector shift into four scalar shifts plus four pairs of vector
13640 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13641 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13642 unsigned TargetOpcode = X86ISD::MOVSS;
13643 bool CanBeSimplified;
13644 // The splat value for the first packed shift (the 'X' from the example).
13645 SDValue Amt1 = Amt->getOperand(0);
13646 // The splat value for the second packed shift (the 'Y' from the example).
13647 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13648 Amt->getOperand(2);
13650 // See if it is possible to replace this node with a sequence of
13651 // two shifts followed by a MOVSS/MOVSD
13652 if (VT == MVT::v4i32) {
13653 // Check if it is legal to use a MOVSS.
13654 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13655 Amt2 == Amt->getOperand(3);
13656 if (!CanBeSimplified) {
13657 // Otherwise, check if we can still simplify this node using a MOVSD.
13658 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13659 Amt->getOperand(2) == Amt->getOperand(3);
13660 TargetOpcode = X86ISD::MOVSD;
13661 Amt2 = Amt->getOperand(2);
13664 // Do similar checks for the case where the machine value type
13666 CanBeSimplified = Amt1 == Amt->getOperand(1);
13667 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13668 CanBeSimplified = Amt2 == Amt->getOperand(i);
13670 if (!CanBeSimplified) {
13671 TargetOpcode = X86ISD::MOVSD;
13672 CanBeSimplified = true;
13673 Amt2 = Amt->getOperand(4);
13674 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13675 CanBeSimplified = Amt1 == Amt->getOperand(i);
13676 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13677 CanBeSimplified = Amt2 == Amt->getOperand(j);
13681 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13682 isa<ConstantSDNode>(Amt2)) {
13683 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13684 EVT CastVT = MVT::v4i32;
13686 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13687 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13689 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13690 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13691 if (TargetOpcode == X86ISD::MOVSD)
13692 CastVT = MVT::v2i64;
13693 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13694 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13695 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13697 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13701 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13702 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13705 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13706 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13708 // Turn 'a' into a mask suitable for VSELECT
13709 SDValue VSelM = DAG.getConstant(0x80, VT);
13710 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13711 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13713 SDValue CM1 = DAG.getConstant(0x0f, VT);
13714 SDValue CM2 = DAG.getConstant(0x3f, VT);
13716 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13717 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13718 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13719 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13720 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13723 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13724 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13725 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13727 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13728 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13729 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13730 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13731 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13734 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13735 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13736 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13738 // return VSELECT(r, r+r, a);
13739 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13740 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13744 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13745 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13746 // solution better.
13747 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13748 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13750 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13751 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13752 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13753 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13754 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13757 // Decompose 256-bit shifts into smaller 128-bit shifts.
13758 if (VT.is256BitVector()) {
13759 unsigned NumElems = VT.getVectorNumElements();
13760 MVT EltVT = VT.getVectorElementType();
13761 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13763 // Extract the two vectors
13764 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13765 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13767 // Recreate the shift amount vectors
13768 SDValue Amt1, Amt2;
13769 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13770 // Constant shift amount
13771 SmallVector<SDValue, 4> Amt1Csts;
13772 SmallVector<SDValue, 4> Amt2Csts;
13773 for (unsigned i = 0; i != NumElems/2; ++i)
13774 Amt1Csts.push_back(Amt->getOperand(i));
13775 for (unsigned i = NumElems/2; i != NumElems; ++i)
13776 Amt2Csts.push_back(Amt->getOperand(i));
13778 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13779 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13781 // Variable shift amount
13782 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13783 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13786 // Issue new vector shifts for the smaller types
13787 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13788 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13790 // Concatenate the result back
13791 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13797 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13798 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13799 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13800 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13801 // has only one use.
13802 SDNode *N = Op.getNode();
13803 SDValue LHS = N->getOperand(0);
13804 SDValue RHS = N->getOperand(1);
13805 unsigned BaseOp = 0;
13808 switch (Op.getOpcode()) {
13809 default: llvm_unreachable("Unknown ovf instruction!");
13811 // A subtract of one will be selected as a INC. Note that INC doesn't
13812 // set CF, so we can't do this for UADDO.
13813 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13815 BaseOp = X86ISD::INC;
13816 Cond = X86::COND_O;
13819 BaseOp = X86ISD::ADD;
13820 Cond = X86::COND_O;
13823 BaseOp = X86ISD::ADD;
13824 Cond = X86::COND_B;
13827 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13828 // set CF, so we can't do this for USUBO.
13829 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13831 BaseOp = X86ISD::DEC;
13832 Cond = X86::COND_O;
13835 BaseOp = X86ISD::SUB;
13836 Cond = X86::COND_O;
13839 BaseOp = X86ISD::SUB;
13840 Cond = X86::COND_B;
13843 BaseOp = X86ISD::SMUL;
13844 Cond = X86::COND_O;
13846 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13847 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13849 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13852 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13853 DAG.getConstant(X86::COND_O, MVT::i32),
13854 SDValue(Sum.getNode(), 2));
13856 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13860 // Also sets EFLAGS.
13861 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13862 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13865 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13866 DAG.getConstant(Cond, MVT::i32),
13867 SDValue(Sum.getNode(), 1));
13869 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13872 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13873 SelectionDAG &DAG) const {
13875 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13876 MVT VT = Op.getSimpleValueType();
13878 if (!Subtarget->hasSSE2() || !VT.isVector())
13881 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13882 ExtraVT.getScalarType().getSizeInBits();
13884 switch (VT.SimpleTy) {
13885 default: return SDValue();
13888 if (!Subtarget->hasFp256())
13890 if (!Subtarget->hasInt256()) {
13891 // needs to be split
13892 unsigned NumElems = VT.getVectorNumElements();
13894 // Extract the LHS vectors
13895 SDValue LHS = Op.getOperand(0);
13896 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13897 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13899 MVT EltVT = VT.getVectorElementType();
13900 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13902 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13903 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13904 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13906 SDValue Extra = DAG.getValueType(ExtraVT);
13908 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13909 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13911 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13916 SDValue Op0 = Op.getOperand(0);
13917 SDValue Op00 = Op0.getOperand(0);
13919 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13920 if (Op0.getOpcode() == ISD::BITCAST &&
13921 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13922 // (sext (vzext x)) -> (vsext x)
13923 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13924 if (Tmp1.getNode()) {
13925 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13926 // This folding is only valid when the in-reg type is a vector of i8,
13928 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13929 ExtraEltVT == MVT::i32) {
13930 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13931 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13932 "This optimization is invalid without a VZEXT.");
13933 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13939 // If the above didn't work, then just use Shift-Left + Shift-Right.
13940 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13942 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13948 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13949 SelectionDAG &DAG) {
13951 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13952 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13953 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13954 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13956 // The only fence that needs an instruction is a sequentially-consistent
13957 // cross-thread fence.
13958 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13959 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13960 // no-sse2). There isn't any reason to disable it if the target processor
13962 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13963 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13965 SDValue Chain = Op.getOperand(0);
13966 SDValue Zero = DAG.getConstant(0, MVT::i32);
13968 DAG.getRegister(X86::ESP, MVT::i32), // Base
13969 DAG.getTargetConstant(1, MVT::i8), // Scale
13970 DAG.getRegister(0, MVT::i32), // Index
13971 DAG.getTargetConstant(0, MVT::i32), // Disp
13972 DAG.getRegister(0, MVT::i32), // Segment.
13976 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13977 return SDValue(Res, 0);
13980 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13981 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13984 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13985 SelectionDAG &DAG) {
13986 MVT T = Op.getSimpleValueType();
13990 switch(T.SimpleTy) {
13991 default: llvm_unreachable("Invalid value type!");
13992 case MVT::i8: Reg = X86::AL; size = 1; break;
13993 case MVT::i16: Reg = X86::AX; size = 2; break;
13994 case MVT::i32: Reg = X86::EAX; size = 4; break;
13996 assert(Subtarget->is64Bit() && "Node not type legal!");
13997 Reg = X86::RAX; size = 8;
14000 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14001 Op.getOperand(2), SDValue());
14002 SDValue Ops[] = { cpIn.getValue(0),
14005 DAG.getTargetConstant(size, MVT::i8),
14006 cpIn.getValue(1) };
14007 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14008 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14009 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14012 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14016 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14017 SelectionDAG &DAG) {
14018 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14019 MVT DstVT = Op.getSimpleValueType();
14020 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14021 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14022 assert((DstVT == MVT::i64 ||
14023 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14024 "Unexpected custom BITCAST");
14025 // i64 <=> MMX conversions are Legal.
14026 if (SrcVT==MVT::i64 && DstVT.isVector())
14028 if (DstVT==MVT::i64 && SrcVT.isVector())
14030 // MMX <=> MMX conversions are Legal.
14031 if (SrcVT.isVector() && DstVT.isVector())
14033 // All other conversions need to be expanded.
14037 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14038 SDNode *Node = Op.getNode();
14040 EVT T = Node->getValueType(0);
14041 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14042 DAG.getConstant(0, T), Node->getOperand(2));
14043 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14044 cast<AtomicSDNode>(Node)->getMemoryVT(),
14045 Node->getOperand(0),
14046 Node->getOperand(1), negOp,
14047 cast<AtomicSDNode>(Node)->getMemOperand(),
14048 cast<AtomicSDNode>(Node)->getOrdering(),
14049 cast<AtomicSDNode>(Node)->getSynchScope());
14052 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14053 SDNode *Node = Op.getNode();
14055 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14057 // Convert seq_cst store -> xchg
14058 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14059 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14060 // (The only way to get a 16-byte store is cmpxchg16b)
14061 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14062 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14063 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14064 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14065 cast<AtomicSDNode>(Node)->getMemoryVT(),
14066 Node->getOperand(0),
14067 Node->getOperand(1), Node->getOperand(2),
14068 cast<AtomicSDNode>(Node)->getMemOperand(),
14069 cast<AtomicSDNode>(Node)->getOrdering(),
14070 cast<AtomicSDNode>(Node)->getSynchScope());
14071 return Swap.getValue(1);
14073 // Other atomic stores have a simple pattern.
14077 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14078 EVT VT = Op.getNode()->getSimpleValueType(0);
14080 // Let legalize expand this if it isn't a legal type yet.
14081 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14084 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14087 bool ExtraOp = false;
14088 switch (Op.getOpcode()) {
14089 default: llvm_unreachable("Invalid code");
14090 case ISD::ADDC: Opc = X86ISD::ADD; break;
14091 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14092 case ISD::SUBC: Opc = X86ISD::SUB; break;
14093 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14097 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14099 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14100 Op.getOperand(1), Op.getOperand(2));
14103 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14104 SelectionDAG &DAG) {
14105 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14107 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14108 // which returns the values as { float, float } (in XMM0) or
14109 // { double, double } (which is returned in XMM0, XMM1).
14111 SDValue Arg = Op.getOperand(0);
14112 EVT ArgVT = Arg.getValueType();
14113 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14115 TargetLowering::ArgListTy Args;
14116 TargetLowering::ArgListEntry Entry;
14120 Entry.isSExt = false;
14121 Entry.isZExt = false;
14122 Args.push_back(Entry);
14124 bool isF64 = ArgVT == MVT::f64;
14125 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14126 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14127 // the results are returned via SRet in memory.
14128 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14129 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14130 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14132 Type *RetTy = isF64
14133 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14134 : (Type*)VectorType::get(ArgTy, 4);
14136 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14137 false, false, false, false, 0,
14138 CallingConv::C, /*isTaillCall=*/false,
14139 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14140 Callee, Args, DAG, dl);
14141 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14144 // Returned in xmm0 and xmm1.
14145 return CallResult.first;
14147 // Returned in bits 0:31 and 32:64 xmm0.
14148 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14149 CallResult.first, DAG.getIntPtrConstant(0));
14150 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14151 CallResult.first, DAG.getIntPtrConstant(1));
14152 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14153 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14156 /// LowerOperation - Provide custom lowering hooks for some operations.
14158 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14159 switch (Op.getOpcode()) {
14160 default: llvm_unreachable("Should not custom lower this!");
14161 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14162 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14163 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14164 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14165 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14166 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14167 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14168 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14169 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14170 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14171 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14172 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14173 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14174 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14175 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14176 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14177 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14178 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14179 case ISD::SHL_PARTS:
14180 case ISD::SRA_PARTS:
14181 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14182 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14183 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14184 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14185 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14186 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14187 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14188 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14189 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14190 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14191 case ISD::FABS: return LowerFABS(Op, DAG);
14192 case ISD::FNEG: return LowerFNEG(Op, DAG);
14193 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14194 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14195 case ISD::SETCC: return LowerSETCC(Op, DAG);
14196 case ISD::SELECT: return LowerSELECT(Op, DAG);
14197 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14198 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14199 case ISD::VASTART: return LowerVASTART(Op, DAG);
14200 case ISD::VAARG: return LowerVAARG(Op, DAG);
14201 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14202 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14203 case ISD::INTRINSIC_VOID:
14204 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14205 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14206 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14207 case ISD::FRAME_TO_ARGS_OFFSET:
14208 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14209 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14210 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14211 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14212 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14213 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14214 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14215 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14216 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14217 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14218 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14219 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14220 case ISD::UMUL_LOHI:
14221 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14224 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14230 case ISD::UMULO: return LowerXALUO(Op, DAG);
14231 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14232 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14236 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14237 case ISD::ADD: return LowerADD(Op, DAG);
14238 case ISD::SUB: return LowerSUB(Op, DAG);
14239 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14243 static void ReplaceATOMIC_LOAD(SDNode *Node,
14244 SmallVectorImpl<SDValue> &Results,
14245 SelectionDAG &DAG) {
14247 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14249 // Convert wide load -> cmpxchg8b/cmpxchg16b
14250 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14251 // (The only way to get a 16-byte load is cmpxchg16b)
14252 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14253 SDValue Zero = DAG.getConstant(0, VT);
14254 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14255 Node->getOperand(0),
14256 Node->getOperand(1), Zero, Zero,
14257 cast<AtomicSDNode>(Node)->getMemOperand(),
14258 cast<AtomicSDNode>(Node)->getOrdering(),
14259 cast<AtomicSDNode>(Node)->getOrdering(),
14260 cast<AtomicSDNode>(Node)->getSynchScope());
14261 Results.push_back(Swap.getValue(0));
14262 Results.push_back(Swap.getValue(1));
14266 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14267 SelectionDAG &DAG, unsigned NewOp) {
14269 assert (Node->getValueType(0) == MVT::i64 &&
14270 "Only know how to expand i64 atomics");
14272 SDValue Chain = Node->getOperand(0);
14273 SDValue In1 = Node->getOperand(1);
14274 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14275 Node->getOperand(2), DAG.getIntPtrConstant(0));
14276 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14277 Node->getOperand(2), DAG.getIntPtrConstant(1));
14278 SDValue Ops[] = { Chain, In1, In2L, In2H };
14279 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14281 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14282 cast<MemSDNode>(Node)->getMemOperand());
14283 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14284 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14285 Results.push_back(Result.getValue(2));
14288 /// ReplaceNodeResults - Replace a node with an illegal result type
14289 /// with a new node built out of custom code.
14290 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14291 SmallVectorImpl<SDValue>&Results,
14292 SelectionDAG &DAG) const {
14294 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14295 switch (N->getOpcode()) {
14297 llvm_unreachable("Do not know how to custom type legalize this operation!");
14298 case ISD::SIGN_EXTEND_INREG:
14303 // We don't want to expand or promote these.
14305 case ISD::FP_TO_SINT:
14306 case ISD::FP_TO_UINT: {
14307 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14309 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14312 std::pair<SDValue,SDValue> Vals =
14313 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14314 SDValue FIST = Vals.first, StackSlot = Vals.second;
14315 if (FIST.getNode()) {
14316 EVT VT = N->getValueType(0);
14317 // Return a load from the stack slot.
14318 if (StackSlot.getNode())
14319 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14320 MachinePointerInfo(),
14321 false, false, false, 0));
14323 Results.push_back(FIST);
14327 case ISD::UINT_TO_FP: {
14328 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14329 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14330 N->getValueType(0) != MVT::v2f32)
14332 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14334 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14336 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14337 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14338 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14339 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14340 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14341 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14344 case ISD::FP_ROUND: {
14345 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14347 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14348 Results.push_back(V);
14351 case ISD::INTRINSIC_W_CHAIN: {
14352 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14354 default : llvm_unreachable("Do not know how to custom type "
14355 "legalize this intrinsic operation!");
14356 case Intrinsic::x86_rdtsc:
14357 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14359 case Intrinsic::x86_rdtscp:
14360 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14364 case ISD::READCYCLECOUNTER: {
14365 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14368 case ISD::ATOMIC_CMP_SWAP: {
14369 EVT T = N->getValueType(0);
14370 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14371 bool Regs64bit = T == MVT::i128;
14372 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14373 SDValue cpInL, cpInH;
14374 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14375 DAG.getConstant(0, HalfT));
14376 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14377 DAG.getConstant(1, HalfT));
14378 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14379 Regs64bit ? X86::RAX : X86::EAX,
14381 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14382 Regs64bit ? X86::RDX : X86::EDX,
14383 cpInH, cpInL.getValue(1));
14384 SDValue swapInL, swapInH;
14385 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14386 DAG.getConstant(0, HalfT));
14387 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14388 DAG.getConstant(1, HalfT));
14389 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14390 Regs64bit ? X86::RBX : X86::EBX,
14391 swapInL, cpInH.getValue(1));
14392 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14393 Regs64bit ? X86::RCX : X86::ECX,
14394 swapInH, swapInL.getValue(1));
14395 SDValue Ops[] = { swapInH.getValue(0),
14397 swapInH.getValue(1) };
14398 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14399 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14400 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14401 X86ISD::LCMPXCHG8_DAG;
14402 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14403 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14404 Regs64bit ? X86::RAX : X86::EAX,
14405 HalfT, Result.getValue(1));
14406 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14407 Regs64bit ? X86::RDX : X86::EDX,
14408 HalfT, cpOutL.getValue(2));
14409 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14410 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14411 Results.push_back(cpOutH.getValue(1));
14414 case ISD::ATOMIC_LOAD_ADD:
14415 case ISD::ATOMIC_LOAD_AND:
14416 case ISD::ATOMIC_LOAD_NAND:
14417 case ISD::ATOMIC_LOAD_OR:
14418 case ISD::ATOMIC_LOAD_SUB:
14419 case ISD::ATOMIC_LOAD_XOR:
14420 case ISD::ATOMIC_LOAD_MAX:
14421 case ISD::ATOMIC_LOAD_MIN:
14422 case ISD::ATOMIC_LOAD_UMAX:
14423 case ISD::ATOMIC_LOAD_UMIN:
14424 case ISD::ATOMIC_SWAP: {
14426 switch (N->getOpcode()) {
14427 default: llvm_unreachable("Unexpected opcode");
14428 case ISD::ATOMIC_LOAD_ADD:
14429 Opc = X86ISD::ATOMADD64_DAG;
14431 case ISD::ATOMIC_LOAD_AND:
14432 Opc = X86ISD::ATOMAND64_DAG;
14434 case ISD::ATOMIC_LOAD_NAND:
14435 Opc = X86ISD::ATOMNAND64_DAG;
14437 case ISD::ATOMIC_LOAD_OR:
14438 Opc = X86ISD::ATOMOR64_DAG;
14440 case ISD::ATOMIC_LOAD_SUB:
14441 Opc = X86ISD::ATOMSUB64_DAG;
14443 case ISD::ATOMIC_LOAD_XOR:
14444 Opc = X86ISD::ATOMXOR64_DAG;
14446 case ISD::ATOMIC_LOAD_MAX:
14447 Opc = X86ISD::ATOMMAX64_DAG;
14449 case ISD::ATOMIC_LOAD_MIN:
14450 Opc = X86ISD::ATOMMIN64_DAG;
14452 case ISD::ATOMIC_LOAD_UMAX:
14453 Opc = X86ISD::ATOMUMAX64_DAG;
14455 case ISD::ATOMIC_LOAD_UMIN:
14456 Opc = X86ISD::ATOMUMIN64_DAG;
14458 case ISD::ATOMIC_SWAP:
14459 Opc = X86ISD::ATOMSWAP64_DAG;
14462 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14465 case ISD::ATOMIC_LOAD:
14466 ReplaceATOMIC_LOAD(N, Results, DAG);
14470 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14472 default: return nullptr;
14473 case X86ISD::BSF: return "X86ISD::BSF";
14474 case X86ISD::BSR: return "X86ISD::BSR";
14475 case X86ISD::SHLD: return "X86ISD::SHLD";
14476 case X86ISD::SHRD: return "X86ISD::SHRD";
14477 case X86ISD::FAND: return "X86ISD::FAND";
14478 case X86ISD::FANDN: return "X86ISD::FANDN";
14479 case X86ISD::FOR: return "X86ISD::FOR";
14480 case X86ISD::FXOR: return "X86ISD::FXOR";
14481 case X86ISD::FSRL: return "X86ISD::FSRL";
14482 case X86ISD::FILD: return "X86ISD::FILD";
14483 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14484 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14485 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14486 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14487 case X86ISD::FLD: return "X86ISD::FLD";
14488 case X86ISD::FST: return "X86ISD::FST";
14489 case X86ISD::CALL: return "X86ISD::CALL";
14490 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14491 case X86ISD::BT: return "X86ISD::BT";
14492 case X86ISD::CMP: return "X86ISD::CMP";
14493 case X86ISD::COMI: return "X86ISD::COMI";
14494 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14495 case X86ISD::CMPM: return "X86ISD::CMPM";
14496 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14497 case X86ISD::SETCC: return "X86ISD::SETCC";
14498 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14499 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14500 case X86ISD::CMOV: return "X86ISD::CMOV";
14501 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14502 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14503 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14504 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14505 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14506 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14507 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14508 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14509 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14510 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14511 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14512 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14513 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14514 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14515 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14516 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14517 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14518 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14519 case X86ISD::HADD: return "X86ISD::HADD";
14520 case X86ISD::HSUB: return "X86ISD::HSUB";
14521 case X86ISD::FHADD: return "X86ISD::FHADD";
14522 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14523 case X86ISD::UMAX: return "X86ISD::UMAX";
14524 case X86ISD::UMIN: return "X86ISD::UMIN";
14525 case X86ISD::SMAX: return "X86ISD::SMAX";
14526 case X86ISD::SMIN: return "X86ISD::SMIN";
14527 case X86ISD::FMAX: return "X86ISD::FMAX";
14528 case X86ISD::FMIN: return "X86ISD::FMIN";
14529 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14530 case X86ISD::FMINC: return "X86ISD::FMINC";
14531 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14532 case X86ISD::FRCP: return "X86ISD::FRCP";
14533 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14534 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14535 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14536 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14537 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14538 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14539 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14540 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14541 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14542 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14543 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14544 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14545 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14546 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14547 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14548 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14549 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14550 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14551 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14552 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14553 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14554 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14555 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14556 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14557 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14558 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14559 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14560 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14561 case X86ISD::VSHL: return "X86ISD::VSHL";
14562 case X86ISD::VSRL: return "X86ISD::VSRL";
14563 case X86ISD::VSRA: return "X86ISD::VSRA";
14564 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14565 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14566 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14567 case X86ISD::CMPP: return "X86ISD::CMPP";
14568 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14569 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14570 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14571 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14572 case X86ISD::ADD: return "X86ISD::ADD";
14573 case X86ISD::SUB: return "X86ISD::SUB";
14574 case X86ISD::ADC: return "X86ISD::ADC";
14575 case X86ISD::SBB: return "X86ISD::SBB";
14576 case X86ISD::SMUL: return "X86ISD::SMUL";
14577 case X86ISD::UMUL: return "X86ISD::UMUL";
14578 case X86ISD::INC: return "X86ISD::INC";
14579 case X86ISD::DEC: return "X86ISD::DEC";
14580 case X86ISD::OR: return "X86ISD::OR";
14581 case X86ISD::XOR: return "X86ISD::XOR";
14582 case X86ISD::AND: return "X86ISD::AND";
14583 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14584 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14585 case X86ISD::PTEST: return "X86ISD::PTEST";
14586 case X86ISD::TESTP: return "X86ISD::TESTP";
14587 case X86ISD::TESTM: return "X86ISD::TESTM";
14588 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14589 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14590 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14591 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14592 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14593 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14594 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14595 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14596 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14597 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14598 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14599 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14600 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14601 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14602 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14603 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14604 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14605 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14606 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14607 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14608 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14609 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14610 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14611 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14612 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14613 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14614 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14615 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14616 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14617 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14618 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14619 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14620 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14621 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14622 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14623 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14624 case X86ISD::SAHF: return "X86ISD::SAHF";
14625 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14626 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14627 case X86ISD::FMADD: return "X86ISD::FMADD";
14628 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14629 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14630 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14631 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14632 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14633 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14634 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14635 case X86ISD::XTEST: return "X86ISD::XTEST";
14639 // isLegalAddressingMode - Return true if the addressing mode represented
14640 // by AM is legal for this target, for a load/store of the specified type.
14641 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14643 // X86 supports extremely general addressing modes.
14644 CodeModel::Model M = getTargetMachine().getCodeModel();
14645 Reloc::Model R = getTargetMachine().getRelocationModel();
14647 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14648 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14653 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14655 // If a reference to this global requires an extra load, we can't fold it.
14656 if (isGlobalStubReference(GVFlags))
14659 // If BaseGV requires a register for the PIC base, we cannot also have a
14660 // BaseReg specified.
14661 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14664 // If lower 4G is not available, then we must use rip-relative addressing.
14665 if ((M != CodeModel::Small || R != Reloc::Static) &&
14666 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14670 switch (AM.Scale) {
14676 // These scales always work.
14681 // These scales are formed with basereg+scalereg. Only accept if there is
14686 default: // Other stuff never works.
14693 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14694 unsigned Bits = Ty->getScalarSizeInBits();
14696 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14697 // particularly cheaper than those without.
14701 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14702 // variable shifts just as cheap as scalar ones.
14703 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14706 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14707 // fully general vector.
14711 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14712 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14714 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14715 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14716 return NumBits1 > NumBits2;
14719 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14720 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14723 if (!isTypeLegal(EVT::getEVT(Ty1)))
14726 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14728 // Assuming the caller doesn't have a zeroext or signext return parameter,
14729 // truncation all the way down to i1 is valid.
14733 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14734 return isInt<32>(Imm);
14737 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14738 // Can also use sub to handle negated immediates.
14739 return isInt<32>(Imm);
14742 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14743 if (!VT1.isInteger() || !VT2.isInteger())
14745 unsigned NumBits1 = VT1.getSizeInBits();
14746 unsigned NumBits2 = VT2.getSizeInBits();
14747 return NumBits1 > NumBits2;
14750 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14751 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14752 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14755 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14756 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14757 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14760 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14761 EVT VT1 = Val.getValueType();
14762 if (isZExtFree(VT1, VT2))
14765 if (Val.getOpcode() != ISD::LOAD)
14768 if (!VT1.isSimple() || !VT1.isInteger() ||
14769 !VT2.isSimple() || !VT2.isInteger())
14772 switch (VT1.getSimpleVT().SimpleTy) {
14777 // X86 has 8, 16, and 32-bit zero-extending loads.
14785 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14786 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14789 VT = VT.getScalarType();
14791 if (!VT.isSimple())
14794 switch (VT.getSimpleVT().SimpleTy) {
14805 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14806 // i16 instructions are longer (0x66 prefix) and potentially slower.
14807 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14810 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14811 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14812 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14813 /// are assumed to be legal.
14815 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14817 if (!VT.isSimple())
14820 MVT SVT = VT.getSimpleVT();
14822 // Very little shuffling can be done for 64-bit vectors right now.
14823 if (VT.getSizeInBits() == 64)
14826 // FIXME: pshufb, blends, shifts.
14827 return (SVT.getVectorNumElements() == 2 ||
14828 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14829 isMOVLMask(M, SVT) ||
14830 isSHUFPMask(M, SVT) ||
14831 isPSHUFDMask(M, SVT) ||
14832 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14833 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14834 isPALIGNRMask(M, SVT, Subtarget) ||
14835 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14836 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14837 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14838 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14842 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14844 if (!VT.isSimple())
14847 MVT SVT = VT.getSimpleVT();
14848 unsigned NumElts = SVT.getVectorNumElements();
14849 // FIXME: This collection of masks seems suspect.
14852 if (NumElts == 4 && SVT.is128BitVector()) {
14853 return (isMOVLMask(Mask, SVT) ||
14854 isCommutedMOVLMask(Mask, SVT, true) ||
14855 isSHUFPMask(Mask, SVT) ||
14856 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14861 //===----------------------------------------------------------------------===//
14862 // X86 Scheduler Hooks
14863 //===----------------------------------------------------------------------===//
14865 /// Utility function to emit xbegin specifying the start of an RTM region.
14866 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14867 const TargetInstrInfo *TII) {
14868 DebugLoc DL = MI->getDebugLoc();
14870 const BasicBlock *BB = MBB->getBasicBlock();
14871 MachineFunction::iterator I = MBB;
14874 // For the v = xbegin(), we generate
14885 MachineBasicBlock *thisMBB = MBB;
14886 MachineFunction *MF = MBB->getParent();
14887 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14888 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14889 MF->insert(I, mainMBB);
14890 MF->insert(I, sinkMBB);
14892 // Transfer the remainder of BB and its successor edges to sinkMBB.
14893 sinkMBB->splice(sinkMBB->begin(), MBB,
14894 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14895 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14899 // # fallthrough to mainMBB
14900 // # abortion to sinkMBB
14901 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14902 thisMBB->addSuccessor(mainMBB);
14903 thisMBB->addSuccessor(sinkMBB);
14907 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14908 mainMBB->addSuccessor(sinkMBB);
14911 // EAX is live into the sinkMBB
14912 sinkMBB->addLiveIn(X86::EAX);
14913 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14914 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14917 MI->eraseFromParent();
14921 // Get CMPXCHG opcode for the specified data type.
14922 static unsigned getCmpXChgOpcode(EVT VT) {
14923 switch (VT.getSimpleVT().SimpleTy) {
14924 case MVT::i8: return X86::LCMPXCHG8;
14925 case MVT::i16: return X86::LCMPXCHG16;
14926 case MVT::i32: return X86::LCMPXCHG32;
14927 case MVT::i64: return X86::LCMPXCHG64;
14931 llvm_unreachable("Invalid operand size!");
14934 // Get LOAD opcode for the specified data type.
14935 static unsigned getLoadOpcode(EVT VT) {
14936 switch (VT.getSimpleVT().SimpleTy) {
14937 case MVT::i8: return X86::MOV8rm;
14938 case MVT::i16: return X86::MOV16rm;
14939 case MVT::i32: return X86::MOV32rm;
14940 case MVT::i64: return X86::MOV64rm;
14944 llvm_unreachable("Invalid operand size!");
14947 // Get opcode of the non-atomic one from the specified atomic instruction.
14948 static unsigned getNonAtomicOpcode(unsigned Opc) {
14950 case X86::ATOMAND8: return X86::AND8rr;
14951 case X86::ATOMAND16: return X86::AND16rr;
14952 case X86::ATOMAND32: return X86::AND32rr;
14953 case X86::ATOMAND64: return X86::AND64rr;
14954 case X86::ATOMOR8: return X86::OR8rr;
14955 case X86::ATOMOR16: return X86::OR16rr;
14956 case X86::ATOMOR32: return X86::OR32rr;
14957 case X86::ATOMOR64: return X86::OR64rr;
14958 case X86::ATOMXOR8: return X86::XOR8rr;
14959 case X86::ATOMXOR16: return X86::XOR16rr;
14960 case X86::ATOMXOR32: return X86::XOR32rr;
14961 case X86::ATOMXOR64: return X86::XOR64rr;
14963 llvm_unreachable("Unhandled atomic-load-op opcode!");
14966 // Get opcode of the non-atomic one from the specified atomic instruction with
14968 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14969 unsigned &ExtraOpc) {
14971 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14972 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14973 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14974 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14975 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14976 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14977 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14978 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14979 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14980 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14981 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14982 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14983 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14984 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14985 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14986 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14987 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14988 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14989 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14990 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14992 llvm_unreachable("Unhandled atomic-load-op opcode!");
14995 // Get opcode of the non-atomic one from the specified atomic instruction for
14996 // 64-bit data type on 32-bit target.
14997 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14999 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15000 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15001 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15002 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15003 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15004 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15005 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15006 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15007 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15008 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15010 llvm_unreachable("Unhandled atomic-load-op opcode!");
15013 // Get opcode of the non-atomic one from the specified atomic instruction for
15014 // 64-bit data type on 32-bit target with extra opcode.
15015 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15017 unsigned &ExtraOpc) {
15019 case X86::ATOMNAND6432:
15020 ExtraOpc = X86::NOT32r;
15021 HiOpc = X86::AND32rr;
15022 return X86::AND32rr;
15024 llvm_unreachable("Unhandled atomic-load-op opcode!");
15027 // Get pseudo CMOV opcode from the specified data type.
15028 static unsigned getPseudoCMOVOpc(EVT VT) {
15029 switch (VT.getSimpleVT().SimpleTy) {
15030 case MVT::i8: return X86::CMOV_GR8;
15031 case MVT::i16: return X86::CMOV_GR16;
15032 case MVT::i32: return X86::CMOV_GR32;
15036 llvm_unreachable("Unknown CMOV opcode!");
15039 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15040 // They will be translated into a spin-loop or compare-exchange loop from
15043 // dst = atomic-fetch-op MI.addr, MI.val
15049 // t1 = LOAD MI.addr
15051 // t4 = phi(t1, t3 / loop)
15052 // t2 = OP MI.val, t4
15054 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15060 MachineBasicBlock *
15061 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15062 MachineBasicBlock *MBB) const {
15063 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15064 DebugLoc DL = MI->getDebugLoc();
15066 MachineFunction *MF = MBB->getParent();
15067 MachineRegisterInfo &MRI = MF->getRegInfo();
15069 const BasicBlock *BB = MBB->getBasicBlock();
15070 MachineFunction::iterator I = MBB;
15073 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15074 "Unexpected number of operands");
15076 assert(MI->hasOneMemOperand() &&
15077 "Expected atomic-load-op to have one memoperand");
15079 // Memory Reference
15080 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15081 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15083 unsigned DstReg, SrcReg;
15084 unsigned MemOpndSlot;
15086 unsigned CurOp = 0;
15088 DstReg = MI->getOperand(CurOp++).getReg();
15089 MemOpndSlot = CurOp;
15090 CurOp += X86::AddrNumOperands;
15091 SrcReg = MI->getOperand(CurOp++).getReg();
15093 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15094 MVT::SimpleValueType VT = *RC->vt_begin();
15095 unsigned t1 = MRI.createVirtualRegister(RC);
15096 unsigned t2 = MRI.createVirtualRegister(RC);
15097 unsigned t3 = MRI.createVirtualRegister(RC);
15098 unsigned t4 = MRI.createVirtualRegister(RC);
15099 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15101 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15102 unsigned LOADOpc = getLoadOpcode(VT);
15104 // For the atomic load-arith operator, we generate
15107 // t1 = LOAD [MI.addr]
15109 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15110 // t1 = OP MI.val, EAX
15112 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15118 MachineBasicBlock *thisMBB = MBB;
15119 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15120 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15121 MF->insert(I, mainMBB);
15122 MF->insert(I, sinkMBB);
15124 MachineInstrBuilder MIB;
15126 // Transfer the remainder of BB and its successor edges to sinkMBB.
15127 sinkMBB->splice(sinkMBB->begin(), MBB,
15128 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15129 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15132 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15133 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15134 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15136 NewMO.setIsKill(false);
15137 MIB.addOperand(NewMO);
15139 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15140 unsigned flags = (*MMOI)->getFlags();
15141 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15142 MachineMemOperand *MMO =
15143 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15144 (*MMOI)->getSize(),
15145 (*MMOI)->getBaseAlignment(),
15146 (*MMOI)->getTBAAInfo(),
15147 (*MMOI)->getRanges());
15148 MIB.addMemOperand(MMO);
15151 thisMBB->addSuccessor(mainMBB);
15154 MachineBasicBlock *origMainMBB = mainMBB;
15157 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15158 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15160 unsigned Opc = MI->getOpcode();
15163 llvm_unreachable("Unhandled atomic-load-op opcode!");
15164 case X86::ATOMAND8:
15165 case X86::ATOMAND16:
15166 case X86::ATOMAND32:
15167 case X86::ATOMAND64:
15169 case X86::ATOMOR16:
15170 case X86::ATOMOR32:
15171 case X86::ATOMOR64:
15172 case X86::ATOMXOR8:
15173 case X86::ATOMXOR16:
15174 case X86::ATOMXOR32:
15175 case X86::ATOMXOR64: {
15176 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15177 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15181 case X86::ATOMNAND8:
15182 case X86::ATOMNAND16:
15183 case X86::ATOMNAND32:
15184 case X86::ATOMNAND64: {
15185 unsigned Tmp = MRI.createVirtualRegister(RC);
15187 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15188 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15190 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15193 case X86::ATOMMAX8:
15194 case X86::ATOMMAX16:
15195 case X86::ATOMMAX32:
15196 case X86::ATOMMAX64:
15197 case X86::ATOMMIN8:
15198 case X86::ATOMMIN16:
15199 case X86::ATOMMIN32:
15200 case X86::ATOMMIN64:
15201 case X86::ATOMUMAX8:
15202 case X86::ATOMUMAX16:
15203 case X86::ATOMUMAX32:
15204 case X86::ATOMUMAX64:
15205 case X86::ATOMUMIN8:
15206 case X86::ATOMUMIN16:
15207 case X86::ATOMUMIN32:
15208 case X86::ATOMUMIN64: {
15210 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15212 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15216 if (Subtarget->hasCMov()) {
15217 if (VT != MVT::i8) {
15219 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15223 // Promote i8 to i32 to use CMOV32
15224 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15225 const TargetRegisterClass *RC32 =
15226 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15227 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15228 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15229 unsigned Tmp = MRI.createVirtualRegister(RC32);
15231 unsigned Undef = MRI.createVirtualRegister(RC32);
15232 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15234 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15237 .addImm(X86::sub_8bit);
15238 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15241 .addImm(X86::sub_8bit);
15243 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15247 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15248 .addReg(Tmp, 0, X86::sub_8bit);
15251 // Use pseudo select and lower them.
15252 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15253 "Invalid atomic-load-op transformation!");
15254 unsigned SelOpc = getPseudoCMOVOpc(VT);
15255 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15256 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15257 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15258 .addReg(SrcReg).addReg(t4)
15260 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15261 // Replace the original PHI node as mainMBB is changed after CMOV
15263 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15264 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15265 Phi->eraseFromParent();
15271 // Copy PhyReg back from virtual register.
15272 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15275 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15276 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15277 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15279 NewMO.setIsKill(false);
15280 MIB.addOperand(NewMO);
15283 MIB.setMemRefs(MMOBegin, MMOEnd);
15285 // Copy PhyReg back to virtual register.
15286 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15289 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15291 mainMBB->addSuccessor(origMainMBB);
15292 mainMBB->addSuccessor(sinkMBB);
15295 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15296 TII->get(TargetOpcode::COPY), DstReg)
15299 MI->eraseFromParent();
15303 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15304 // instructions. They will be translated into a spin-loop or compare-exchange
15308 // dst = atomic-fetch-op MI.addr, MI.val
15314 // t1L = LOAD [MI.addr + 0]
15315 // t1H = LOAD [MI.addr + 4]
15317 // t4L = phi(t1L, t3L / loop)
15318 // t4H = phi(t1H, t3H / loop)
15319 // t2L = OP MI.val.lo, t4L
15320 // t2H = OP MI.val.hi, t4H
15325 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15333 MachineBasicBlock *
15334 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15335 MachineBasicBlock *MBB) const {
15336 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15337 DebugLoc DL = MI->getDebugLoc();
15339 MachineFunction *MF = MBB->getParent();
15340 MachineRegisterInfo &MRI = MF->getRegInfo();
15342 const BasicBlock *BB = MBB->getBasicBlock();
15343 MachineFunction::iterator I = MBB;
15346 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15347 "Unexpected number of operands");
15349 assert(MI->hasOneMemOperand() &&
15350 "Expected atomic-load-op32 to have one memoperand");
15352 // Memory Reference
15353 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15354 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15356 unsigned DstLoReg, DstHiReg;
15357 unsigned SrcLoReg, SrcHiReg;
15358 unsigned MemOpndSlot;
15360 unsigned CurOp = 0;
15362 DstLoReg = MI->getOperand(CurOp++).getReg();
15363 DstHiReg = MI->getOperand(CurOp++).getReg();
15364 MemOpndSlot = CurOp;
15365 CurOp += X86::AddrNumOperands;
15366 SrcLoReg = MI->getOperand(CurOp++).getReg();
15367 SrcHiReg = MI->getOperand(CurOp++).getReg();
15369 const TargetRegisterClass *RC = &X86::GR32RegClass;
15370 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15372 unsigned t1L = MRI.createVirtualRegister(RC);
15373 unsigned t1H = MRI.createVirtualRegister(RC);
15374 unsigned t2L = MRI.createVirtualRegister(RC);
15375 unsigned t2H = MRI.createVirtualRegister(RC);
15376 unsigned t3L = MRI.createVirtualRegister(RC);
15377 unsigned t3H = MRI.createVirtualRegister(RC);
15378 unsigned t4L = MRI.createVirtualRegister(RC);
15379 unsigned t4H = MRI.createVirtualRegister(RC);
15381 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15382 unsigned LOADOpc = X86::MOV32rm;
15384 // For the atomic load-arith operator, we generate
15387 // t1L = LOAD [MI.addr + 0]
15388 // t1H = LOAD [MI.addr + 4]
15390 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15391 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15392 // t2L = OP MI.val.lo, t4L
15393 // t2H = OP MI.val.hi, t4H
15396 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15404 MachineBasicBlock *thisMBB = MBB;
15405 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15406 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15407 MF->insert(I, mainMBB);
15408 MF->insert(I, sinkMBB);
15410 MachineInstrBuilder MIB;
15412 // Transfer the remainder of BB and its successor edges to sinkMBB.
15413 sinkMBB->splice(sinkMBB->begin(), MBB,
15414 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15415 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15419 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15420 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15421 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15423 NewMO.setIsKill(false);
15424 MIB.addOperand(NewMO);
15426 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15427 unsigned flags = (*MMOI)->getFlags();
15428 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15429 MachineMemOperand *MMO =
15430 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15431 (*MMOI)->getSize(),
15432 (*MMOI)->getBaseAlignment(),
15433 (*MMOI)->getTBAAInfo(),
15434 (*MMOI)->getRanges());
15435 MIB.addMemOperand(MMO);
15437 MachineInstr *LowMI = MIB;
15440 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15441 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15442 if (i == X86::AddrDisp) {
15443 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15445 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15447 NewMO.setIsKill(false);
15448 MIB.addOperand(NewMO);
15451 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15453 thisMBB->addSuccessor(mainMBB);
15456 MachineBasicBlock *origMainMBB = mainMBB;
15459 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15460 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15461 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15462 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15464 unsigned Opc = MI->getOpcode();
15467 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15468 case X86::ATOMAND6432:
15469 case X86::ATOMOR6432:
15470 case X86::ATOMXOR6432:
15471 case X86::ATOMADD6432:
15472 case X86::ATOMSUB6432: {
15474 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15475 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15477 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15481 case X86::ATOMNAND6432: {
15482 unsigned HiOpc, NOTOpc;
15483 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15484 unsigned TmpL = MRI.createVirtualRegister(RC);
15485 unsigned TmpH = MRI.createVirtualRegister(RC);
15486 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15488 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15490 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15491 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15494 case X86::ATOMMAX6432:
15495 case X86::ATOMMIN6432:
15496 case X86::ATOMUMAX6432:
15497 case X86::ATOMUMIN6432: {
15499 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15500 unsigned cL = MRI.createVirtualRegister(RC8);
15501 unsigned cH = MRI.createVirtualRegister(RC8);
15502 unsigned cL32 = MRI.createVirtualRegister(RC);
15503 unsigned cH32 = MRI.createVirtualRegister(RC);
15504 unsigned cc = MRI.createVirtualRegister(RC);
15505 // cl := cmp src_lo, lo
15506 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15507 .addReg(SrcLoReg).addReg(t4L);
15508 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15509 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15510 // ch := cmp src_hi, hi
15511 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15512 .addReg(SrcHiReg).addReg(t4H);
15513 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15514 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15515 // cc := if (src_hi == hi) ? cl : ch;
15516 if (Subtarget->hasCMov()) {
15517 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15518 .addReg(cH32).addReg(cL32);
15520 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15521 .addReg(cH32).addReg(cL32)
15522 .addImm(X86::COND_E);
15523 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15525 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15526 if (Subtarget->hasCMov()) {
15527 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15528 .addReg(SrcLoReg).addReg(t4L);
15529 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15530 .addReg(SrcHiReg).addReg(t4H);
15532 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15533 .addReg(SrcLoReg).addReg(t4L)
15534 .addImm(X86::COND_NE);
15535 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15536 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15537 // 2nd CMOV lowering.
15538 mainMBB->addLiveIn(X86::EFLAGS);
15539 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15540 .addReg(SrcHiReg).addReg(t4H)
15541 .addImm(X86::COND_NE);
15542 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15543 // Replace the original PHI node as mainMBB is changed after CMOV
15545 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15546 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15547 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15548 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15549 PhiL->eraseFromParent();
15550 PhiH->eraseFromParent();
15554 case X86::ATOMSWAP6432: {
15556 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15557 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15558 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15563 // Copy EDX:EAX back from HiReg:LoReg
15564 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15565 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15566 // Copy ECX:EBX from t1H:t1L
15567 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15568 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15570 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15571 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15572 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15574 NewMO.setIsKill(false);
15575 MIB.addOperand(NewMO);
15577 MIB.setMemRefs(MMOBegin, MMOEnd);
15579 // Copy EDX:EAX back to t3H:t3L
15580 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15581 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15583 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15585 mainMBB->addSuccessor(origMainMBB);
15586 mainMBB->addSuccessor(sinkMBB);
15589 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15590 TII->get(TargetOpcode::COPY), DstLoReg)
15592 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15593 TII->get(TargetOpcode::COPY), DstHiReg)
15596 MI->eraseFromParent();
15600 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15601 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15602 // in the .td file.
15603 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15604 const TargetInstrInfo *TII) {
15606 switch (MI->getOpcode()) {
15607 default: llvm_unreachable("illegal opcode!");
15608 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15609 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15610 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15611 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15612 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15613 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15614 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15615 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15618 DebugLoc dl = MI->getDebugLoc();
15619 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15621 unsigned NumArgs = MI->getNumOperands();
15622 for (unsigned i = 1; i < NumArgs; ++i) {
15623 MachineOperand &Op = MI->getOperand(i);
15624 if (!(Op.isReg() && Op.isImplicit()))
15625 MIB.addOperand(Op);
15627 if (MI->hasOneMemOperand())
15628 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15630 BuildMI(*BB, MI, dl,
15631 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15632 .addReg(X86::XMM0);
15634 MI->eraseFromParent();
15638 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15639 // defs in an instruction pattern
15640 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15641 const TargetInstrInfo *TII) {
15643 switch (MI->getOpcode()) {
15644 default: llvm_unreachable("illegal opcode!");
15645 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15646 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15647 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15648 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15649 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15650 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15651 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15652 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15655 DebugLoc dl = MI->getDebugLoc();
15656 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15658 unsigned NumArgs = MI->getNumOperands(); // remove the results
15659 for (unsigned i = 1; i < NumArgs; ++i) {
15660 MachineOperand &Op = MI->getOperand(i);
15661 if (!(Op.isReg() && Op.isImplicit()))
15662 MIB.addOperand(Op);
15664 if (MI->hasOneMemOperand())
15665 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15667 BuildMI(*BB, MI, dl,
15668 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15671 MI->eraseFromParent();
15675 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15676 const TargetInstrInfo *TII,
15677 const X86Subtarget* Subtarget) {
15678 DebugLoc dl = MI->getDebugLoc();
15680 // Address into RAX/EAX, other two args into ECX, EDX.
15681 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15682 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15683 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15684 for (int i = 0; i < X86::AddrNumOperands; ++i)
15685 MIB.addOperand(MI->getOperand(i));
15687 unsigned ValOps = X86::AddrNumOperands;
15688 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15689 .addReg(MI->getOperand(ValOps).getReg());
15690 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15691 .addReg(MI->getOperand(ValOps+1).getReg());
15693 // The instruction doesn't actually take any operands though.
15694 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15696 MI->eraseFromParent(); // The pseudo is gone now.
15700 MachineBasicBlock *
15701 X86TargetLowering::EmitVAARG64WithCustomInserter(
15703 MachineBasicBlock *MBB) const {
15704 // Emit va_arg instruction on X86-64.
15706 // Operands to this pseudo-instruction:
15707 // 0 ) Output : destination address (reg)
15708 // 1-5) Input : va_list address (addr, i64mem)
15709 // 6 ) ArgSize : Size (in bytes) of vararg type
15710 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15711 // 8 ) Align : Alignment of type
15712 // 9 ) EFLAGS (implicit-def)
15714 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15715 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15717 unsigned DestReg = MI->getOperand(0).getReg();
15718 MachineOperand &Base = MI->getOperand(1);
15719 MachineOperand &Scale = MI->getOperand(2);
15720 MachineOperand &Index = MI->getOperand(3);
15721 MachineOperand &Disp = MI->getOperand(4);
15722 MachineOperand &Segment = MI->getOperand(5);
15723 unsigned ArgSize = MI->getOperand(6).getImm();
15724 unsigned ArgMode = MI->getOperand(7).getImm();
15725 unsigned Align = MI->getOperand(8).getImm();
15727 // Memory Reference
15728 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15729 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15730 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15732 // Machine Information
15733 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15734 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15735 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15736 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15737 DebugLoc DL = MI->getDebugLoc();
15739 // struct va_list {
15742 // i64 overflow_area (address)
15743 // i64 reg_save_area (address)
15745 // sizeof(va_list) = 24
15746 // alignment(va_list) = 8
15748 unsigned TotalNumIntRegs = 6;
15749 unsigned TotalNumXMMRegs = 8;
15750 bool UseGPOffset = (ArgMode == 1);
15751 bool UseFPOffset = (ArgMode == 2);
15752 unsigned MaxOffset = TotalNumIntRegs * 8 +
15753 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15755 /* Align ArgSize to a multiple of 8 */
15756 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15757 bool NeedsAlign = (Align > 8);
15759 MachineBasicBlock *thisMBB = MBB;
15760 MachineBasicBlock *overflowMBB;
15761 MachineBasicBlock *offsetMBB;
15762 MachineBasicBlock *endMBB;
15764 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15765 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15766 unsigned OffsetReg = 0;
15768 if (!UseGPOffset && !UseFPOffset) {
15769 // If we only pull from the overflow region, we don't create a branch.
15770 // We don't need to alter control flow.
15771 OffsetDestReg = 0; // unused
15772 OverflowDestReg = DestReg;
15774 offsetMBB = nullptr;
15775 overflowMBB = thisMBB;
15778 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15779 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15780 // If not, pull from overflow_area. (branch to overflowMBB)
15785 // offsetMBB overflowMBB
15790 // Registers for the PHI in endMBB
15791 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15792 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15794 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15795 MachineFunction *MF = MBB->getParent();
15796 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15797 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15798 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15800 MachineFunction::iterator MBBIter = MBB;
15803 // Insert the new basic blocks
15804 MF->insert(MBBIter, offsetMBB);
15805 MF->insert(MBBIter, overflowMBB);
15806 MF->insert(MBBIter, endMBB);
15808 // Transfer the remainder of MBB and its successor edges to endMBB.
15809 endMBB->splice(endMBB->begin(), thisMBB,
15810 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15811 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15813 // Make offsetMBB and overflowMBB successors of thisMBB
15814 thisMBB->addSuccessor(offsetMBB);
15815 thisMBB->addSuccessor(overflowMBB);
15817 // endMBB is a successor of both offsetMBB and overflowMBB
15818 offsetMBB->addSuccessor(endMBB);
15819 overflowMBB->addSuccessor(endMBB);
15821 // Load the offset value into a register
15822 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15823 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15827 .addDisp(Disp, UseFPOffset ? 4 : 0)
15828 .addOperand(Segment)
15829 .setMemRefs(MMOBegin, MMOEnd);
15831 // Check if there is enough room left to pull this argument.
15832 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15834 .addImm(MaxOffset + 8 - ArgSizeA8);
15836 // Branch to "overflowMBB" if offset >= max
15837 // Fall through to "offsetMBB" otherwise
15838 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15839 .addMBB(overflowMBB);
15842 // In offsetMBB, emit code to use the reg_save_area.
15844 assert(OffsetReg != 0);
15846 // Read the reg_save_area address.
15847 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15848 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15853 .addOperand(Segment)
15854 .setMemRefs(MMOBegin, MMOEnd);
15856 // Zero-extend the offset
15857 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15858 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15861 .addImm(X86::sub_32bit);
15863 // Add the offset to the reg_save_area to get the final address.
15864 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15865 .addReg(OffsetReg64)
15866 .addReg(RegSaveReg);
15868 // Compute the offset for the next argument
15869 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15870 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15872 .addImm(UseFPOffset ? 16 : 8);
15874 // Store it back into the va_list.
15875 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15879 .addDisp(Disp, UseFPOffset ? 4 : 0)
15880 .addOperand(Segment)
15881 .addReg(NextOffsetReg)
15882 .setMemRefs(MMOBegin, MMOEnd);
15885 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15890 // Emit code to use overflow area
15893 // Load the overflow_area address into a register.
15894 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15895 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15900 .addOperand(Segment)
15901 .setMemRefs(MMOBegin, MMOEnd);
15903 // If we need to align it, do so. Otherwise, just copy the address
15904 // to OverflowDestReg.
15906 // Align the overflow address
15907 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15908 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15910 // aligned_addr = (addr + (align-1)) & ~(align-1)
15911 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15912 .addReg(OverflowAddrReg)
15915 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15917 .addImm(~(uint64_t)(Align-1));
15919 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15920 .addReg(OverflowAddrReg);
15923 // Compute the next overflow address after this argument.
15924 // (the overflow address should be kept 8-byte aligned)
15925 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15926 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15927 .addReg(OverflowDestReg)
15928 .addImm(ArgSizeA8);
15930 // Store the new overflow address.
15931 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15936 .addOperand(Segment)
15937 .addReg(NextAddrReg)
15938 .setMemRefs(MMOBegin, MMOEnd);
15940 // If we branched, emit the PHI to the front of endMBB.
15942 BuildMI(*endMBB, endMBB->begin(), DL,
15943 TII->get(X86::PHI), DestReg)
15944 .addReg(OffsetDestReg).addMBB(offsetMBB)
15945 .addReg(OverflowDestReg).addMBB(overflowMBB);
15948 // Erase the pseudo instruction
15949 MI->eraseFromParent();
15954 MachineBasicBlock *
15955 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15957 MachineBasicBlock *MBB) const {
15958 // Emit code to save XMM registers to the stack. The ABI says that the
15959 // number of registers to save is given in %al, so it's theoretically
15960 // possible to do an indirect jump trick to avoid saving all of them,
15961 // however this code takes a simpler approach and just executes all
15962 // of the stores if %al is non-zero. It's less code, and it's probably
15963 // easier on the hardware branch predictor, and stores aren't all that
15964 // expensive anyway.
15966 // Create the new basic blocks. One block contains all the XMM stores,
15967 // and one block is the final destination regardless of whether any
15968 // stores were performed.
15969 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15970 MachineFunction *F = MBB->getParent();
15971 MachineFunction::iterator MBBIter = MBB;
15973 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15974 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15975 F->insert(MBBIter, XMMSaveMBB);
15976 F->insert(MBBIter, EndMBB);
15978 // Transfer the remainder of MBB and its successor edges to EndMBB.
15979 EndMBB->splice(EndMBB->begin(), MBB,
15980 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15981 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15983 // The original block will now fall through to the XMM save block.
15984 MBB->addSuccessor(XMMSaveMBB);
15985 // The XMMSaveMBB will fall through to the end block.
15986 XMMSaveMBB->addSuccessor(EndMBB);
15988 // Now add the instructions.
15989 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15990 DebugLoc DL = MI->getDebugLoc();
15992 unsigned CountReg = MI->getOperand(0).getReg();
15993 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15994 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15996 if (!Subtarget->isTargetWin64()) {
15997 // If %al is 0, branch around the XMM save block.
15998 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15999 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16000 MBB->addSuccessor(EndMBB);
16003 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16004 // that was just emitted, but clearly shouldn't be "saved".
16005 assert((MI->getNumOperands() <= 3 ||
16006 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16007 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16008 && "Expected last argument to be EFLAGS");
16009 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16010 // In the XMM save block, save all the XMM argument registers.
16011 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16012 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16013 MachineMemOperand *MMO =
16014 F->getMachineMemOperand(
16015 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16016 MachineMemOperand::MOStore,
16017 /*Size=*/16, /*Align=*/16);
16018 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16019 .addFrameIndex(RegSaveFrameIndex)
16020 .addImm(/*Scale=*/1)
16021 .addReg(/*IndexReg=*/0)
16022 .addImm(/*Disp=*/Offset)
16023 .addReg(/*Segment=*/0)
16024 .addReg(MI->getOperand(i).getReg())
16025 .addMemOperand(MMO);
16028 MI->eraseFromParent(); // The pseudo instruction is gone now.
16033 // The EFLAGS operand of SelectItr might be missing a kill marker
16034 // because there were multiple uses of EFLAGS, and ISel didn't know
16035 // which to mark. Figure out whether SelectItr should have had a
16036 // kill marker, and set it if it should. Returns the correct kill
16038 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16039 MachineBasicBlock* BB,
16040 const TargetRegisterInfo* TRI) {
16041 // Scan forward through BB for a use/def of EFLAGS.
16042 MachineBasicBlock::iterator miI(std::next(SelectItr));
16043 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16044 const MachineInstr& mi = *miI;
16045 if (mi.readsRegister(X86::EFLAGS))
16047 if (mi.definesRegister(X86::EFLAGS))
16048 break; // Should have kill-flag - update below.
16051 // If we hit the end of the block, check whether EFLAGS is live into a
16053 if (miI == BB->end()) {
16054 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16055 sEnd = BB->succ_end();
16056 sItr != sEnd; ++sItr) {
16057 MachineBasicBlock* succ = *sItr;
16058 if (succ->isLiveIn(X86::EFLAGS))
16063 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16064 // out. SelectMI should have a kill flag on EFLAGS.
16065 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16069 MachineBasicBlock *
16070 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16071 MachineBasicBlock *BB) const {
16072 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16073 DebugLoc DL = MI->getDebugLoc();
16075 // To "insert" a SELECT_CC instruction, we actually have to insert the
16076 // diamond control-flow pattern. The incoming instruction knows the
16077 // destination vreg to set, the condition code register to branch on, the
16078 // true/false values to select between, and a branch opcode to use.
16079 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16080 MachineFunction::iterator It = BB;
16086 // cmpTY ccX, r1, r2
16088 // fallthrough --> copy0MBB
16089 MachineBasicBlock *thisMBB = BB;
16090 MachineFunction *F = BB->getParent();
16091 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16092 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16093 F->insert(It, copy0MBB);
16094 F->insert(It, sinkMBB);
16096 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16097 // live into the sink and copy blocks.
16098 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16099 if (!MI->killsRegister(X86::EFLAGS) &&
16100 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16101 copy0MBB->addLiveIn(X86::EFLAGS);
16102 sinkMBB->addLiveIn(X86::EFLAGS);
16105 // Transfer the remainder of BB and its successor edges to sinkMBB.
16106 sinkMBB->splice(sinkMBB->begin(), BB,
16107 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16108 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16110 // Add the true and fallthrough blocks as its successors.
16111 BB->addSuccessor(copy0MBB);
16112 BB->addSuccessor(sinkMBB);
16114 // Create the conditional branch instruction.
16116 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16117 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16120 // %FalseValue = ...
16121 // # fallthrough to sinkMBB
16122 copy0MBB->addSuccessor(sinkMBB);
16125 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16127 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16128 TII->get(X86::PHI), MI->getOperand(0).getReg())
16129 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16130 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16132 MI->eraseFromParent(); // The pseudo instruction is gone now.
16136 MachineBasicBlock *
16137 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16138 bool Is64Bit) const {
16139 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16140 DebugLoc DL = MI->getDebugLoc();
16141 MachineFunction *MF = BB->getParent();
16142 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16144 assert(MF->shouldSplitStack());
16146 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16147 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16150 // ... [Till the alloca]
16151 // If stacklet is not large enough, jump to mallocMBB
16154 // Allocate by subtracting from RSP
16155 // Jump to continueMBB
16158 // Allocate by call to runtime
16162 // [rest of original BB]
16165 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16166 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16167 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16169 MachineRegisterInfo &MRI = MF->getRegInfo();
16170 const TargetRegisterClass *AddrRegClass =
16171 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16173 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16174 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16175 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16176 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16177 sizeVReg = MI->getOperand(1).getReg(),
16178 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16180 MachineFunction::iterator MBBIter = BB;
16183 MF->insert(MBBIter, bumpMBB);
16184 MF->insert(MBBIter, mallocMBB);
16185 MF->insert(MBBIter, continueMBB);
16187 continueMBB->splice(continueMBB->begin(), BB,
16188 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16189 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16191 // Add code to the main basic block to check if the stack limit has been hit,
16192 // and if so, jump to mallocMBB otherwise to bumpMBB.
16193 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16194 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16195 .addReg(tmpSPVReg).addReg(sizeVReg);
16196 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16197 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16198 .addReg(SPLimitVReg);
16199 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16201 // bumpMBB simply decreases the stack pointer, since we know the current
16202 // stacklet has enough space.
16203 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16204 .addReg(SPLimitVReg);
16205 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16206 .addReg(SPLimitVReg);
16207 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16209 // Calls into a routine in libgcc to allocate more space from the heap.
16210 const uint32_t *RegMask =
16211 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16213 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16215 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16216 .addExternalSymbol("__morestack_allocate_stack_space")
16217 .addRegMask(RegMask)
16218 .addReg(X86::RDI, RegState::Implicit)
16219 .addReg(X86::RAX, RegState::ImplicitDefine);
16221 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16223 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16224 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16225 .addExternalSymbol("__morestack_allocate_stack_space")
16226 .addRegMask(RegMask)
16227 .addReg(X86::EAX, RegState::ImplicitDefine);
16231 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16234 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16235 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16236 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16238 // Set up the CFG correctly.
16239 BB->addSuccessor(bumpMBB);
16240 BB->addSuccessor(mallocMBB);
16241 mallocMBB->addSuccessor(continueMBB);
16242 bumpMBB->addSuccessor(continueMBB);
16244 // Take care of the PHI nodes.
16245 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16246 MI->getOperand(0).getReg())
16247 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16248 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16250 // Delete the original pseudo instruction.
16251 MI->eraseFromParent();
16254 return continueMBB;
16257 MachineBasicBlock *
16258 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16259 MachineBasicBlock *BB) const {
16260 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16261 DebugLoc DL = MI->getDebugLoc();
16263 assert(!Subtarget->isTargetMacho());
16265 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16266 // non-trivial part is impdef of ESP.
16268 if (Subtarget->isTargetWin64()) {
16269 if (Subtarget->isTargetCygMing()) {
16270 // ___chkstk(Mingw64):
16271 // Clobbers R10, R11, RAX and EFLAGS.
16273 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16274 .addExternalSymbol("___chkstk")
16275 .addReg(X86::RAX, RegState::Implicit)
16276 .addReg(X86::RSP, RegState::Implicit)
16277 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16278 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16279 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16281 // __chkstk(MSVCRT): does not update stack pointer.
16282 // Clobbers R10, R11 and EFLAGS.
16283 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16284 .addExternalSymbol("__chkstk")
16285 .addReg(X86::RAX, RegState::Implicit)
16286 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16287 // RAX has the offset to be subtracted from RSP.
16288 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16293 const char *StackProbeSymbol =
16294 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16296 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16297 .addExternalSymbol(StackProbeSymbol)
16298 .addReg(X86::EAX, RegState::Implicit)
16299 .addReg(X86::ESP, RegState::Implicit)
16300 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16301 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16302 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16305 MI->eraseFromParent(); // The pseudo instruction is gone now.
16309 MachineBasicBlock *
16310 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16311 MachineBasicBlock *BB) const {
16312 // This is pretty easy. We're taking the value that we received from
16313 // our load from the relocation, sticking it in either RDI (x86-64)
16314 // or EAX and doing an indirect call. The return value will then
16315 // be in the normal return register.
16316 const X86InstrInfo *TII
16317 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16318 DebugLoc DL = MI->getDebugLoc();
16319 MachineFunction *F = BB->getParent();
16321 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16322 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16324 // Get a register mask for the lowered call.
16325 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16326 // proper register mask.
16327 const uint32_t *RegMask =
16328 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16329 if (Subtarget->is64Bit()) {
16330 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16331 TII->get(X86::MOV64rm), X86::RDI)
16333 .addImm(0).addReg(0)
16334 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16335 MI->getOperand(3).getTargetFlags())
16337 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16338 addDirectMem(MIB, X86::RDI);
16339 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16340 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16341 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16342 TII->get(X86::MOV32rm), X86::EAX)
16344 .addImm(0).addReg(0)
16345 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16346 MI->getOperand(3).getTargetFlags())
16348 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16349 addDirectMem(MIB, X86::EAX);
16350 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16352 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16353 TII->get(X86::MOV32rm), X86::EAX)
16354 .addReg(TII->getGlobalBaseReg(F))
16355 .addImm(0).addReg(0)
16356 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16357 MI->getOperand(3).getTargetFlags())
16359 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16360 addDirectMem(MIB, X86::EAX);
16361 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16364 MI->eraseFromParent(); // The pseudo instruction is gone now.
16368 MachineBasicBlock *
16369 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16370 MachineBasicBlock *MBB) const {
16371 DebugLoc DL = MI->getDebugLoc();
16372 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16374 MachineFunction *MF = MBB->getParent();
16375 MachineRegisterInfo &MRI = MF->getRegInfo();
16377 const BasicBlock *BB = MBB->getBasicBlock();
16378 MachineFunction::iterator I = MBB;
16381 // Memory Reference
16382 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16383 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16386 unsigned MemOpndSlot = 0;
16388 unsigned CurOp = 0;
16390 DstReg = MI->getOperand(CurOp++).getReg();
16391 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16392 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16393 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16394 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16396 MemOpndSlot = CurOp;
16398 MVT PVT = getPointerTy();
16399 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16400 "Invalid Pointer Size!");
16402 // For v = setjmp(buf), we generate
16405 // buf[LabelOffset] = restoreMBB
16406 // SjLjSetup restoreMBB
16412 // v = phi(main, restore)
16417 MachineBasicBlock *thisMBB = MBB;
16418 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16419 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16420 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16421 MF->insert(I, mainMBB);
16422 MF->insert(I, sinkMBB);
16423 MF->push_back(restoreMBB);
16425 MachineInstrBuilder MIB;
16427 // Transfer the remainder of BB and its successor edges to sinkMBB.
16428 sinkMBB->splice(sinkMBB->begin(), MBB,
16429 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16430 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16433 unsigned PtrStoreOpc = 0;
16434 unsigned LabelReg = 0;
16435 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16436 Reloc::Model RM = getTargetMachine().getRelocationModel();
16437 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16438 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16440 // Prepare IP either in reg or imm.
16441 if (!UseImmLabel) {
16442 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16443 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16444 LabelReg = MRI.createVirtualRegister(PtrRC);
16445 if (Subtarget->is64Bit()) {
16446 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16450 .addMBB(restoreMBB)
16453 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16454 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16455 .addReg(XII->getGlobalBaseReg(MF))
16458 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16462 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16464 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16465 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16466 if (i == X86::AddrDisp)
16467 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16469 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16472 MIB.addReg(LabelReg);
16474 MIB.addMBB(restoreMBB);
16475 MIB.setMemRefs(MMOBegin, MMOEnd);
16477 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16478 .addMBB(restoreMBB);
16480 const X86RegisterInfo *RegInfo =
16481 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16482 MIB.addRegMask(RegInfo->getNoPreservedMask());
16483 thisMBB->addSuccessor(mainMBB);
16484 thisMBB->addSuccessor(restoreMBB);
16488 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16489 mainMBB->addSuccessor(sinkMBB);
16492 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16493 TII->get(X86::PHI), DstReg)
16494 .addReg(mainDstReg).addMBB(mainMBB)
16495 .addReg(restoreDstReg).addMBB(restoreMBB);
16498 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16499 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16500 restoreMBB->addSuccessor(sinkMBB);
16502 MI->eraseFromParent();
16506 MachineBasicBlock *
16507 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16508 MachineBasicBlock *MBB) const {
16509 DebugLoc DL = MI->getDebugLoc();
16510 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16512 MachineFunction *MF = MBB->getParent();
16513 MachineRegisterInfo &MRI = MF->getRegInfo();
16515 // Memory Reference
16516 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16517 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16519 MVT PVT = getPointerTy();
16520 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16521 "Invalid Pointer Size!");
16523 const TargetRegisterClass *RC =
16524 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16525 unsigned Tmp = MRI.createVirtualRegister(RC);
16526 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16527 const X86RegisterInfo *RegInfo =
16528 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16529 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16530 unsigned SP = RegInfo->getStackRegister();
16532 MachineInstrBuilder MIB;
16534 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16535 const int64_t SPOffset = 2 * PVT.getStoreSize();
16537 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16538 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16541 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16542 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16543 MIB.addOperand(MI->getOperand(i));
16544 MIB.setMemRefs(MMOBegin, MMOEnd);
16546 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16547 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16548 if (i == X86::AddrDisp)
16549 MIB.addDisp(MI->getOperand(i), LabelOffset);
16551 MIB.addOperand(MI->getOperand(i));
16553 MIB.setMemRefs(MMOBegin, MMOEnd);
16555 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16556 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16557 if (i == X86::AddrDisp)
16558 MIB.addDisp(MI->getOperand(i), SPOffset);
16560 MIB.addOperand(MI->getOperand(i));
16562 MIB.setMemRefs(MMOBegin, MMOEnd);
16564 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16566 MI->eraseFromParent();
16570 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16571 // accumulator loops. Writing back to the accumulator allows the coalescer
16572 // to remove extra copies in the loop.
16573 MachineBasicBlock *
16574 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16575 MachineBasicBlock *MBB) const {
16576 MachineOperand &AddendOp = MI->getOperand(3);
16578 // Bail out early if the addend isn't a register - we can't switch these.
16579 if (!AddendOp.isReg())
16582 MachineFunction &MF = *MBB->getParent();
16583 MachineRegisterInfo &MRI = MF.getRegInfo();
16585 // Check whether the addend is defined by a PHI:
16586 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16587 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16588 if (!AddendDef.isPHI())
16591 // Look for the following pattern:
16593 // %addend = phi [%entry, 0], [%loop, %result]
16595 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16599 // %addend = phi [%entry, 0], [%loop, %result]
16601 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16603 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16604 assert(AddendDef.getOperand(i).isReg());
16605 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16606 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16607 if (&PHISrcInst == MI) {
16608 // Found a matching instruction.
16609 unsigned NewFMAOpc = 0;
16610 switch (MI->getOpcode()) {
16611 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16612 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16613 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16614 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16615 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16616 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16617 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16618 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16619 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16620 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16621 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16622 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16623 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16624 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16625 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16626 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16627 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16628 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16629 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16630 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16631 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16632 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16633 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16634 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16635 default: llvm_unreachable("Unrecognized FMA variant.");
16638 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16639 MachineInstrBuilder MIB =
16640 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16641 .addOperand(MI->getOperand(0))
16642 .addOperand(MI->getOperand(3))
16643 .addOperand(MI->getOperand(2))
16644 .addOperand(MI->getOperand(1));
16645 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16646 MI->eraseFromParent();
16653 MachineBasicBlock *
16654 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16655 MachineBasicBlock *BB) const {
16656 switch (MI->getOpcode()) {
16657 default: llvm_unreachable("Unexpected instr type to insert");
16658 case X86::TAILJMPd64:
16659 case X86::TAILJMPr64:
16660 case X86::TAILJMPm64:
16661 llvm_unreachable("TAILJMP64 would not be touched here.");
16662 case X86::TCRETURNdi64:
16663 case X86::TCRETURNri64:
16664 case X86::TCRETURNmi64:
16666 case X86::WIN_ALLOCA:
16667 return EmitLoweredWinAlloca(MI, BB);
16668 case X86::SEG_ALLOCA_32:
16669 return EmitLoweredSegAlloca(MI, BB, false);
16670 case X86::SEG_ALLOCA_64:
16671 return EmitLoweredSegAlloca(MI, BB, true);
16672 case X86::TLSCall_32:
16673 case X86::TLSCall_64:
16674 return EmitLoweredTLSCall(MI, BB);
16675 case X86::CMOV_GR8:
16676 case X86::CMOV_FR32:
16677 case X86::CMOV_FR64:
16678 case X86::CMOV_V4F32:
16679 case X86::CMOV_V2F64:
16680 case X86::CMOV_V2I64:
16681 case X86::CMOV_V8F32:
16682 case X86::CMOV_V4F64:
16683 case X86::CMOV_V4I64:
16684 case X86::CMOV_V16F32:
16685 case X86::CMOV_V8F64:
16686 case X86::CMOV_V8I64:
16687 case X86::CMOV_GR16:
16688 case X86::CMOV_GR32:
16689 case X86::CMOV_RFP32:
16690 case X86::CMOV_RFP64:
16691 case X86::CMOV_RFP80:
16692 return EmitLoweredSelect(MI, BB);
16694 case X86::FP32_TO_INT16_IN_MEM:
16695 case X86::FP32_TO_INT32_IN_MEM:
16696 case X86::FP32_TO_INT64_IN_MEM:
16697 case X86::FP64_TO_INT16_IN_MEM:
16698 case X86::FP64_TO_INT32_IN_MEM:
16699 case X86::FP64_TO_INT64_IN_MEM:
16700 case X86::FP80_TO_INT16_IN_MEM:
16701 case X86::FP80_TO_INT32_IN_MEM:
16702 case X86::FP80_TO_INT64_IN_MEM: {
16703 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16704 DebugLoc DL = MI->getDebugLoc();
16706 // Change the floating point control register to use "round towards zero"
16707 // mode when truncating to an integer value.
16708 MachineFunction *F = BB->getParent();
16709 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16710 addFrameReference(BuildMI(*BB, MI, DL,
16711 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16713 // Load the old value of the high byte of the control word...
16715 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16716 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16719 // Set the high part to be round to zero...
16720 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16723 // Reload the modified control word now...
16724 addFrameReference(BuildMI(*BB, MI, DL,
16725 TII->get(X86::FLDCW16m)), CWFrameIdx);
16727 // Restore the memory image of control word to original value
16728 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16731 // Get the X86 opcode to use.
16733 switch (MI->getOpcode()) {
16734 default: llvm_unreachable("illegal opcode!");
16735 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16736 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16737 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16738 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16739 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16740 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16741 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16742 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16743 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16747 MachineOperand &Op = MI->getOperand(0);
16749 AM.BaseType = X86AddressMode::RegBase;
16750 AM.Base.Reg = Op.getReg();
16752 AM.BaseType = X86AddressMode::FrameIndexBase;
16753 AM.Base.FrameIndex = Op.getIndex();
16755 Op = MI->getOperand(1);
16757 AM.Scale = Op.getImm();
16758 Op = MI->getOperand(2);
16760 AM.IndexReg = Op.getImm();
16761 Op = MI->getOperand(3);
16762 if (Op.isGlobal()) {
16763 AM.GV = Op.getGlobal();
16765 AM.Disp = Op.getImm();
16767 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16768 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16770 // Reload the original control word now.
16771 addFrameReference(BuildMI(*BB, MI, DL,
16772 TII->get(X86::FLDCW16m)), CWFrameIdx);
16774 MI->eraseFromParent(); // The pseudo instruction is gone now.
16777 // String/text processing lowering.
16778 case X86::PCMPISTRM128REG:
16779 case X86::VPCMPISTRM128REG:
16780 case X86::PCMPISTRM128MEM:
16781 case X86::VPCMPISTRM128MEM:
16782 case X86::PCMPESTRM128REG:
16783 case X86::VPCMPESTRM128REG:
16784 case X86::PCMPESTRM128MEM:
16785 case X86::VPCMPESTRM128MEM:
16786 assert(Subtarget->hasSSE42() &&
16787 "Target must have SSE4.2 or AVX features enabled");
16788 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16790 // String/text processing lowering.
16791 case X86::PCMPISTRIREG:
16792 case X86::VPCMPISTRIREG:
16793 case X86::PCMPISTRIMEM:
16794 case X86::VPCMPISTRIMEM:
16795 case X86::PCMPESTRIREG:
16796 case X86::VPCMPESTRIREG:
16797 case X86::PCMPESTRIMEM:
16798 case X86::VPCMPESTRIMEM:
16799 assert(Subtarget->hasSSE42() &&
16800 "Target must have SSE4.2 or AVX features enabled");
16801 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16803 // Thread synchronization.
16805 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16809 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16811 // Atomic Lowering.
16812 case X86::ATOMAND8:
16813 case X86::ATOMAND16:
16814 case X86::ATOMAND32:
16815 case X86::ATOMAND64:
16818 case X86::ATOMOR16:
16819 case X86::ATOMOR32:
16820 case X86::ATOMOR64:
16822 case X86::ATOMXOR16:
16823 case X86::ATOMXOR8:
16824 case X86::ATOMXOR32:
16825 case X86::ATOMXOR64:
16827 case X86::ATOMNAND8:
16828 case X86::ATOMNAND16:
16829 case X86::ATOMNAND32:
16830 case X86::ATOMNAND64:
16832 case X86::ATOMMAX8:
16833 case X86::ATOMMAX16:
16834 case X86::ATOMMAX32:
16835 case X86::ATOMMAX64:
16837 case X86::ATOMMIN8:
16838 case X86::ATOMMIN16:
16839 case X86::ATOMMIN32:
16840 case X86::ATOMMIN64:
16842 case X86::ATOMUMAX8:
16843 case X86::ATOMUMAX16:
16844 case X86::ATOMUMAX32:
16845 case X86::ATOMUMAX64:
16847 case X86::ATOMUMIN8:
16848 case X86::ATOMUMIN16:
16849 case X86::ATOMUMIN32:
16850 case X86::ATOMUMIN64:
16851 return EmitAtomicLoadArith(MI, BB);
16853 // This group does 64-bit operations on a 32-bit host.
16854 case X86::ATOMAND6432:
16855 case X86::ATOMOR6432:
16856 case X86::ATOMXOR6432:
16857 case X86::ATOMNAND6432:
16858 case X86::ATOMADD6432:
16859 case X86::ATOMSUB6432:
16860 case X86::ATOMMAX6432:
16861 case X86::ATOMMIN6432:
16862 case X86::ATOMUMAX6432:
16863 case X86::ATOMUMIN6432:
16864 case X86::ATOMSWAP6432:
16865 return EmitAtomicLoadArith6432(MI, BB);
16867 case X86::VASTART_SAVE_XMM_REGS:
16868 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16870 case X86::VAARG_64:
16871 return EmitVAARG64WithCustomInserter(MI, BB);
16873 case X86::EH_SjLj_SetJmp32:
16874 case X86::EH_SjLj_SetJmp64:
16875 return emitEHSjLjSetJmp(MI, BB);
16877 case X86::EH_SjLj_LongJmp32:
16878 case X86::EH_SjLj_LongJmp64:
16879 return emitEHSjLjLongJmp(MI, BB);
16881 case TargetOpcode::STACKMAP:
16882 case TargetOpcode::PATCHPOINT:
16883 return emitPatchPoint(MI, BB);
16885 case X86::VFMADDPDr213r:
16886 case X86::VFMADDPSr213r:
16887 case X86::VFMADDSDr213r:
16888 case X86::VFMADDSSr213r:
16889 case X86::VFMSUBPDr213r:
16890 case X86::VFMSUBPSr213r:
16891 case X86::VFMSUBSDr213r:
16892 case X86::VFMSUBSSr213r:
16893 case X86::VFNMADDPDr213r:
16894 case X86::VFNMADDPSr213r:
16895 case X86::VFNMADDSDr213r:
16896 case X86::VFNMADDSSr213r:
16897 case X86::VFNMSUBPDr213r:
16898 case X86::VFNMSUBPSr213r:
16899 case X86::VFNMSUBSDr213r:
16900 case X86::VFNMSUBSSr213r:
16901 case X86::VFMADDPDr213rY:
16902 case X86::VFMADDPSr213rY:
16903 case X86::VFMSUBPDr213rY:
16904 case X86::VFMSUBPSr213rY:
16905 case X86::VFNMADDPDr213rY:
16906 case X86::VFNMADDPSr213rY:
16907 case X86::VFNMSUBPDr213rY:
16908 case X86::VFNMSUBPSr213rY:
16909 return emitFMA3Instr(MI, BB);
16913 //===----------------------------------------------------------------------===//
16914 // X86 Optimization Hooks
16915 //===----------------------------------------------------------------------===//
16917 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16920 const SelectionDAG &DAG,
16921 unsigned Depth) const {
16922 unsigned BitWidth = KnownZero.getBitWidth();
16923 unsigned Opc = Op.getOpcode();
16924 assert((Opc >= ISD::BUILTIN_OP_END ||
16925 Opc == ISD::INTRINSIC_WO_CHAIN ||
16926 Opc == ISD::INTRINSIC_W_CHAIN ||
16927 Opc == ISD::INTRINSIC_VOID) &&
16928 "Should use MaskedValueIsZero if you don't know whether Op"
16929 " is a target node!");
16931 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16945 // These nodes' second result is a boolean.
16946 if (Op.getResNo() == 0)
16949 case X86ISD::SETCC:
16950 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16952 case ISD::INTRINSIC_WO_CHAIN: {
16953 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16954 unsigned NumLoBits = 0;
16957 case Intrinsic::x86_sse_movmsk_ps:
16958 case Intrinsic::x86_avx_movmsk_ps_256:
16959 case Intrinsic::x86_sse2_movmsk_pd:
16960 case Intrinsic::x86_avx_movmsk_pd_256:
16961 case Intrinsic::x86_mmx_pmovmskb:
16962 case Intrinsic::x86_sse2_pmovmskb_128:
16963 case Intrinsic::x86_avx2_pmovmskb: {
16964 // High bits of movmskp{s|d}, pmovmskb are known zero.
16966 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16967 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16968 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16969 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16970 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16971 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16972 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16973 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16975 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16984 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16986 const SelectionDAG &,
16987 unsigned Depth) const {
16988 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16989 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16990 return Op.getValueType().getScalarType().getSizeInBits();
16996 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16997 /// node is a GlobalAddress + offset.
16998 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16999 const GlobalValue* &GA,
17000 int64_t &Offset) const {
17001 if (N->getOpcode() == X86ISD::Wrapper) {
17002 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17003 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17004 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17008 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17011 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17012 /// same as extracting the high 128-bit part of 256-bit vector and then
17013 /// inserting the result into the low part of a new 256-bit vector
17014 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17015 EVT VT = SVOp->getValueType(0);
17016 unsigned NumElems = VT.getVectorNumElements();
17018 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17019 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17020 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17021 SVOp->getMaskElt(j) >= 0)
17027 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17028 /// same as extracting the low 128-bit part of 256-bit vector and then
17029 /// inserting the result into the high part of a new 256-bit vector
17030 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17031 EVT VT = SVOp->getValueType(0);
17032 unsigned NumElems = VT.getVectorNumElements();
17034 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17035 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17036 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17037 SVOp->getMaskElt(j) >= 0)
17043 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17044 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17045 TargetLowering::DAGCombinerInfo &DCI,
17046 const X86Subtarget* Subtarget) {
17048 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17049 SDValue V1 = SVOp->getOperand(0);
17050 SDValue V2 = SVOp->getOperand(1);
17051 EVT VT = SVOp->getValueType(0);
17052 unsigned NumElems = VT.getVectorNumElements();
17054 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17055 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17059 // V UNDEF BUILD_VECTOR UNDEF
17061 // CONCAT_VECTOR CONCAT_VECTOR
17064 // RESULT: V + zero extended
17066 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17067 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17068 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17071 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17074 // To match the shuffle mask, the first half of the mask should
17075 // be exactly the first vector, and all the rest a splat with the
17076 // first element of the second one.
17077 for (unsigned i = 0; i != NumElems/2; ++i)
17078 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17079 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17082 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17083 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17084 if (Ld->hasNUsesOfValue(1, 0)) {
17085 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17086 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17088 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17090 Ld->getPointerInfo(),
17091 Ld->getAlignment(),
17092 false/*isVolatile*/, true/*ReadMem*/,
17093 false/*WriteMem*/);
17095 // Make sure the newly-created LOAD is in the same position as Ld in
17096 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17097 // and update uses of Ld's output chain to use the TokenFactor.
17098 if (Ld->hasAnyUseOfValue(1)) {
17099 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17100 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17101 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17102 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17103 SDValue(ResNode.getNode(), 1));
17106 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17110 // Emit a zeroed vector and insert the desired subvector on its
17112 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17113 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17114 return DCI.CombineTo(N, InsV);
17117 //===--------------------------------------------------------------------===//
17118 // Combine some shuffles into subvector extracts and inserts:
17121 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17122 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17123 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17124 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17125 return DCI.CombineTo(N, InsV);
17128 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17129 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17130 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17131 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17132 return DCI.CombineTo(N, InsV);
17138 /// PerformShuffleCombine - Performs several different shuffle combines.
17139 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17140 TargetLowering::DAGCombinerInfo &DCI,
17141 const X86Subtarget *Subtarget) {
17143 EVT VT = N->getValueType(0);
17145 // Don't create instructions with illegal types after legalize types has run.
17146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17147 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17150 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17151 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17152 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17153 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17155 // Only handle 128 wide vector from here on.
17156 if (!VT.is128BitVector())
17159 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17160 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17161 // consecutive, non-overlapping, and in the right order.
17162 SmallVector<SDValue, 16> Elts;
17163 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17164 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17166 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17169 /// PerformTruncateCombine - Converts truncate operation to
17170 /// a sequence of vector shuffle operations.
17171 /// It is possible when we truncate 256-bit vector to 128-bit vector
17172 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17173 TargetLowering::DAGCombinerInfo &DCI,
17174 const X86Subtarget *Subtarget) {
17178 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17179 /// specific shuffle of a load can be folded into a single element load.
17180 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17181 /// shuffles have been customed lowered so we need to handle those here.
17182 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17183 TargetLowering::DAGCombinerInfo &DCI) {
17184 if (DCI.isBeforeLegalizeOps())
17187 SDValue InVec = N->getOperand(0);
17188 SDValue EltNo = N->getOperand(1);
17190 if (!isa<ConstantSDNode>(EltNo))
17193 EVT VT = InVec.getValueType();
17195 bool HasShuffleIntoBitcast = false;
17196 if (InVec.getOpcode() == ISD::BITCAST) {
17197 // Don't duplicate a load with other uses.
17198 if (!InVec.hasOneUse())
17200 EVT BCVT = InVec.getOperand(0).getValueType();
17201 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17203 InVec = InVec.getOperand(0);
17204 HasShuffleIntoBitcast = true;
17207 if (!isTargetShuffle(InVec.getOpcode()))
17210 // Don't duplicate a load with other uses.
17211 if (!InVec.hasOneUse())
17214 SmallVector<int, 16> ShuffleMask;
17216 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17220 // Select the input vector, guarding against out of range extract vector.
17221 unsigned NumElems = VT.getVectorNumElements();
17222 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17223 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17224 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17225 : InVec.getOperand(1);
17227 // If inputs to shuffle are the same for both ops, then allow 2 uses
17228 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17230 if (LdNode.getOpcode() == ISD::BITCAST) {
17231 // Don't duplicate a load with other uses.
17232 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17235 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17236 LdNode = LdNode.getOperand(0);
17239 if (!ISD::isNormalLoad(LdNode.getNode()))
17242 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17244 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17247 if (HasShuffleIntoBitcast) {
17248 // If there's a bitcast before the shuffle, check if the load type and
17249 // alignment is valid.
17250 unsigned Align = LN0->getAlignment();
17251 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17252 unsigned NewAlign = TLI.getDataLayout()->
17253 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17255 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17259 // All checks match so transform back to vector_shuffle so that DAG combiner
17260 // can finish the job
17263 // Create shuffle node taking into account the case that its a unary shuffle
17264 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17265 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17266 InVec.getOperand(0), Shuffle,
17268 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17269 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17273 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17274 /// generation and convert it from being a bunch of shuffles and extracts
17275 /// to a simple store and scalar loads to extract the elements.
17276 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17277 TargetLowering::DAGCombinerInfo &DCI) {
17278 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17279 if (NewOp.getNode())
17282 SDValue InputVector = N->getOperand(0);
17284 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17285 // from mmx to v2i32 has a single usage.
17286 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17287 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17288 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17289 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17290 N->getValueType(0),
17291 InputVector.getNode()->getOperand(0));
17293 // Only operate on vectors of 4 elements, where the alternative shuffling
17294 // gets to be more expensive.
17295 if (InputVector.getValueType() != MVT::v4i32)
17298 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17299 // single use which is a sign-extend or zero-extend, and all elements are
17301 SmallVector<SDNode *, 4> Uses;
17302 unsigned ExtractedElements = 0;
17303 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17304 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17305 if (UI.getUse().getResNo() != InputVector.getResNo())
17308 SDNode *Extract = *UI;
17309 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17312 if (Extract->getValueType(0) != MVT::i32)
17314 if (!Extract->hasOneUse())
17316 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17317 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17319 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17322 // Record which element was extracted.
17323 ExtractedElements |=
17324 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17326 Uses.push_back(Extract);
17329 // If not all the elements were used, this may not be worthwhile.
17330 if (ExtractedElements != 15)
17333 // Ok, we've now decided to do the transformation.
17334 SDLoc dl(InputVector);
17336 // Store the value to a temporary stack slot.
17337 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17338 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17339 MachinePointerInfo(), false, false, 0);
17341 // Replace each use (extract) with a load of the appropriate element.
17342 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17343 UE = Uses.end(); UI != UE; ++UI) {
17344 SDNode *Extract = *UI;
17346 // cOMpute the element's address.
17347 SDValue Idx = Extract->getOperand(1);
17349 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17350 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17351 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17352 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17354 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17355 StackPtr, OffsetVal);
17357 // Load the scalar.
17358 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17359 ScalarAddr, MachinePointerInfo(),
17360 false, false, false, 0);
17362 // Replace the exact with the load.
17363 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17366 // The replacement was made in place; don't return anything.
17370 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17371 static std::pair<unsigned, bool>
17372 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17373 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17374 if (!VT.isVector())
17375 return std::make_pair(0, false);
17377 bool NeedSplit = false;
17378 switch (VT.getSimpleVT().SimpleTy) {
17379 default: return std::make_pair(0, false);
17383 if (!Subtarget->hasAVX2())
17385 if (!Subtarget->hasAVX())
17386 return std::make_pair(0, false);
17391 if (!Subtarget->hasSSE2())
17392 return std::make_pair(0, false);
17395 // SSE2 has only a small subset of the operations.
17396 bool hasUnsigned = Subtarget->hasSSE41() ||
17397 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17398 bool hasSigned = Subtarget->hasSSE41() ||
17399 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17401 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17404 // Check for x CC y ? x : y.
17405 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17406 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17411 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17414 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17417 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17420 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17422 // Check for x CC y ? y : x -- a min/max with reversed arms.
17423 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17424 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17429 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17432 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17435 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17438 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17442 return std::make_pair(Opc, NeedSplit);
17445 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17447 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17448 TargetLowering::DAGCombinerInfo &DCI,
17449 const X86Subtarget *Subtarget) {
17451 SDValue Cond = N->getOperand(0);
17452 // Get the LHS/RHS of the select.
17453 SDValue LHS = N->getOperand(1);
17454 SDValue RHS = N->getOperand(2);
17455 EVT VT = LHS.getValueType();
17456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17458 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17459 // instructions match the semantics of the common C idiom x<y?x:y but not
17460 // x<=y?x:y, because of how they handle negative zero (which can be
17461 // ignored in unsafe-math mode).
17462 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17463 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17464 (Subtarget->hasSSE2() ||
17465 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17466 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17468 unsigned Opcode = 0;
17469 // Check for x CC y ? x : y.
17470 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17471 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17475 // Converting this to a min would handle NaNs incorrectly, and swapping
17476 // the operands would cause it to handle comparisons between positive
17477 // and negative zero incorrectly.
17478 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17479 if (!DAG.getTarget().Options.UnsafeFPMath &&
17480 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17482 std::swap(LHS, RHS);
17484 Opcode = X86ISD::FMIN;
17487 // Converting this to a min would handle comparisons between positive
17488 // and negative zero incorrectly.
17489 if (!DAG.getTarget().Options.UnsafeFPMath &&
17490 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17492 Opcode = X86ISD::FMIN;
17495 // Converting this to a min would handle both negative zeros and NaNs
17496 // incorrectly, but we can swap the operands to fix both.
17497 std::swap(LHS, RHS);
17501 Opcode = X86ISD::FMIN;
17505 // Converting this to a max would handle comparisons between positive
17506 // and negative zero incorrectly.
17507 if (!DAG.getTarget().Options.UnsafeFPMath &&
17508 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17510 Opcode = X86ISD::FMAX;
17513 // Converting this to a max would handle NaNs incorrectly, and swapping
17514 // the operands would cause it to handle comparisons between positive
17515 // and negative zero incorrectly.
17516 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17517 if (!DAG.getTarget().Options.UnsafeFPMath &&
17518 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17520 std::swap(LHS, RHS);
17522 Opcode = X86ISD::FMAX;
17525 // Converting this to a max would handle both negative zeros and NaNs
17526 // incorrectly, but we can swap the operands to fix both.
17527 std::swap(LHS, RHS);
17531 Opcode = X86ISD::FMAX;
17534 // Check for x CC y ? y : x -- a min/max with reversed arms.
17535 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17536 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17540 // Converting this to a min would handle comparisons between positive
17541 // and negative zero incorrectly, and swapping the operands would
17542 // cause it to handle NaNs incorrectly.
17543 if (!DAG.getTarget().Options.UnsafeFPMath &&
17544 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17545 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17547 std::swap(LHS, RHS);
17549 Opcode = X86ISD::FMIN;
17552 // Converting this to a min would handle NaNs incorrectly.
17553 if (!DAG.getTarget().Options.UnsafeFPMath &&
17554 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17556 Opcode = X86ISD::FMIN;
17559 // Converting this to a min would handle both negative zeros and NaNs
17560 // incorrectly, but we can swap the operands to fix both.
17561 std::swap(LHS, RHS);
17565 Opcode = X86ISD::FMIN;
17569 // Converting this to a max would handle NaNs incorrectly.
17570 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17572 Opcode = X86ISD::FMAX;
17575 // Converting this to a max would handle comparisons between positive
17576 // and negative zero incorrectly, and swapping the operands would
17577 // cause it to handle NaNs incorrectly.
17578 if (!DAG.getTarget().Options.UnsafeFPMath &&
17579 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17580 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17582 std::swap(LHS, RHS);
17584 Opcode = X86ISD::FMAX;
17587 // Converting this to a max would handle both negative zeros and NaNs
17588 // incorrectly, but we can swap the operands to fix both.
17589 std::swap(LHS, RHS);
17593 Opcode = X86ISD::FMAX;
17599 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17602 EVT CondVT = Cond.getValueType();
17603 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17604 CondVT.getVectorElementType() == MVT::i1) {
17605 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17606 // lowering on AVX-512. In this case we convert it to
17607 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17608 // The same situation for all 128 and 256-bit vectors of i8 and i16
17609 EVT OpVT = LHS.getValueType();
17610 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17611 (OpVT.getVectorElementType() == MVT::i8 ||
17612 OpVT.getVectorElementType() == MVT::i16)) {
17613 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17614 DCI.AddToWorklist(Cond.getNode());
17615 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17618 // If this is a select between two integer constants, try to do some
17620 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17621 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17622 // Don't do this for crazy integer types.
17623 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17624 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17625 // so that TrueC (the true value) is larger than FalseC.
17626 bool NeedsCondInvert = false;
17628 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17629 // Efficiently invertible.
17630 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17631 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17632 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17633 NeedsCondInvert = true;
17634 std::swap(TrueC, FalseC);
17637 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17638 if (FalseC->getAPIntValue() == 0 &&
17639 TrueC->getAPIntValue().isPowerOf2()) {
17640 if (NeedsCondInvert) // Invert the condition if needed.
17641 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17642 DAG.getConstant(1, Cond.getValueType()));
17644 // Zero extend the condition if needed.
17645 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17647 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17648 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17649 DAG.getConstant(ShAmt, MVT::i8));
17652 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17653 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17654 if (NeedsCondInvert) // Invert the condition if needed.
17655 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17656 DAG.getConstant(1, Cond.getValueType()));
17658 // Zero extend the condition if needed.
17659 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17660 FalseC->getValueType(0), Cond);
17661 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17662 SDValue(FalseC, 0));
17665 // Optimize cases that will turn into an LEA instruction. This requires
17666 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17667 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17668 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17669 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17671 bool isFastMultiplier = false;
17673 switch ((unsigned char)Diff) {
17675 case 1: // result = add base, cond
17676 case 2: // result = lea base( , cond*2)
17677 case 3: // result = lea base(cond, cond*2)
17678 case 4: // result = lea base( , cond*4)
17679 case 5: // result = lea base(cond, cond*4)
17680 case 8: // result = lea base( , cond*8)
17681 case 9: // result = lea base(cond, cond*8)
17682 isFastMultiplier = true;
17687 if (isFastMultiplier) {
17688 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17689 if (NeedsCondInvert) // Invert the condition if needed.
17690 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17691 DAG.getConstant(1, Cond.getValueType()));
17693 // Zero extend the condition if needed.
17694 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17696 // Scale the condition by the difference.
17698 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17699 DAG.getConstant(Diff, Cond.getValueType()));
17701 // Add the base if non-zero.
17702 if (FalseC->getAPIntValue() != 0)
17703 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17704 SDValue(FalseC, 0));
17711 // Canonicalize max and min:
17712 // (x > y) ? x : y -> (x >= y) ? x : y
17713 // (x < y) ? x : y -> (x <= y) ? x : y
17714 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17715 // the need for an extra compare
17716 // against zero. e.g.
17717 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17719 // testl %edi, %edi
17721 // cmovgl %edi, %eax
17725 // cmovsl %eax, %edi
17726 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17727 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17728 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17729 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17734 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17735 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17736 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17737 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17742 // Early exit check
17743 if (!TLI.isTypeLegal(VT))
17746 // Match VSELECTs into subs with unsigned saturation.
17747 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17748 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17749 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17750 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17751 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17753 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17754 // left side invert the predicate to simplify logic below.
17756 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17758 CC = ISD::getSetCCInverse(CC, true);
17759 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17763 if (Other.getNode() && Other->getNumOperands() == 2 &&
17764 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17765 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17766 SDValue CondRHS = Cond->getOperand(1);
17768 // Look for a general sub with unsigned saturation first.
17769 // x >= y ? x-y : 0 --> subus x, y
17770 // x > y ? x-y : 0 --> subus x, y
17771 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17772 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17773 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17775 // If the RHS is a constant we have to reverse the const canonicalization.
17776 // x > C-1 ? x+-C : 0 --> subus x, C
17777 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17778 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17779 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17780 if (CondRHS.getConstantOperandVal(0) == -A-1)
17781 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17782 DAG.getConstant(-A, VT));
17785 // Another special case: If C was a sign bit, the sub has been
17786 // canonicalized into a xor.
17787 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17788 // it's safe to decanonicalize the xor?
17789 // x s< 0 ? x^C : 0 --> subus x, C
17790 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17791 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17792 isSplatVector(OpRHS.getNode())) {
17793 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17795 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17800 // Try to match a min/max vector operation.
17801 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17802 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17803 unsigned Opc = ret.first;
17804 bool NeedSplit = ret.second;
17806 if (Opc && NeedSplit) {
17807 unsigned NumElems = VT.getVectorNumElements();
17808 // Extract the LHS vectors
17809 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17810 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17812 // Extract the RHS vectors
17813 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17814 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17816 // Create min/max for each subvector
17817 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17818 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17820 // Merge the result
17821 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17823 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17826 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17827 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17828 // Check if SETCC has already been promoted
17829 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17830 // Check that condition value type matches vselect operand type
17833 assert(Cond.getValueType().isVector() &&
17834 "vector select expects a vector selector!");
17836 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17837 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17839 if (!TValIsAllOnes && !FValIsAllZeros) {
17840 // Try invert the condition if true value is not all 1s and false value
17842 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17843 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17845 if (TValIsAllZeros || FValIsAllOnes) {
17846 SDValue CC = Cond.getOperand(2);
17847 ISD::CondCode NewCC =
17848 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17849 Cond.getOperand(0).getValueType().isInteger());
17850 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17851 std::swap(LHS, RHS);
17852 TValIsAllOnes = FValIsAllOnes;
17853 FValIsAllZeros = TValIsAllZeros;
17857 if (TValIsAllOnes || FValIsAllZeros) {
17860 if (TValIsAllOnes && FValIsAllZeros)
17862 else if (TValIsAllOnes)
17863 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17864 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17865 else if (FValIsAllZeros)
17866 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17867 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17869 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17873 // Try to fold this VSELECT into a MOVSS/MOVSD
17874 if (N->getOpcode() == ISD::VSELECT &&
17875 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17876 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17877 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17878 bool CanFold = false;
17879 unsigned NumElems = Cond.getNumOperands();
17883 if (isZero(Cond.getOperand(0))) {
17886 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17887 // fold (vselect <0,-1> -> (movsd A, B)
17888 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17889 CanFold = isAllOnes(Cond.getOperand(i));
17890 } else if (isAllOnes(Cond.getOperand(0))) {
17894 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17895 // fold (vselect <-1,0> -> (movsd B, A)
17896 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17897 CanFold = isZero(Cond.getOperand(i));
17901 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17902 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17903 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17906 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17907 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17908 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17909 // (v2i64 (bitcast B)))))
17911 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17912 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17913 // (v2f64 (bitcast B)))))
17915 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17916 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17917 // (v2i64 (bitcast A)))))
17919 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17920 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17921 // (v2f64 (bitcast A)))))
17923 CanFold = (isZero(Cond.getOperand(0)) &&
17924 isZero(Cond.getOperand(1)) &&
17925 isAllOnes(Cond.getOperand(2)) &&
17926 isAllOnes(Cond.getOperand(3)));
17928 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17929 isAllOnes(Cond.getOperand(1)) &&
17930 isZero(Cond.getOperand(2)) &&
17931 isZero(Cond.getOperand(3))) {
17933 std::swap(LHS, RHS);
17937 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17938 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17939 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17940 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17942 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17948 // If we know that this node is legal then we know that it is going to be
17949 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17950 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17951 // to simplify previous instructions.
17952 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17953 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17954 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17956 // Don't optimize vector selects that map to mask-registers.
17960 // Check all uses of that condition operand to check whether it will be
17961 // consumed by non-BLEND instructions, which may depend on all bits are set
17963 for (SDNode::use_iterator I = Cond->use_begin(),
17964 E = Cond->use_end(); I != E; ++I)
17965 if (I->getOpcode() != ISD::VSELECT)
17966 // TODO: Add other opcodes eventually lowered into BLEND.
17969 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17970 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17972 APInt KnownZero, KnownOne;
17973 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17974 DCI.isBeforeLegalizeOps());
17975 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17976 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17977 DCI.CommitTargetLoweringOpt(TLO);
17983 // Check whether a boolean test is testing a boolean value generated by
17984 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17987 // Simplify the following patterns:
17988 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17989 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17990 // to (Op EFLAGS Cond)
17992 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17993 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17994 // to (Op EFLAGS !Cond)
17996 // where Op could be BRCOND or CMOV.
17998 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17999 // Quit if not CMP and SUB with its value result used.
18000 if (Cmp.getOpcode() != X86ISD::CMP &&
18001 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18004 // Quit if not used as a boolean value.
18005 if (CC != X86::COND_E && CC != X86::COND_NE)
18008 // Check CMP operands. One of them should be 0 or 1 and the other should be
18009 // an SetCC or extended from it.
18010 SDValue Op1 = Cmp.getOperand(0);
18011 SDValue Op2 = Cmp.getOperand(1);
18014 const ConstantSDNode* C = nullptr;
18015 bool needOppositeCond = (CC == X86::COND_E);
18016 bool checkAgainstTrue = false; // Is it a comparison against 1?
18018 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18020 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18022 else // Quit if all operands are not constants.
18025 if (C->getZExtValue() == 1) {
18026 needOppositeCond = !needOppositeCond;
18027 checkAgainstTrue = true;
18028 } else if (C->getZExtValue() != 0)
18029 // Quit if the constant is neither 0 or 1.
18032 bool truncatedToBoolWithAnd = false;
18033 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18034 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18035 SetCC.getOpcode() == ISD::TRUNCATE ||
18036 SetCC.getOpcode() == ISD::AND) {
18037 if (SetCC.getOpcode() == ISD::AND) {
18039 ConstantSDNode *CS;
18040 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18041 CS->getZExtValue() == 1)
18043 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18044 CS->getZExtValue() == 1)
18048 SetCC = SetCC.getOperand(OpIdx);
18049 truncatedToBoolWithAnd = true;
18051 SetCC = SetCC.getOperand(0);
18054 switch (SetCC.getOpcode()) {
18055 case X86ISD::SETCC_CARRY:
18056 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18057 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18058 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18059 // truncated to i1 using 'and'.
18060 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18062 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18063 "Invalid use of SETCC_CARRY!");
18065 case X86ISD::SETCC:
18066 // Set the condition code or opposite one if necessary.
18067 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18068 if (needOppositeCond)
18069 CC = X86::GetOppositeBranchCondition(CC);
18070 return SetCC.getOperand(1);
18071 case X86ISD::CMOV: {
18072 // Check whether false/true value has canonical one, i.e. 0 or 1.
18073 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18074 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18075 // Quit if true value is not a constant.
18078 // Quit if false value is not a constant.
18080 SDValue Op = SetCC.getOperand(0);
18081 // Skip 'zext' or 'trunc' node.
18082 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18083 Op.getOpcode() == ISD::TRUNCATE)
18084 Op = Op.getOperand(0);
18085 // A special case for rdrand/rdseed, where 0 is set if false cond is
18087 if ((Op.getOpcode() != X86ISD::RDRAND &&
18088 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18091 // Quit if false value is not the constant 0 or 1.
18092 bool FValIsFalse = true;
18093 if (FVal && FVal->getZExtValue() != 0) {
18094 if (FVal->getZExtValue() != 1)
18096 // If FVal is 1, opposite cond is needed.
18097 needOppositeCond = !needOppositeCond;
18098 FValIsFalse = false;
18100 // Quit if TVal is not the constant opposite of FVal.
18101 if (FValIsFalse && TVal->getZExtValue() != 1)
18103 if (!FValIsFalse && TVal->getZExtValue() != 0)
18105 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18106 if (needOppositeCond)
18107 CC = X86::GetOppositeBranchCondition(CC);
18108 return SetCC.getOperand(3);
18115 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18116 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18117 TargetLowering::DAGCombinerInfo &DCI,
18118 const X86Subtarget *Subtarget) {
18121 // If the flag operand isn't dead, don't touch this CMOV.
18122 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18125 SDValue FalseOp = N->getOperand(0);
18126 SDValue TrueOp = N->getOperand(1);
18127 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18128 SDValue Cond = N->getOperand(3);
18130 if (CC == X86::COND_E || CC == X86::COND_NE) {
18131 switch (Cond.getOpcode()) {
18135 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18136 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18137 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18143 Flags = checkBoolTestSetCCCombine(Cond, CC);
18144 if (Flags.getNode() &&
18145 // Extra check as FCMOV only supports a subset of X86 cond.
18146 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18147 SDValue Ops[] = { FalseOp, TrueOp,
18148 DAG.getConstant(CC, MVT::i8), Flags };
18149 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18152 // If this is a select between two integer constants, try to do some
18153 // optimizations. Note that the operands are ordered the opposite of SELECT
18155 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18156 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18157 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18158 // larger than FalseC (the false value).
18159 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18160 CC = X86::GetOppositeBranchCondition(CC);
18161 std::swap(TrueC, FalseC);
18162 std::swap(TrueOp, FalseOp);
18165 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18166 // This is efficient for any integer data type (including i8/i16) and
18168 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18169 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18170 DAG.getConstant(CC, MVT::i8), Cond);
18172 // Zero extend the condition if needed.
18173 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18175 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18176 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18177 DAG.getConstant(ShAmt, MVT::i8));
18178 if (N->getNumValues() == 2) // Dead flag value?
18179 return DCI.CombineTo(N, Cond, SDValue());
18183 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18184 // for any integer data type, including i8/i16.
18185 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18186 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18187 DAG.getConstant(CC, MVT::i8), Cond);
18189 // Zero extend the condition if needed.
18190 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18191 FalseC->getValueType(0), Cond);
18192 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18193 SDValue(FalseC, 0));
18195 if (N->getNumValues() == 2) // Dead flag value?
18196 return DCI.CombineTo(N, Cond, SDValue());
18200 // Optimize cases that will turn into an LEA instruction. This requires
18201 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18202 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18203 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18204 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18206 bool isFastMultiplier = false;
18208 switch ((unsigned char)Diff) {
18210 case 1: // result = add base, cond
18211 case 2: // result = lea base( , cond*2)
18212 case 3: // result = lea base(cond, cond*2)
18213 case 4: // result = lea base( , cond*4)
18214 case 5: // result = lea base(cond, cond*4)
18215 case 8: // result = lea base( , cond*8)
18216 case 9: // result = lea base(cond, cond*8)
18217 isFastMultiplier = true;
18222 if (isFastMultiplier) {
18223 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18224 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18225 DAG.getConstant(CC, MVT::i8), Cond);
18226 // Zero extend the condition if needed.
18227 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18229 // Scale the condition by the difference.
18231 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18232 DAG.getConstant(Diff, Cond.getValueType()));
18234 // Add the base if non-zero.
18235 if (FalseC->getAPIntValue() != 0)
18236 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18237 SDValue(FalseC, 0));
18238 if (N->getNumValues() == 2) // Dead flag value?
18239 return DCI.CombineTo(N, Cond, SDValue());
18246 // Handle these cases:
18247 // (select (x != c), e, c) -> select (x != c), e, x),
18248 // (select (x == c), c, e) -> select (x == c), x, e)
18249 // where the c is an integer constant, and the "select" is the combination
18250 // of CMOV and CMP.
18252 // The rationale for this change is that the conditional-move from a constant
18253 // needs two instructions, however, conditional-move from a register needs
18254 // only one instruction.
18256 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18257 // some instruction-combining opportunities. This opt needs to be
18258 // postponed as late as possible.
18260 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18261 // the DCI.xxxx conditions are provided to postpone the optimization as
18262 // late as possible.
18264 ConstantSDNode *CmpAgainst = nullptr;
18265 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18266 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18267 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18269 if (CC == X86::COND_NE &&
18270 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18271 CC = X86::GetOppositeBranchCondition(CC);
18272 std::swap(TrueOp, FalseOp);
18275 if (CC == X86::COND_E &&
18276 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18277 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18278 DAG.getConstant(CC, MVT::i8), Cond };
18279 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18287 /// PerformMulCombine - Optimize a single multiply with constant into two
18288 /// in order to implement it with two cheaper instructions, e.g.
18289 /// LEA + SHL, LEA + LEA.
18290 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18291 TargetLowering::DAGCombinerInfo &DCI) {
18292 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18295 EVT VT = N->getValueType(0);
18296 if (VT != MVT::i64)
18299 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18302 uint64_t MulAmt = C->getZExtValue();
18303 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18306 uint64_t MulAmt1 = 0;
18307 uint64_t MulAmt2 = 0;
18308 if ((MulAmt % 9) == 0) {
18310 MulAmt2 = MulAmt / 9;
18311 } else if ((MulAmt % 5) == 0) {
18313 MulAmt2 = MulAmt / 5;
18314 } else if ((MulAmt % 3) == 0) {
18316 MulAmt2 = MulAmt / 3;
18319 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18322 if (isPowerOf2_64(MulAmt2) &&
18323 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18324 // If second multiplifer is pow2, issue it first. We want the multiply by
18325 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18327 std::swap(MulAmt1, MulAmt2);
18330 if (isPowerOf2_64(MulAmt1))
18331 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18332 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18334 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18335 DAG.getConstant(MulAmt1, VT));
18337 if (isPowerOf2_64(MulAmt2))
18338 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18339 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18341 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18342 DAG.getConstant(MulAmt2, VT));
18344 // Do not add new nodes to DAG combiner worklist.
18345 DCI.CombineTo(N, NewMul, false);
18350 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18351 SDValue N0 = N->getOperand(0);
18352 SDValue N1 = N->getOperand(1);
18353 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18354 EVT VT = N0.getValueType();
18356 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18357 // since the result of setcc_c is all zero's or all ones.
18358 if (VT.isInteger() && !VT.isVector() &&
18359 N1C && N0.getOpcode() == ISD::AND &&
18360 N0.getOperand(1).getOpcode() == ISD::Constant) {
18361 SDValue N00 = N0.getOperand(0);
18362 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18363 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18364 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18365 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18366 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18367 APInt ShAmt = N1C->getAPIntValue();
18368 Mask = Mask.shl(ShAmt);
18370 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18371 N00, DAG.getConstant(Mask, VT));
18375 // Hardware support for vector shifts is sparse which makes us scalarize the
18376 // vector operations in many cases. Also, on sandybridge ADD is faster than
18378 // (shl V, 1) -> add V,V
18379 if (isSplatVector(N1.getNode())) {
18380 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18381 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18382 // We shift all of the values by one. In many cases we do not have
18383 // hardware support for this operation. This is better expressed as an ADD
18385 if (N1C && (1 == N1C->getZExtValue())) {
18386 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18393 /// \brief Returns a vector of 0s if the node in input is a vector logical
18394 /// shift by a constant amount which is known to be bigger than or equal
18395 /// to the vector element size in bits.
18396 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18397 const X86Subtarget *Subtarget) {
18398 EVT VT = N->getValueType(0);
18400 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18401 (!Subtarget->hasInt256() ||
18402 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18405 SDValue Amt = N->getOperand(1);
18407 if (isSplatVector(Amt.getNode())) {
18408 SDValue SclrAmt = Amt->getOperand(0);
18409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18410 APInt ShiftAmt = C->getAPIntValue();
18411 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18413 // SSE2/AVX2 logical shifts always return a vector of 0s
18414 // if the shift amount is bigger than or equal to
18415 // the element size. The constant shift amount will be
18416 // encoded as a 8-bit immediate.
18417 if (ShiftAmt.trunc(8).uge(MaxAmount))
18418 return getZeroVector(VT, Subtarget, DAG, DL);
18425 /// PerformShiftCombine - Combine shifts.
18426 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18427 TargetLowering::DAGCombinerInfo &DCI,
18428 const X86Subtarget *Subtarget) {
18429 if (N->getOpcode() == ISD::SHL) {
18430 SDValue V = PerformSHLCombine(N, DAG);
18431 if (V.getNode()) return V;
18434 if (N->getOpcode() != ISD::SRA) {
18435 // Try to fold this logical shift into a zero vector.
18436 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18437 if (V.getNode()) return V;
18443 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18444 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18445 // and friends. Likewise for OR -> CMPNEQSS.
18446 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18447 TargetLowering::DAGCombinerInfo &DCI,
18448 const X86Subtarget *Subtarget) {
18451 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18452 // we're requiring SSE2 for both.
18453 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18454 SDValue N0 = N->getOperand(0);
18455 SDValue N1 = N->getOperand(1);
18456 SDValue CMP0 = N0->getOperand(1);
18457 SDValue CMP1 = N1->getOperand(1);
18460 // The SETCCs should both refer to the same CMP.
18461 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18464 SDValue CMP00 = CMP0->getOperand(0);
18465 SDValue CMP01 = CMP0->getOperand(1);
18466 EVT VT = CMP00.getValueType();
18468 if (VT == MVT::f32 || VT == MVT::f64) {
18469 bool ExpectingFlags = false;
18470 // Check for any users that want flags:
18471 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18472 !ExpectingFlags && UI != UE; ++UI)
18473 switch (UI->getOpcode()) {
18478 ExpectingFlags = true;
18480 case ISD::CopyToReg:
18481 case ISD::SIGN_EXTEND:
18482 case ISD::ZERO_EXTEND:
18483 case ISD::ANY_EXTEND:
18487 if (!ExpectingFlags) {
18488 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18489 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18491 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18492 X86::CondCode tmp = cc0;
18497 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18498 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18499 // FIXME: need symbolic constants for these magic numbers.
18500 // See X86ATTInstPrinter.cpp:printSSECC().
18501 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18502 if (Subtarget->hasAVX512()) {
18503 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18504 CMP01, DAG.getConstant(x86cc, MVT::i8));
18505 if (N->getValueType(0) != MVT::i1)
18506 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18510 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18511 CMP00.getValueType(), CMP00, CMP01,
18512 DAG.getConstant(x86cc, MVT::i8));
18514 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18515 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18517 if (is64BitFP && !Subtarget->is64Bit()) {
18518 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18519 // 64-bit integer, since that's not a legal type. Since
18520 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18521 // bits, but can do this little dance to extract the lowest 32 bits
18522 // and work with those going forward.
18523 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18525 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18527 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18528 Vector32, DAG.getIntPtrConstant(0));
18532 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18533 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18534 DAG.getConstant(1, IntVT));
18535 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18536 return OneBitOfTruth;
18544 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18545 /// so it can be folded inside ANDNP.
18546 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18547 EVT VT = N->getValueType(0);
18549 // Match direct AllOnes for 128 and 256-bit vectors
18550 if (ISD::isBuildVectorAllOnes(N))
18553 // Look through a bit convert.
18554 if (N->getOpcode() == ISD::BITCAST)
18555 N = N->getOperand(0).getNode();
18557 // Sometimes the operand may come from a insert_subvector building a 256-bit
18559 if (VT.is256BitVector() &&
18560 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18561 SDValue V1 = N->getOperand(0);
18562 SDValue V2 = N->getOperand(1);
18564 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18565 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18566 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18567 ISD::isBuildVectorAllOnes(V2.getNode()))
18574 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18575 // register. In most cases we actually compare or select YMM-sized registers
18576 // and mixing the two types creates horrible code. This method optimizes
18577 // some of the transition sequences.
18578 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18579 TargetLowering::DAGCombinerInfo &DCI,
18580 const X86Subtarget *Subtarget) {
18581 EVT VT = N->getValueType(0);
18582 if (!VT.is256BitVector())
18585 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18586 N->getOpcode() == ISD::ZERO_EXTEND ||
18587 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18589 SDValue Narrow = N->getOperand(0);
18590 EVT NarrowVT = Narrow->getValueType(0);
18591 if (!NarrowVT.is128BitVector())
18594 if (Narrow->getOpcode() != ISD::XOR &&
18595 Narrow->getOpcode() != ISD::AND &&
18596 Narrow->getOpcode() != ISD::OR)
18599 SDValue N0 = Narrow->getOperand(0);
18600 SDValue N1 = Narrow->getOperand(1);
18603 // The Left side has to be a trunc.
18604 if (N0.getOpcode() != ISD::TRUNCATE)
18607 // The type of the truncated inputs.
18608 EVT WideVT = N0->getOperand(0)->getValueType(0);
18612 // The right side has to be a 'trunc' or a constant vector.
18613 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18614 bool RHSConst = (isSplatVector(N1.getNode()) &&
18615 isa<ConstantSDNode>(N1->getOperand(0)));
18616 if (!RHSTrunc && !RHSConst)
18619 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18621 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18624 // Set N0 and N1 to hold the inputs to the new wide operation.
18625 N0 = N0->getOperand(0);
18627 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18628 N1->getOperand(0));
18629 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18630 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18631 } else if (RHSTrunc) {
18632 N1 = N1->getOperand(0);
18635 // Generate the wide operation.
18636 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18637 unsigned Opcode = N->getOpcode();
18639 case ISD::ANY_EXTEND:
18641 case ISD::ZERO_EXTEND: {
18642 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18643 APInt Mask = APInt::getAllOnesValue(InBits);
18644 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18645 return DAG.getNode(ISD::AND, DL, VT,
18646 Op, DAG.getConstant(Mask, VT));
18648 case ISD::SIGN_EXTEND:
18649 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18650 Op, DAG.getValueType(NarrowVT));
18652 llvm_unreachable("Unexpected opcode");
18656 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18657 TargetLowering::DAGCombinerInfo &DCI,
18658 const X86Subtarget *Subtarget) {
18659 EVT VT = N->getValueType(0);
18660 if (DCI.isBeforeLegalizeOps())
18663 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18667 // Create BEXTR instructions
18668 // BEXTR is ((X >> imm) & (2**size-1))
18669 if (VT == MVT::i32 || VT == MVT::i64) {
18670 SDValue N0 = N->getOperand(0);
18671 SDValue N1 = N->getOperand(1);
18674 // Check for BEXTR.
18675 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18676 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18677 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18678 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18679 if (MaskNode && ShiftNode) {
18680 uint64_t Mask = MaskNode->getZExtValue();
18681 uint64_t Shift = ShiftNode->getZExtValue();
18682 if (isMask_64(Mask)) {
18683 uint64_t MaskSize = CountPopulation_64(Mask);
18684 if (Shift + MaskSize <= VT.getSizeInBits())
18685 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18686 DAG.getConstant(Shift | (MaskSize << 8), VT));
18694 // Want to form ANDNP nodes:
18695 // 1) In the hopes of then easily combining them with OR and AND nodes
18696 // to form PBLEND/PSIGN.
18697 // 2) To match ANDN packed intrinsics
18698 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18701 SDValue N0 = N->getOperand(0);
18702 SDValue N1 = N->getOperand(1);
18705 // Check LHS for vnot
18706 if (N0.getOpcode() == ISD::XOR &&
18707 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18708 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18709 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18711 // Check RHS for vnot
18712 if (N1.getOpcode() == ISD::XOR &&
18713 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18714 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18715 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18720 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18721 TargetLowering::DAGCombinerInfo &DCI,
18722 const X86Subtarget *Subtarget) {
18723 if (DCI.isBeforeLegalizeOps())
18726 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18730 SDValue N0 = N->getOperand(0);
18731 SDValue N1 = N->getOperand(1);
18732 EVT VT = N->getValueType(0);
18734 // look for psign/blend
18735 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18736 if (!Subtarget->hasSSSE3() ||
18737 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18740 // Canonicalize pandn to RHS
18741 if (N0.getOpcode() == X86ISD::ANDNP)
18743 // or (and (m, y), (pandn m, x))
18744 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18745 SDValue Mask = N1.getOperand(0);
18746 SDValue X = N1.getOperand(1);
18748 if (N0.getOperand(0) == Mask)
18749 Y = N0.getOperand(1);
18750 if (N0.getOperand(1) == Mask)
18751 Y = N0.getOperand(0);
18753 // Check to see if the mask appeared in both the AND and ANDNP and
18757 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18758 // Look through mask bitcast.
18759 if (Mask.getOpcode() == ISD::BITCAST)
18760 Mask = Mask.getOperand(0);
18761 if (X.getOpcode() == ISD::BITCAST)
18762 X = X.getOperand(0);
18763 if (Y.getOpcode() == ISD::BITCAST)
18764 Y = Y.getOperand(0);
18766 EVT MaskVT = Mask.getValueType();
18768 // Validate that the Mask operand is a vector sra node.
18769 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18770 // there is no psrai.b
18771 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18772 unsigned SraAmt = ~0;
18773 if (Mask.getOpcode() == ISD::SRA) {
18774 SDValue Amt = Mask.getOperand(1);
18775 if (isSplatVector(Amt.getNode())) {
18776 SDValue SclrAmt = Amt->getOperand(0);
18777 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18778 SraAmt = C->getZExtValue();
18780 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18781 SDValue SraC = Mask.getOperand(1);
18782 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18784 if ((SraAmt + 1) != EltBits)
18789 // Now we know we at least have a plendvb with the mask val. See if
18790 // we can form a psignb/w/d.
18791 // psign = x.type == y.type == mask.type && y = sub(0, x);
18792 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18793 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18794 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18795 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18796 "Unsupported VT for PSIGN");
18797 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18798 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18800 // PBLENDVB only available on SSE 4.1
18801 if (!Subtarget->hasSSE41())
18804 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18806 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18807 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18808 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18809 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18810 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18814 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18817 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18818 MachineFunction &MF = DAG.getMachineFunction();
18819 bool OptForSize = MF.getFunction()->getAttributes().
18820 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18822 // SHLD/SHRD instructions have lower register pressure, but on some
18823 // platforms they have higher latency than the equivalent
18824 // series of shifts/or that would otherwise be generated.
18825 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18826 // have higher latencies and we are not optimizing for size.
18827 if (!OptForSize && Subtarget->isSHLDSlow())
18830 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18832 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18834 if (!N0.hasOneUse() || !N1.hasOneUse())
18837 SDValue ShAmt0 = N0.getOperand(1);
18838 if (ShAmt0.getValueType() != MVT::i8)
18840 SDValue ShAmt1 = N1.getOperand(1);
18841 if (ShAmt1.getValueType() != MVT::i8)
18843 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18844 ShAmt0 = ShAmt0.getOperand(0);
18845 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18846 ShAmt1 = ShAmt1.getOperand(0);
18849 unsigned Opc = X86ISD::SHLD;
18850 SDValue Op0 = N0.getOperand(0);
18851 SDValue Op1 = N1.getOperand(0);
18852 if (ShAmt0.getOpcode() == ISD::SUB) {
18853 Opc = X86ISD::SHRD;
18854 std::swap(Op0, Op1);
18855 std::swap(ShAmt0, ShAmt1);
18858 unsigned Bits = VT.getSizeInBits();
18859 if (ShAmt1.getOpcode() == ISD::SUB) {
18860 SDValue Sum = ShAmt1.getOperand(0);
18861 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18862 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18863 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18864 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18865 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18866 return DAG.getNode(Opc, DL, VT,
18868 DAG.getNode(ISD::TRUNCATE, DL,
18871 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18872 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18874 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18875 return DAG.getNode(Opc, DL, VT,
18876 N0.getOperand(0), N1.getOperand(0),
18877 DAG.getNode(ISD::TRUNCATE, DL,
18884 // Generate NEG and CMOV for integer abs.
18885 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18886 EVT VT = N->getValueType(0);
18888 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18889 // 8-bit integer abs to NEG and CMOV.
18890 if (VT.isInteger() && VT.getSizeInBits() == 8)
18893 SDValue N0 = N->getOperand(0);
18894 SDValue N1 = N->getOperand(1);
18897 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18898 // and change it to SUB and CMOV.
18899 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18900 N0.getOpcode() == ISD::ADD &&
18901 N0.getOperand(1) == N1 &&
18902 N1.getOpcode() == ISD::SRA &&
18903 N1.getOperand(0) == N0.getOperand(0))
18904 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18905 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18906 // Generate SUB & CMOV.
18907 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18908 DAG.getConstant(0, VT), N0.getOperand(0));
18910 SDValue Ops[] = { N0.getOperand(0), Neg,
18911 DAG.getConstant(X86::COND_GE, MVT::i8),
18912 SDValue(Neg.getNode(), 1) };
18913 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18918 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18919 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18920 TargetLowering::DAGCombinerInfo &DCI,
18921 const X86Subtarget *Subtarget) {
18922 if (DCI.isBeforeLegalizeOps())
18925 if (Subtarget->hasCMov()) {
18926 SDValue RV = performIntegerAbsCombine(N, DAG);
18934 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18935 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18936 TargetLowering::DAGCombinerInfo &DCI,
18937 const X86Subtarget *Subtarget) {
18938 LoadSDNode *Ld = cast<LoadSDNode>(N);
18939 EVT RegVT = Ld->getValueType(0);
18940 EVT MemVT = Ld->getMemoryVT();
18942 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18943 unsigned RegSz = RegVT.getSizeInBits();
18945 // On Sandybridge unaligned 256bit loads are inefficient.
18946 ISD::LoadExtType Ext = Ld->getExtensionType();
18947 unsigned Alignment = Ld->getAlignment();
18948 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18949 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18950 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18951 unsigned NumElems = RegVT.getVectorNumElements();
18955 SDValue Ptr = Ld->getBasePtr();
18956 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18958 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18960 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18961 Ld->getPointerInfo(), Ld->isVolatile(),
18962 Ld->isNonTemporal(), Ld->isInvariant(),
18964 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18965 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18966 Ld->getPointerInfo(), Ld->isVolatile(),
18967 Ld->isNonTemporal(), Ld->isInvariant(),
18968 std::min(16U, Alignment));
18969 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18971 Load2.getValue(1));
18973 SDValue NewVec = DAG.getUNDEF(RegVT);
18974 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18975 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18976 return DCI.CombineTo(N, NewVec, TF, true);
18979 // If this is a vector EXT Load then attempt to optimize it using a
18980 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18981 // expansion is still better than scalar code.
18982 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18983 // emit a shuffle and a arithmetic shift.
18984 // TODO: It is possible to support ZExt by zeroing the undef values
18985 // during the shuffle phase or after the shuffle.
18986 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18987 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18988 assert(MemVT != RegVT && "Cannot extend to the same type");
18989 assert(MemVT.isVector() && "Must load a vector from memory");
18991 unsigned NumElems = RegVT.getVectorNumElements();
18992 unsigned MemSz = MemVT.getSizeInBits();
18993 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18995 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18998 // All sizes must be a power of two.
18999 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19002 // Attempt to load the original value using scalar loads.
19003 // Find the largest scalar type that divides the total loaded size.
19004 MVT SclrLoadTy = MVT::i8;
19005 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19006 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19007 MVT Tp = (MVT::SimpleValueType)tp;
19008 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19013 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19014 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19016 SclrLoadTy = MVT::f64;
19018 // Calculate the number of scalar loads that we need to perform
19019 // in order to load our vector from memory.
19020 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19021 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19024 unsigned loadRegZize = RegSz;
19025 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19028 // Represent our vector as a sequence of elements which are the
19029 // largest scalar that we can load.
19030 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19031 loadRegZize/SclrLoadTy.getSizeInBits());
19033 // Represent the data using the same element type that is stored in
19034 // memory. In practice, we ''widen'' MemVT.
19036 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19037 loadRegZize/MemVT.getScalarType().getSizeInBits());
19039 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19040 "Invalid vector type");
19042 // We can't shuffle using an illegal type.
19043 if (!TLI.isTypeLegal(WideVecVT))
19046 SmallVector<SDValue, 8> Chains;
19047 SDValue Ptr = Ld->getBasePtr();
19048 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19049 TLI.getPointerTy());
19050 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19052 for (unsigned i = 0; i < NumLoads; ++i) {
19053 // Perform a single load.
19054 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19055 Ptr, Ld->getPointerInfo(),
19056 Ld->isVolatile(), Ld->isNonTemporal(),
19057 Ld->isInvariant(), Ld->getAlignment());
19058 Chains.push_back(ScalarLoad.getValue(1));
19059 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19060 // another round of DAGCombining.
19062 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19064 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19065 ScalarLoad, DAG.getIntPtrConstant(i));
19067 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19070 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19072 // Bitcast the loaded value to a vector of the original element type, in
19073 // the size of the target vector type.
19074 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19075 unsigned SizeRatio = RegSz/MemSz;
19077 if (Ext == ISD::SEXTLOAD) {
19078 // If we have SSE4.1 we can directly emit a VSEXT node.
19079 if (Subtarget->hasSSE41()) {
19080 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19081 return DCI.CombineTo(N, Sext, TF, true);
19084 // Otherwise we'll shuffle the small elements in the high bits of the
19085 // larger type and perform an arithmetic shift. If the shift is not legal
19086 // it's better to scalarize.
19087 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19090 // Redistribute the loaded elements into the different locations.
19091 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19092 for (unsigned i = 0; i != NumElems; ++i)
19093 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19095 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19096 DAG.getUNDEF(WideVecVT),
19099 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19101 // Build the arithmetic shift.
19102 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19103 MemVT.getVectorElementType().getSizeInBits();
19104 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19105 DAG.getConstant(Amt, RegVT));
19107 return DCI.CombineTo(N, Shuff, TF, true);
19110 // Redistribute the loaded elements into the different locations.
19111 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19112 for (unsigned i = 0; i != NumElems; ++i)
19113 ShuffleVec[i*SizeRatio] = i;
19115 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19116 DAG.getUNDEF(WideVecVT),
19119 // Bitcast to the requested type.
19120 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19121 // Replace the original load with the new sequence
19122 // and return the new chain.
19123 return DCI.CombineTo(N, Shuff, TF, true);
19129 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19130 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19131 const X86Subtarget *Subtarget) {
19132 StoreSDNode *St = cast<StoreSDNode>(N);
19133 EVT VT = St->getValue().getValueType();
19134 EVT StVT = St->getMemoryVT();
19136 SDValue StoredVal = St->getOperand(1);
19137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19139 // If we are saving a concatenation of two XMM registers, perform two stores.
19140 // On Sandy Bridge, 256-bit memory operations are executed by two
19141 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19142 // memory operation.
19143 unsigned Alignment = St->getAlignment();
19144 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19145 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19146 StVT == VT && !IsAligned) {
19147 unsigned NumElems = VT.getVectorNumElements();
19151 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19152 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19154 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19155 SDValue Ptr0 = St->getBasePtr();
19156 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19158 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19159 St->getPointerInfo(), St->isVolatile(),
19160 St->isNonTemporal(), Alignment);
19161 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19162 St->getPointerInfo(), St->isVolatile(),
19163 St->isNonTemporal(),
19164 std::min(16U, Alignment));
19165 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19168 // Optimize trunc store (of multiple scalars) to shuffle and store.
19169 // First, pack all of the elements in one place. Next, store to memory
19170 // in fewer chunks.
19171 if (St->isTruncatingStore() && VT.isVector()) {
19172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19173 unsigned NumElems = VT.getVectorNumElements();
19174 assert(StVT != VT && "Cannot truncate to the same type");
19175 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19176 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19178 // From, To sizes and ElemCount must be pow of two
19179 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19180 // We are going to use the original vector elt for storing.
19181 // Accumulated smaller vector elements must be a multiple of the store size.
19182 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19184 unsigned SizeRatio = FromSz / ToSz;
19186 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19188 // Create a type on which we perform the shuffle
19189 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19190 StVT.getScalarType(), NumElems*SizeRatio);
19192 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19194 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19195 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19196 for (unsigned i = 0; i != NumElems; ++i)
19197 ShuffleVec[i] = i * SizeRatio;
19199 // Can't shuffle using an illegal type.
19200 if (!TLI.isTypeLegal(WideVecVT))
19203 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19204 DAG.getUNDEF(WideVecVT),
19206 // At this point all of the data is stored at the bottom of the
19207 // register. We now need to save it to mem.
19209 // Find the largest store unit
19210 MVT StoreType = MVT::i8;
19211 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19212 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19213 MVT Tp = (MVT::SimpleValueType)tp;
19214 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19218 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19219 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19220 (64 <= NumElems * ToSz))
19221 StoreType = MVT::f64;
19223 // Bitcast the original vector into a vector of store-size units
19224 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19225 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19226 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19227 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19228 SmallVector<SDValue, 8> Chains;
19229 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19230 TLI.getPointerTy());
19231 SDValue Ptr = St->getBasePtr();
19233 // Perform one or more big stores into memory.
19234 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19235 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19236 StoreType, ShuffWide,
19237 DAG.getIntPtrConstant(i));
19238 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19239 St->getPointerInfo(), St->isVolatile(),
19240 St->isNonTemporal(), St->getAlignment());
19241 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19242 Chains.push_back(Ch);
19245 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19248 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19249 // the FP state in cases where an emms may be missing.
19250 // A preferable solution to the general problem is to figure out the right
19251 // places to insert EMMS. This qualifies as a quick hack.
19253 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19254 if (VT.getSizeInBits() != 64)
19257 const Function *F = DAG.getMachineFunction().getFunction();
19258 bool NoImplicitFloatOps = F->getAttributes().
19259 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19260 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19261 && Subtarget->hasSSE2();
19262 if ((VT.isVector() ||
19263 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19264 isa<LoadSDNode>(St->getValue()) &&
19265 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19266 St->getChain().hasOneUse() && !St->isVolatile()) {
19267 SDNode* LdVal = St->getValue().getNode();
19268 LoadSDNode *Ld = nullptr;
19269 int TokenFactorIndex = -1;
19270 SmallVector<SDValue, 8> Ops;
19271 SDNode* ChainVal = St->getChain().getNode();
19272 // Must be a store of a load. We currently handle two cases: the load
19273 // is a direct child, and it's under an intervening TokenFactor. It is
19274 // possible to dig deeper under nested TokenFactors.
19275 if (ChainVal == LdVal)
19276 Ld = cast<LoadSDNode>(St->getChain());
19277 else if (St->getValue().hasOneUse() &&
19278 ChainVal->getOpcode() == ISD::TokenFactor) {
19279 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19280 if (ChainVal->getOperand(i).getNode() == LdVal) {
19281 TokenFactorIndex = i;
19282 Ld = cast<LoadSDNode>(St->getValue());
19284 Ops.push_back(ChainVal->getOperand(i));
19288 if (!Ld || !ISD::isNormalLoad(Ld))
19291 // If this is not the MMX case, i.e. we are just turning i64 load/store
19292 // into f64 load/store, avoid the transformation if there are multiple
19293 // uses of the loaded value.
19294 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19299 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19300 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19302 if (Subtarget->is64Bit() || F64IsLegal) {
19303 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19304 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19305 Ld->getPointerInfo(), Ld->isVolatile(),
19306 Ld->isNonTemporal(), Ld->isInvariant(),
19307 Ld->getAlignment());
19308 SDValue NewChain = NewLd.getValue(1);
19309 if (TokenFactorIndex != -1) {
19310 Ops.push_back(NewChain);
19311 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19313 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19314 St->getPointerInfo(),
19315 St->isVolatile(), St->isNonTemporal(),
19316 St->getAlignment());
19319 // Otherwise, lower to two pairs of 32-bit loads / stores.
19320 SDValue LoAddr = Ld->getBasePtr();
19321 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19322 DAG.getConstant(4, MVT::i32));
19324 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19325 Ld->getPointerInfo(),
19326 Ld->isVolatile(), Ld->isNonTemporal(),
19327 Ld->isInvariant(), Ld->getAlignment());
19328 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19329 Ld->getPointerInfo().getWithOffset(4),
19330 Ld->isVolatile(), Ld->isNonTemporal(),
19332 MinAlign(Ld->getAlignment(), 4));
19334 SDValue NewChain = LoLd.getValue(1);
19335 if (TokenFactorIndex != -1) {
19336 Ops.push_back(LoLd);
19337 Ops.push_back(HiLd);
19338 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19341 LoAddr = St->getBasePtr();
19342 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19343 DAG.getConstant(4, MVT::i32));
19345 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19346 St->getPointerInfo(),
19347 St->isVolatile(), St->isNonTemporal(),
19348 St->getAlignment());
19349 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19350 St->getPointerInfo().getWithOffset(4),
19352 St->isNonTemporal(),
19353 MinAlign(St->getAlignment(), 4));
19354 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19359 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19360 /// and return the operands for the horizontal operation in LHS and RHS. A
19361 /// horizontal operation performs the binary operation on successive elements
19362 /// of its first operand, then on successive elements of its second operand,
19363 /// returning the resulting values in a vector. For example, if
19364 /// A = < float a0, float a1, float a2, float a3 >
19366 /// B = < float b0, float b1, float b2, float b3 >
19367 /// then the result of doing a horizontal operation on A and B is
19368 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19369 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19370 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19371 /// set to A, RHS to B, and the routine returns 'true'.
19372 /// Note that the binary operation should have the property that if one of the
19373 /// operands is UNDEF then the result is UNDEF.
19374 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19375 // Look for the following pattern: if
19376 // A = < float a0, float a1, float a2, float a3 >
19377 // B = < float b0, float b1, float b2, float b3 >
19379 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19380 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19381 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19382 // which is A horizontal-op B.
19384 // At least one of the operands should be a vector shuffle.
19385 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19386 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19389 MVT VT = LHS.getSimpleValueType();
19391 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19392 "Unsupported vector type for horizontal add/sub");
19394 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19395 // operate independently on 128-bit lanes.
19396 unsigned NumElts = VT.getVectorNumElements();
19397 unsigned NumLanes = VT.getSizeInBits()/128;
19398 unsigned NumLaneElts = NumElts / NumLanes;
19399 assert((NumLaneElts % 2 == 0) &&
19400 "Vector type should have an even number of elements in each lane");
19401 unsigned HalfLaneElts = NumLaneElts/2;
19403 // View LHS in the form
19404 // LHS = VECTOR_SHUFFLE A, B, LMask
19405 // If LHS is not a shuffle then pretend it is the shuffle
19406 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19407 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19410 SmallVector<int, 16> LMask(NumElts);
19411 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19412 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19413 A = LHS.getOperand(0);
19414 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19415 B = LHS.getOperand(1);
19416 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19417 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19419 if (LHS.getOpcode() != ISD::UNDEF)
19421 for (unsigned i = 0; i != NumElts; ++i)
19425 // Likewise, view RHS in the form
19426 // RHS = VECTOR_SHUFFLE C, D, RMask
19428 SmallVector<int, 16> RMask(NumElts);
19429 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19430 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19431 C = RHS.getOperand(0);
19432 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19433 D = RHS.getOperand(1);
19434 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19435 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19437 if (RHS.getOpcode() != ISD::UNDEF)
19439 for (unsigned i = 0; i != NumElts; ++i)
19443 // Check that the shuffles are both shuffling the same vectors.
19444 if (!(A == C && B == D) && !(A == D && B == C))
19447 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19448 if (!A.getNode() && !B.getNode())
19451 // If A and B occur in reverse order in RHS, then "swap" them (which means
19452 // rewriting the mask).
19454 CommuteVectorShuffleMask(RMask, NumElts);
19456 // At this point LHS and RHS are equivalent to
19457 // LHS = VECTOR_SHUFFLE A, B, LMask
19458 // RHS = VECTOR_SHUFFLE A, B, RMask
19459 // Check that the masks correspond to performing a horizontal operation.
19460 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19461 for (unsigned i = 0; i != NumLaneElts; ++i) {
19462 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19464 // Ignore any UNDEF components.
19465 if (LIdx < 0 || RIdx < 0 ||
19466 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19467 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19470 // Check that successive elements are being operated on. If not, this is
19471 // not a horizontal operation.
19472 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19473 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19474 if (!(LIdx == Index && RIdx == Index + 1) &&
19475 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19480 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19481 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19485 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19486 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19487 const X86Subtarget *Subtarget) {
19488 EVT VT = N->getValueType(0);
19489 SDValue LHS = N->getOperand(0);
19490 SDValue RHS = N->getOperand(1);
19492 // Try to synthesize horizontal adds from adds of shuffles.
19493 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19494 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19495 isHorizontalBinOp(LHS, RHS, true))
19496 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19500 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19501 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19502 const X86Subtarget *Subtarget) {
19503 EVT VT = N->getValueType(0);
19504 SDValue LHS = N->getOperand(0);
19505 SDValue RHS = N->getOperand(1);
19507 // Try to synthesize horizontal subs from subs of shuffles.
19508 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19509 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19510 isHorizontalBinOp(LHS, RHS, false))
19511 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19515 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19516 /// X86ISD::FXOR nodes.
19517 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19518 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19519 // F[X]OR(0.0, x) -> x
19520 // F[X]OR(x, 0.0) -> x
19521 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19522 if (C->getValueAPF().isPosZero())
19523 return N->getOperand(1);
19524 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19525 if (C->getValueAPF().isPosZero())
19526 return N->getOperand(0);
19530 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19531 /// X86ISD::FMAX nodes.
19532 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19533 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19535 // Only perform optimizations if UnsafeMath is used.
19536 if (!DAG.getTarget().Options.UnsafeFPMath)
19539 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19540 // into FMINC and FMAXC, which are Commutative operations.
19541 unsigned NewOp = 0;
19542 switch (N->getOpcode()) {
19543 default: llvm_unreachable("unknown opcode");
19544 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19545 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19548 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19549 N->getOperand(0), N->getOperand(1));
19552 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19553 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19554 // FAND(0.0, x) -> 0.0
19555 // FAND(x, 0.0) -> 0.0
19556 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19557 if (C->getValueAPF().isPosZero())
19558 return N->getOperand(0);
19559 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19560 if (C->getValueAPF().isPosZero())
19561 return N->getOperand(1);
19565 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19566 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19567 // FANDN(x, 0.0) -> 0.0
19568 // FANDN(0.0, x) -> x
19569 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19570 if (C->getValueAPF().isPosZero())
19571 return N->getOperand(1);
19572 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19573 if (C->getValueAPF().isPosZero())
19574 return N->getOperand(1);
19578 static SDValue PerformBTCombine(SDNode *N,
19580 TargetLowering::DAGCombinerInfo &DCI) {
19581 // BT ignores high bits in the bit index operand.
19582 SDValue Op1 = N->getOperand(1);
19583 if (Op1.hasOneUse()) {
19584 unsigned BitWidth = Op1.getValueSizeInBits();
19585 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19586 APInt KnownZero, KnownOne;
19587 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19588 !DCI.isBeforeLegalizeOps());
19589 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19590 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19591 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19592 DCI.CommitTargetLoweringOpt(TLO);
19597 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19598 SDValue Op = N->getOperand(0);
19599 if (Op.getOpcode() == ISD::BITCAST)
19600 Op = Op.getOperand(0);
19601 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19602 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19603 VT.getVectorElementType().getSizeInBits() ==
19604 OpVT.getVectorElementType().getSizeInBits()) {
19605 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19610 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19611 const X86Subtarget *Subtarget) {
19612 EVT VT = N->getValueType(0);
19613 if (!VT.isVector())
19616 SDValue N0 = N->getOperand(0);
19617 SDValue N1 = N->getOperand(1);
19618 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19621 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19622 // both SSE and AVX2 since there is no sign-extended shift right
19623 // operation on a vector with 64-bit elements.
19624 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19625 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19626 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19627 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19628 SDValue N00 = N0.getOperand(0);
19630 // EXTLOAD has a better solution on AVX2,
19631 // it may be replaced with X86ISD::VSEXT node.
19632 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19633 if (!ISD::isNormalLoad(N00.getNode()))
19636 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19637 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19639 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19645 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19646 TargetLowering::DAGCombinerInfo &DCI,
19647 const X86Subtarget *Subtarget) {
19648 if (!DCI.isBeforeLegalizeOps())
19651 if (!Subtarget->hasFp256())
19654 EVT VT = N->getValueType(0);
19655 if (VT.isVector() && VT.getSizeInBits() == 256) {
19656 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19664 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19665 const X86Subtarget* Subtarget) {
19667 EVT VT = N->getValueType(0);
19669 // Let legalize expand this if it isn't a legal type yet.
19670 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19673 EVT ScalarVT = VT.getScalarType();
19674 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19675 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19678 SDValue A = N->getOperand(0);
19679 SDValue B = N->getOperand(1);
19680 SDValue C = N->getOperand(2);
19682 bool NegA = (A.getOpcode() == ISD::FNEG);
19683 bool NegB = (B.getOpcode() == ISD::FNEG);
19684 bool NegC = (C.getOpcode() == ISD::FNEG);
19686 // Negative multiplication when NegA xor NegB
19687 bool NegMul = (NegA != NegB);
19689 A = A.getOperand(0);
19691 B = B.getOperand(0);
19693 C = C.getOperand(0);
19697 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19699 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19701 return DAG.getNode(Opcode, dl, VT, A, B, C);
19704 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19705 TargetLowering::DAGCombinerInfo &DCI,
19706 const X86Subtarget *Subtarget) {
19707 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19708 // (and (i32 x86isd::setcc_carry), 1)
19709 // This eliminates the zext. This transformation is necessary because
19710 // ISD::SETCC is always legalized to i8.
19712 SDValue N0 = N->getOperand(0);
19713 EVT VT = N->getValueType(0);
19715 if (N0.getOpcode() == ISD::AND &&
19717 N0.getOperand(0).hasOneUse()) {
19718 SDValue N00 = N0.getOperand(0);
19719 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19720 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19721 if (!C || C->getZExtValue() != 1)
19723 return DAG.getNode(ISD::AND, dl, VT,
19724 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19725 N00.getOperand(0), N00.getOperand(1)),
19726 DAG.getConstant(1, VT));
19730 if (N0.getOpcode() == ISD::TRUNCATE &&
19732 N0.getOperand(0).hasOneUse()) {
19733 SDValue N00 = N0.getOperand(0);
19734 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19735 return DAG.getNode(ISD::AND, dl, VT,
19736 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19737 N00.getOperand(0), N00.getOperand(1)),
19738 DAG.getConstant(1, VT));
19741 if (VT.is256BitVector()) {
19742 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19750 // Optimize x == -y --> x+y == 0
19751 // x != -y --> x+y != 0
19752 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19753 const X86Subtarget* Subtarget) {
19754 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19755 SDValue LHS = N->getOperand(0);
19756 SDValue RHS = N->getOperand(1);
19757 EVT VT = N->getValueType(0);
19760 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19761 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19762 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19763 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19764 LHS.getValueType(), RHS, LHS.getOperand(1));
19765 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19766 addV, DAG.getConstant(0, addV.getValueType()), CC);
19768 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19769 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19770 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19771 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19772 RHS.getValueType(), LHS, RHS.getOperand(1));
19773 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19774 addV, DAG.getConstant(0, addV.getValueType()), CC);
19777 if (VT.getScalarType() == MVT::i1) {
19778 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19779 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19780 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19781 if (!IsSEXT0 && !IsVZero0)
19783 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19784 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19785 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19787 if (!IsSEXT1 && !IsVZero1)
19790 if (IsSEXT0 && IsVZero1) {
19791 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19792 if (CC == ISD::SETEQ)
19793 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19794 return LHS.getOperand(0);
19796 if (IsSEXT1 && IsVZero0) {
19797 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19798 if (CC == ISD::SETEQ)
19799 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19800 return RHS.getOperand(0);
19807 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19808 // as "sbb reg,reg", since it can be extended without zext and produces
19809 // an all-ones bit which is more useful than 0/1 in some cases.
19810 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19813 return DAG.getNode(ISD::AND, DL, VT,
19814 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19815 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19816 DAG.getConstant(1, VT));
19817 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19818 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19819 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19820 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19823 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19824 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19825 TargetLowering::DAGCombinerInfo &DCI,
19826 const X86Subtarget *Subtarget) {
19828 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19829 SDValue EFLAGS = N->getOperand(1);
19831 if (CC == X86::COND_A) {
19832 // Try to convert COND_A into COND_B in an attempt to facilitate
19833 // materializing "setb reg".
19835 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19836 // cannot take an immediate as its first operand.
19838 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19839 EFLAGS.getValueType().isInteger() &&
19840 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19841 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19842 EFLAGS.getNode()->getVTList(),
19843 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19844 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19845 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19849 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19850 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19852 if (CC == X86::COND_B)
19853 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19857 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19858 if (Flags.getNode()) {
19859 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19860 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19866 // Optimize branch condition evaluation.
19868 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19869 TargetLowering::DAGCombinerInfo &DCI,
19870 const X86Subtarget *Subtarget) {
19872 SDValue Chain = N->getOperand(0);
19873 SDValue Dest = N->getOperand(1);
19874 SDValue EFLAGS = N->getOperand(3);
19875 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19879 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19880 if (Flags.getNode()) {
19881 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19882 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19889 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19890 const X86TargetLowering *XTLI) {
19891 SDValue Op0 = N->getOperand(0);
19892 EVT InVT = Op0->getValueType(0);
19894 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19895 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19897 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19898 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19899 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19902 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19903 // a 32-bit target where SSE doesn't support i64->FP operations.
19904 if (Op0.getOpcode() == ISD::LOAD) {
19905 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19906 EVT VT = Ld->getValueType(0);
19907 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19908 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19909 !XTLI->getSubtarget()->is64Bit() &&
19911 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19912 Ld->getChain(), Op0, DAG);
19913 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19920 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19921 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19922 X86TargetLowering::DAGCombinerInfo &DCI) {
19923 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19924 // the result is either zero or one (depending on the input carry bit).
19925 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19926 if (X86::isZeroNode(N->getOperand(0)) &&
19927 X86::isZeroNode(N->getOperand(1)) &&
19928 // We don't have a good way to replace an EFLAGS use, so only do this when
19930 SDValue(N, 1).use_empty()) {
19932 EVT VT = N->getValueType(0);
19933 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19934 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19935 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19936 DAG.getConstant(X86::COND_B,MVT::i8),
19938 DAG.getConstant(1, VT));
19939 return DCI.CombineTo(N, Res1, CarryOut);
19945 // fold (add Y, (sete X, 0)) -> adc 0, Y
19946 // (add Y, (setne X, 0)) -> sbb -1, Y
19947 // (sub (sete X, 0), Y) -> sbb 0, Y
19948 // (sub (setne X, 0), Y) -> adc -1, Y
19949 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19952 // Look through ZExts.
19953 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19954 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19957 SDValue SetCC = Ext.getOperand(0);
19958 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19961 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19962 if (CC != X86::COND_E && CC != X86::COND_NE)
19965 SDValue Cmp = SetCC.getOperand(1);
19966 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19967 !X86::isZeroNode(Cmp.getOperand(1)) ||
19968 !Cmp.getOperand(0).getValueType().isInteger())
19971 SDValue CmpOp0 = Cmp.getOperand(0);
19972 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19973 DAG.getConstant(1, CmpOp0.getValueType()));
19975 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19976 if (CC == X86::COND_NE)
19977 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19978 DL, OtherVal.getValueType(), OtherVal,
19979 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19980 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19981 DL, OtherVal.getValueType(), OtherVal,
19982 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19985 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19986 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19987 const X86Subtarget *Subtarget) {
19988 EVT VT = N->getValueType(0);
19989 SDValue Op0 = N->getOperand(0);
19990 SDValue Op1 = N->getOperand(1);
19992 // Try to synthesize horizontal adds from adds of shuffles.
19993 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19994 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19995 isHorizontalBinOp(Op0, Op1, true))
19996 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19998 return OptimizeConditionalInDecrement(N, DAG);
20001 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20002 const X86Subtarget *Subtarget) {
20003 SDValue Op0 = N->getOperand(0);
20004 SDValue Op1 = N->getOperand(1);
20006 // X86 can't encode an immediate LHS of a sub. See if we can push the
20007 // negation into a preceding instruction.
20008 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20009 // If the RHS of the sub is a XOR with one use and a constant, invert the
20010 // immediate. Then add one to the LHS of the sub so we can turn
20011 // X-Y -> X+~Y+1, saving one register.
20012 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20013 isa<ConstantSDNode>(Op1.getOperand(1))) {
20014 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20015 EVT VT = Op0.getValueType();
20016 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20018 DAG.getConstant(~XorC, VT));
20019 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20020 DAG.getConstant(C->getAPIntValue()+1, VT));
20024 // Try to synthesize horizontal adds from adds of shuffles.
20025 EVT VT = N->getValueType(0);
20026 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20027 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20028 isHorizontalBinOp(Op0, Op1, true))
20029 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20031 return OptimizeConditionalInDecrement(N, DAG);
20034 /// performVZEXTCombine - Performs build vector combines
20035 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20036 TargetLowering::DAGCombinerInfo &DCI,
20037 const X86Subtarget *Subtarget) {
20038 // (vzext (bitcast (vzext (x)) -> (vzext x)
20039 SDValue In = N->getOperand(0);
20040 while (In.getOpcode() == ISD::BITCAST)
20041 In = In.getOperand(0);
20043 if (In.getOpcode() != X86ISD::VZEXT)
20046 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20050 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20051 DAGCombinerInfo &DCI) const {
20052 SelectionDAG &DAG = DCI.DAG;
20053 switch (N->getOpcode()) {
20055 case ISD::EXTRACT_VECTOR_ELT:
20056 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20058 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20059 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20060 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20061 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20062 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20063 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20066 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20067 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20068 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20069 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20070 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20071 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20072 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20073 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20074 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20076 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20078 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20079 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20080 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20081 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20082 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20083 case ISD::ANY_EXTEND:
20084 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20085 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20086 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20087 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20088 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20089 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20090 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20091 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20092 case X86ISD::SHUFP: // Handle all target specific shuffles
20093 case X86ISD::PALIGNR:
20094 case X86ISD::UNPCKH:
20095 case X86ISD::UNPCKL:
20096 case X86ISD::MOVHLPS:
20097 case X86ISD::MOVLHPS:
20098 case X86ISD::PSHUFD:
20099 case X86ISD::PSHUFHW:
20100 case X86ISD::PSHUFLW:
20101 case X86ISD::MOVSS:
20102 case X86ISD::MOVSD:
20103 case X86ISD::VPERMILP:
20104 case X86ISD::VPERM2X128:
20105 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20106 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20112 /// isTypeDesirableForOp - Return true if the target has native support for
20113 /// the specified value type and it is 'desirable' to use the type for the
20114 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20115 /// instruction encodings are longer and some i16 instructions are slow.
20116 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20117 if (!isTypeLegal(VT))
20119 if (VT != MVT::i16)
20126 case ISD::SIGN_EXTEND:
20127 case ISD::ZERO_EXTEND:
20128 case ISD::ANY_EXTEND:
20141 /// IsDesirableToPromoteOp - This method query the target whether it is
20142 /// beneficial for dag combiner to promote the specified node. If true, it
20143 /// should return the desired promotion type by reference.
20144 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20145 EVT VT = Op.getValueType();
20146 if (VT != MVT::i16)
20149 bool Promote = false;
20150 bool Commute = false;
20151 switch (Op.getOpcode()) {
20154 LoadSDNode *LD = cast<LoadSDNode>(Op);
20155 // If the non-extending load has a single use and it's not live out, then it
20156 // might be folded.
20157 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20158 Op.hasOneUse()*/) {
20159 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20160 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20161 // The only case where we'd want to promote LOAD (rather then it being
20162 // promoted as an operand is when it's only use is liveout.
20163 if (UI->getOpcode() != ISD::CopyToReg)
20170 case ISD::SIGN_EXTEND:
20171 case ISD::ZERO_EXTEND:
20172 case ISD::ANY_EXTEND:
20177 SDValue N0 = Op.getOperand(0);
20178 // Look out for (store (shl (load), x)).
20179 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20192 SDValue N0 = Op.getOperand(0);
20193 SDValue N1 = Op.getOperand(1);
20194 if (!Commute && MayFoldLoad(N1))
20196 // Avoid disabling potential load folding opportunities.
20197 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20199 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20209 //===----------------------------------------------------------------------===//
20210 // X86 Inline Assembly Support
20211 //===----------------------------------------------------------------------===//
20214 // Helper to match a string separated by whitespace.
20215 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20216 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20218 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20219 StringRef piece(*args[i]);
20220 if (!s.startswith(piece)) // Check if the piece matches.
20223 s = s.substr(piece.size());
20224 StringRef::size_type pos = s.find_first_not_of(" \t");
20225 if (pos == 0) // We matched a prefix.
20233 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20236 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20238 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20239 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20240 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20241 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20243 if (AsmPieces.size() == 3)
20245 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20252 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20253 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20255 std::string AsmStr = IA->getAsmString();
20257 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20258 if (!Ty || Ty->getBitWidth() % 16 != 0)
20261 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20262 SmallVector<StringRef, 4> AsmPieces;
20263 SplitString(AsmStr, AsmPieces, ";\n");
20265 switch (AsmPieces.size()) {
20266 default: return false;
20268 // FIXME: this should verify that we are targeting a 486 or better. If not,
20269 // we will turn this bswap into something that will be lowered to logical
20270 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20271 // lower so don't worry about this.
20273 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20274 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20275 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20276 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20277 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20278 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20279 // No need to check constraints, nothing other than the equivalent of
20280 // "=r,0" would be valid here.
20281 return IntrinsicLowering::LowerToByteSwap(CI);
20284 // rorw $$8, ${0:w} --> llvm.bswap.i16
20285 if (CI->getType()->isIntegerTy(16) &&
20286 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20287 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20288 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20290 const std::string &ConstraintsStr = IA->getConstraintString();
20291 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20292 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20293 if (clobbersFlagRegisters(AsmPieces))
20294 return IntrinsicLowering::LowerToByteSwap(CI);
20298 if (CI->getType()->isIntegerTy(32) &&
20299 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20300 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20301 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20302 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20304 const std::string &ConstraintsStr = IA->getConstraintString();
20305 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20306 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20307 if (clobbersFlagRegisters(AsmPieces))
20308 return IntrinsicLowering::LowerToByteSwap(CI);
20311 if (CI->getType()->isIntegerTy(64)) {
20312 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20313 if (Constraints.size() >= 2 &&
20314 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20315 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20316 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20317 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20318 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20319 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20320 return IntrinsicLowering::LowerToByteSwap(CI);
20328 /// getConstraintType - Given a constraint letter, return the type of
20329 /// constraint it is for this target.
20330 X86TargetLowering::ConstraintType
20331 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20332 if (Constraint.size() == 1) {
20333 switch (Constraint[0]) {
20344 return C_RegisterClass;
20368 return TargetLowering::getConstraintType(Constraint);
20371 /// Examine constraint type and operand type and determine a weight value.
20372 /// This object must already have been set up with the operand type
20373 /// and the current alternative constraint selected.
20374 TargetLowering::ConstraintWeight
20375 X86TargetLowering::getSingleConstraintMatchWeight(
20376 AsmOperandInfo &info, const char *constraint) const {
20377 ConstraintWeight weight = CW_Invalid;
20378 Value *CallOperandVal = info.CallOperandVal;
20379 // If we don't have a value, we can't do a match,
20380 // but allow it at the lowest weight.
20381 if (!CallOperandVal)
20383 Type *type = CallOperandVal->getType();
20384 // Look at the constraint type.
20385 switch (*constraint) {
20387 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20398 if (CallOperandVal->getType()->isIntegerTy())
20399 weight = CW_SpecificReg;
20404 if (type->isFloatingPointTy())
20405 weight = CW_SpecificReg;
20408 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20409 weight = CW_SpecificReg;
20413 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20414 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20415 weight = CW_Register;
20418 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20419 if (C->getZExtValue() <= 31)
20420 weight = CW_Constant;
20424 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20425 if (C->getZExtValue() <= 63)
20426 weight = CW_Constant;
20430 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20431 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20432 weight = CW_Constant;
20436 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20437 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20438 weight = CW_Constant;
20442 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20443 if (C->getZExtValue() <= 3)
20444 weight = CW_Constant;
20448 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20449 if (C->getZExtValue() <= 0xff)
20450 weight = CW_Constant;
20455 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20456 weight = CW_Constant;
20460 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20461 if ((C->getSExtValue() >= -0x80000000LL) &&
20462 (C->getSExtValue() <= 0x7fffffffLL))
20463 weight = CW_Constant;
20467 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20468 if (C->getZExtValue() <= 0xffffffff)
20469 weight = CW_Constant;
20476 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20477 /// with another that has more specific requirements based on the type of the
20478 /// corresponding operand.
20479 const char *X86TargetLowering::
20480 LowerXConstraint(EVT ConstraintVT) const {
20481 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20482 // 'f' like normal targets.
20483 if (ConstraintVT.isFloatingPoint()) {
20484 if (Subtarget->hasSSE2())
20486 if (Subtarget->hasSSE1())
20490 return TargetLowering::LowerXConstraint(ConstraintVT);
20493 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20494 /// vector. If it is invalid, don't add anything to Ops.
20495 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20496 std::string &Constraint,
20497 std::vector<SDValue>&Ops,
20498 SelectionDAG &DAG) const {
20501 // Only support length 1 constraints for now.
20502 if (Constraint.length() > 1) return;
20504 char ConstraintLetter = Constraint[0];
20505 switch (ConstraintLetter) {
20508 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20509 if (C->getZExtValue() <= 31) {
20510 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20517 if (C->getZExtValue() <= 63) {
20518 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20524 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20525 if (isInt<8>(C->getSExtValue())) {
20526 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20533 if (C->getZExtValue() <= 255) {
20534 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20540 // 32-bit signed value
20541 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20542 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20543 C->getSExtValue())) {
20544 // Widen to 64 bits here to get it sign extended.
20545 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20548 // FIXME gcc accepts some relocatable values here too, but only in certain
20549 // memory models; it's complicated.
20554 // 32-bit unsigned value
20555 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20556 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20557 C->getZExtValue())) {
20558 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20562 // FIXME gcc accepts some relocatable values here too, but only in certain
20563 // memory models; it's complicated.
20567 // Literal immediates are always ok.
20568 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20569 // Widen to 64 bits here to get it sign extended.
20570 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20574 // In any sort of PIC mode addresses need to be computed at runtime by
20575 // adding in a register or some sort of table lookup. These can't
20576 // be used as immediates.
20577 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20580 // If we are in non-pic codegen mode, we allow the address of a global (with
20581 // an optional displacement) to be used with 'i'.
20582 GlobalAddressSDNode *GA = nullptr;
20583 int64_t Offset = 0;
20585 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20587 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20588 Offset += GA->getOffset();
20590 } else if (Op.getOpcode() == ISD::ADD) {
20591 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20592 Offset += C->getZExtValue();
20593 Op = Op.getOperand(0);
20596 } else if (Op.getOpcode() == ISD::SUB) {
20597 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20598 Offset += -C->getZExtValue();
20599 Op = Op.getOperand(0);
20604 // Otherwise, this isn't something we can handle, reject it.
20608 const GlobalValue *GV = GA->getGlobal();
20609 // If we require an extra load to get this address, as in PIC mode, we
20610 // can't accept it.
20611 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20612 getTargetMachine())))
20615 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20616 GA->getValueType(0), Offset);
20621 if (Result.getNode()) {
20622 Ops.push_back(Result);
20625 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20628 std::pair<unsigned, const TargetRegisterClass*>
20629 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20631 // First, see if this is a constraint that directly corresponds to an LLVM
20633 if (Constraint.size() == 1) {
20634 // GCC Constraint Letters
20635 switch (Constraint[0]) {
20637 // TODO: Slight differences here in allocation order and leaving
20638 // RIP in the class. Do they matter any more here than they do
20639 // in the normal allocation?
20640 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20641 if (Subtarget->is64Bit()) {
20642 if (VT == MVT::i32 || VT == MVT::f32)
20643 return std::make_pair(0U, &X86::GR32RegClass);
20644 if (VT == MVT::i16)
20645 return std::make_pair(0U, &X86::GR16RegClass);
20646 if (VT == MVT::i8 || VT == MVT::i1)
20647 return std::make_pair(0U, &X86::GR8RegClass);
20648 if (VT == MVT::i64 || VT == MVT::f64)
20649 return std::make_pair(0U, &X86::GR64RegClass);
20652 // 32-bit fallthrough
20653 case 'Q': // Q_REGS
20654 if (VT == MVT::i32 || VT == MVT::f32)
20655 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20656 if (VT == MVT::i16)
20657 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20658 if (VT == MVT::i8 || VT == MVT::i1)
20659 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20660 if (VT == MVT::i64)
20661 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20663 case 'r': // GENERAL_REGS
20664 case 'l': // INDEX_REGS
20665 if (VT == MVT::i8 || VT == MVT::i1)
20666 return std::make_pair(0U, &X86::GR8RegClass);
20667 if (VT == MVT::i16)
20668 return std::make_pair(0U, &X86::GR16RegClass);
20669 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20670 return std::make_pair(0U, &X86::GR32RegClass);
20671 return std::make_pair(0U, &X86::GR64RegClass);
20672 case 'R': // LEGACY_REGS
20673 if (VT == MVT::i8 || VT == MVT::i1)
20674 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20675 if (VT == MVT::i16)
20676 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20677 if (VT == MVT::i32 || !Subtarget->is64Bit())
20678 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20679 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20680 case 'f': // FP Stack registers.
20681 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20682 // value to the correct fpstack register class.
20683 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20684 return std::make_pair(0U, &X86::RFP32RegClass);
20685 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20686 return std::make_pair(0U, &X86::RFP64RegClass);
20687 return std::make_pair(0U, &X86::RFP80RegClass);
20688 case 'y': // MMX_REGS if MMX allowed.
20689 if (!Subtarget->hasMMX()) break;
20690 return std::make_pair(0U, &X86::VR64RegClass);
20691 case 'Y': // SSE_REGS if SSE2 allowed
20692 if (!Subtarget->hasSSE2()) break;
20694 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20695 if (!Subtarget->hasSSE1()) break;
20697 switch (VT.SimpleTy) {
20699 // Scalar SSE types.
20702 return std::make_pair(0U, &X86::FR32RegClass);
20705 return std::make_pair(0U, &X86::FR64RegClass);
20713 return std::make_pair(0U, &X86::VR128RegClass);
20721 return std::make_pair(0U, &X86::VR256RegClass);
20726 return std::make_pair(0U, &X86::VR512RegClass);
20732 // Use the default implementation in TargetLowering to convert the register
20733 // constraint into a member of a register class.
20734 std::pair<unsigned, const TargetRegisterClass*> Res;
20735 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20737 // Not found as a standard register?
20739 // Map st(0) -> st(7) -> ST0
20740 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20741 tolower(Constraint[1]) == 's' &&
20742 tolower(Constraint[2]) == 't' &&
20743 Constraint[3] == '(' &&
20744 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20745 Constraint[5] == ')' &&
20746 Constraint[6] == '}') {
20748 Res.first = X86::ST0+Constraint[4]-'0';
20749 Res.second = &X86::RFP80RegClass;
20753 // GCC allows "st(0)" to be called just plain "st".
20754 if (StringRef("{st}").equals_lower(Constraint)) {
20755 Res.first = X86::ST0;
20756 Res.second = &X86::RFP80RegClass;
20761 if (StringRef("{flags}").equals_lower(Constraint)) {
20762 Res.first = X86::EFLAGS;
20763 Res.second = &X86::CCRRegClass;
20767 // 'A' means EAX + EDX.
20768 if (Constraint == "A") {
20769 Res.first = X86::EAX;
20770 Res.second = &X86::GR32_ADRegClass;
20776 // Otherwise, check to see if this is a register class of the wrong value
20777 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20778 // turn into {ax},{dx}.
20779 if (Res.second->hasType(VT))
20780 return Res; // Correct type already, nothing to do.
20782 // All of the single-register GCC register classes map their values onto
20783 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20784 // really want an 8-bit or 32-bit register, map to the appropriate register
20785 // class and return the appropriate register.
20786 if (Res.second == &X86::GR16RegClass) {
20787 if (VT == MVT::i8 || VT == MVT::i1) {
20788 unsigned DestReg = 0;
20789 switch (Res.first) {
20791 case X86::AX: DestReg = X86::AL; break;
20792 case X86::DX: DestReg = X86::DL; break;
20793 case X86::CX: DestReg = X86::CL; break;
20794 case X86::BX: DestReg = X86::BL; break;
20797 Res.first = DestReg;
20798 Res.second = &X86::GR8RegClass;
20800 } else if (VT == MVT::i32 || VT == MVT::f32) {
20801 unsigned DestReg = 0;
20802 switch (Res.first) {
20804 case X86::AX: DestReg = X86::EAX; break;
20805 case X86::DX: DestReg = X86::EDX; break;
20806 case X86::CX: DestReg = X86::ECX; break;
20807 case X86::BX: DestReg = X86::EBX; break;
20808 case X86::SI: DestReg = X86::ESI; break;
20809 case X86::DI: DestReg = X86::EDI; break;
20810 case X86::BP: DestReg = X86::EBP; break;
20811 case X86::SP: DestReg = X86::ESP; break;
20814 Res.first = DestReg;
20815 Res.second = &X86::GR32RegClass;
20817 } else if (VT == MVT::i64 || VT == MVT::f64) {
20818 unsigned DestReg = 0;
20819 switch (Res.first) {
20821 case X86::AX: DestReg = X86::RAX; break;
20822 case X86::DX: DestReg = X86::RDX; break;
20823 case X86::CX: DestReg = X86::RCX; break;
20824 case X86::BX: DestReg = X86::RBX; break;
20825 case X86::SI: DestReg = X86::RSI; break;
20826 case X86::DI: DestReg = X86::RDI; break;
20827 case X86::BP: DestReg = X86::RBP; break;
20828 case X86::SP: DestReg = X86::RSP; break;
20831 Res.first = DestReg;
20832 Res.second = &X86::GR64RegClass;
20835 } else if (Res.second == &X86::FR32RegClass ||
20836 Res.second == &X86::FR64RegClass ||
20837 Res.second == &X86::VR128RegClass ||
20838 Res.second == &X86::VR256RegClass ||
20839 Res.second == &X86::FR32XRegClass ||
20840 Res.second == &X86::FR64XRegClass ||
20841 Res.second == &X86::VR128XRegClass ||
20842 Res.second == &X86::VR256XRegClass ||
20843 Res.second == &X86::VR512RegClass) {
20844 // Handle references to XMM physical registers that got mapped into the
20845 // wrong class. This can happen with constraints like {xmm0} where the
20846 // target independent register mapper will just pick the first match it can
20847 // find, ignoring the required type.
20849 if (VT == MVT::f32 || VT == MVT::i32)
20850 Res.second = &X86::FR32RegClass;
20851 else if (VT == MVT::f64 || VT == MVT::i64)
20852 Res.second = &X86::FR64RegClass;
20853 else if (X86::VR128RegClass.hasType(VT))
20854 Res.second = &X86::VR128RegClass;
20855 else if (X86::VR256RegClass.hasType(VT))
20856 Res.second = &X86::VR256RegClass;
20857 else if (X86::VR512RegClass.hasType(VT))
20858 Res.second = &X86::VR512RegClass;
20864 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20866 // Scaling factors are not free at all.
20867 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20868 // will take 2 allocations in the out of order engine instead of 1
20869 // for plain addressing mode, i.e. inst (reg1).
20871 // vaddps (%rsi,%drx), %ymm0, %ymm1
20872 // Requires two allocations (one for the load, one for the computation)
20874 // vaddps (%rsi), %ymm0, %ymm1
20875 // Requires just 1 allocation, i.e., freeing allocations for other operations
20876 // and having less micro operations to execute.
20878 // For some X86 architectures, this is even worse because for instance for
20879 // stores, the complex addressing mode forces the instruction to use the
20880 // "load" ports instead of the dedicated "store" port.
20881 // E.g., on Haswell:
20882 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
20883 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
20884 if (isLegalAddressingMode(AM, Ty))
20885 // Scale represents reg2 * scale, thus account for 1
20886 // as soon as we use a second register.
20887 return AM.Scale != 0;