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));
7471 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7472 SelectionDAG &DAG) {
7473 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7474 MVT VT = Op.getSimpleValueType();
7476 SDValue V1 = Op.getOperand(0);
7477 SDValue V2 = Op.getOperand(1);
7479 if (isZeroShuffle(SVOp))
7480 return getZeroVector(VT, Subtarget, DAG, dl);
7482 // Handle splat operations
7483 if (SVOp->isSplat()) {
7484 // Use vbroadcast whenever the splat comes from a foldable load
7485 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7486 if (Broadcast.getNode())
7490 // Check integer expanding shuffles.
7491 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7492 if (NewOp.getNode())
7495 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7497 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7499 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7500 if (NewOp.getNode())
7501 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7502 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7503 // FIXME: Figure out a cleaner way to do this.
7504 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7505 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7506 if (NewOp.getNode()) {
7507 MVT NewVT = NewOp.getSimpleValueType();
7508 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7509 NewVT, true, false))
7510 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7513 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7514 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7515 if (NewOp.getNode()) {
7516 MVT NewVT = NewOp.getSimpleValueType();
7517 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7518 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7522 } else if ((VT == MVT::v2i64 || VT == MVT::v2f64) && Subtarget->hasSSE2()) {
7523 // Emit movq and vmovq to copy an i64 or f64 to a vector and zero the
7525 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7526 MVT NewVT = SVOp->getSimpleValueType(0);
7527 if (isCommutedMOVLMask(SVOp->getMask(), NewVT, true, false))
7528 return getVZextMovL(VT, NewVT, SVOp->getOperand(0), DAG, Subtarget, dl);
7529 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7530 MVT NewVT = SVOp->getSimpleValueType(0);
7531 if (isMOVLMask(SVOp->getMask(), NewVT))
7532 return getVZextMovL(VT, NewVT, SVOp->getOperand(1), DAG, Subtarget, dl);
7539 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7540 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7541 SDValue V1 = Op.getOperand(0);
7542 SDValue V2 = Op.getOperand(1);
7543 MVT VT = Op.getSimpleValueType();
7545 unsigned NumElems = VT.getVectorNumElements();
7546 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7547 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7548 bool V1IsSplat = false;
7549 bool V2IsSplat = false;
7550 bool HasSSE2 = Subtarget->hasSSE2();
7551 bool HasFp256 = Subtarget->hasFp256();
7552 bool HasInt256 = Subtarget->hasInt256();
7553 MachineFunction &MF = DAG.getMachineFunction();
7554 bool OptForSize = MF.getFunction()->getAttributes().
7555 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7557 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7559 if (V1IsUndef && V2IsUndef)
7560 return DAG.getUNDEF(VT);
7562 // When we create a shuffle node we put the UNDEF node to second operand,
7563 // but in some cases the first operand may be transformed to UNDEF.
7564 // In this case we should just commute the node.
7566 return CommuteVectorShuffle(SVOp, DAG);
7568 // Vector shuffle lowering takes 3 steps:
7570 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7571 // narrowing and commutation of operands should be handled.
7572 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7574 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7575 // so the shuffle can be broken into other shuffles and the legalizer can
7576 // try the lowering again.
7578 // The general idea is that no vector_shuffle operation should be left to
7579 // be matched during isel, all of them must be converted to a target specific
7582 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7583 // narrowing and commutation of operands should be handled. The actual code
7584 // doesn't include all of those, work in progress...
7585 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7586 if (NewOp.getNode())
7589 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7591 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7592 // unpckh_undef). Only use pshufd if speed is more important than size.
7593 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7594 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7595 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7596 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7598 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7599 V2IsUndef && MayFoldVectorLoad(V1))
7600 return getMOVDDup(Op, dl, V1, DAG);
7602 if (isMOVHLPS_v_undef_Mask(M, VT))
7603 return getMOVHighToLow(Op, dl, DAG);
7605 // Use to match splats
7606 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7607 (VT == MVT::v2f64 || VT == MVT::v2i64))
7608 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7610 if (isPSHUFDMask(M, VT)) {
7611 // The actual implementation will match the mask in the if above and then
7612 // during isel it can match several different instructions, not only pshufd
7613 // as its name says, sad but true, emulate the behavior for now...
7614 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7615 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7617 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7619 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7620 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7622 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7623 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7626 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7630 if (isPALIGNRMask(M, VT, Subtarget))
7631 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7632 getShufflePALIGNRImmediate(SVOp),
7635 // Check if this can be converted into a logical shift.
7636 bool isLeft = false;
7639 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7640 if (isShift && ShVal.hasOneUse()) {
7641 // If the shifted value has multiple uses, it may be cheaper to use
7642 // v_set0 + movlhps or movhlps, etc.
7643 MVT EltVT = VT.getVectorElementType();
7644 ShAmt *= EltVT.getSizeInBits();
7645 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7648 if (isMOVLMask(M, VT)) {
7649 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7650 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7651 if (!isMOVLPMask(M, VT)) {
7652 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7653 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7655 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7656 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7660 // FIXME: fold these into legal mask.
7661 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7662 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7664 if (isMOVHLPSMask(M, VT))
7665 return getMOVHighToLow(Op, dl, DAG);
7667 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7668 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7670 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7671 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7673 if (isMOVLPMask(M, VT))
7674 return getMOVLP(Op, dl, DAG, HasSSE2);
7676 if (ShouldXformToMOVHLPS(M, VT) ||
7677 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7678 return CommuteVectorShuffle(SVOp, DAG);
7681 // No better options. Use a vshldq / vsrldq.
7682 MVT EltVT = VT.getVectorElementType();
7683 ShAmt *= EltVT.getSizeInBits();
7684 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7687 bool Commuted = false;
7688 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7689 // 1,1,1,1 -> v8i16 though.
7690 V1IsSplat = isSplatVector(V1.getNode());
7691 V2IsSplat = isSplatVector(V2.getNode());
7693 // Canonicalize the splat or undef, if present, to be on the RHS.
7694 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7695 CommuteVectorShuffleMask(M, NumElems);
7697 std::swap(V1IsSplat, V2IsSplat);
7701 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7702 // Shuffling low element of v1 into undef, just return v1.
7705 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7706 // the instruction selector will not match, so get a canonical MOVL with
7707 // swapped operands to undo the commute.
7708 return getMOVL(DAG, dl, VT, V2, V1);
7711 if (isUNPCKLMask(M, VT, HasInt256))
7712 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7714 if (isUNPCKHMask(M, VT, HasInt256))
7715 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7718 // Normalize mask so all entries that point to V2 points to its first
7719 // element then try to match unpck{h|l} again. If match, return a
7720 // new vector_shuffle with the corrected mask.p
7721 SmallVector<int, 8> NewMask(M.begin(), M.end());
7722 NormalizeMask(NewMask, NumElems);
7723 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7724 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7725 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7726 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7730 // Commute is back and try unpck* again.
7731 // FIXME: this seems wrong.
7732 CommuteVectorShuffleMask(M, NumElems);
7734 std::swap(V1IsSplat, V2IsSplat);
7736 if (isUNPCKLMask(M, VT, HasInt256))
7737 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7739 if (isUNPCKHMask(M, VT, HasInt256))
7740 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7743 // Normalize the node to match x86 shuffle ops if needed
7744 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7745 return CommuteVectorShuffle(SVOp, DAG);
7747 // The checks below are all present in isShuffleMaskLegal, but they are
7748 // inlined here right now to enable us to directly emit target specific
7749 // nodes, and remove one by one until they don't return Op anymore.
7751 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7752 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7753 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7754 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7757 if (isPSHUFHWMask(M, VT, HasInt256))
7758 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7759 getShufflePSHUFHWImmediate(SVOp),
7762 if (isPSHUFLWMask(M, VT, HasInt256))
7763 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7764 getShufflePSHUFLWImmediate(SVOp),
7767 if (isSHUFPMask(M, VT))
7768 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7769 getShuffleSHUFImmediate(SVOp), DAG);
7771 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7772 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7773 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7774 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7776 //===--------------------------------------------------------------------===//
7777 // Generate target specific nodes for 128 or 256-bit shuffles only
7778 // supported in the AVX instruction set.
7781 // Handle VMOVDDUPY permutations
7782 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7783 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7785 // Handle VPERMILPS/D* permutations
7786 if (isVPERMILPMask(M, VT)) {
7787 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7788 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7789 getShuffleSHUFImmediate(SVOp), DAG);
7790 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7791 getShuffleSHUFImmediate(SVOp), DAG);
7795 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7796 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7797 Idx*(NumElems/2), DAG, dl);
7799 // Handle VPERM2F128/VPERM2I128 permutations
7800 if (isVPERM2X128Mask(M, VT, HasFp256))
7801 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7802 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7804 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7805 if (BlendOp.getNode())
7808 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7809 return getINSERTPS(SVOp, dl, DAG);
7812 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7813 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7815 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7816 VT.is512BitVector()) {
7817 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7818 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7819 SmallVector<SDValue, 16> permclMask;
7820 for (unsigned i = 0; i != NumElems; ++i) {
7821 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7824 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7826 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7827 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7828 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7829 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7830 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7833 //===--------------------------------------------------------------------===//
7834 // Since no target specific shuffle was selected for this generic one,
7835 // lower it into other known shuffles. FIXME: this isn't true yet, but
7836 // this is the plan.
7839 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7840 if (VT == MVT::v8i16) {
7841 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7842 if (NewOp.getNode())
7846 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7847 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7848 if (NewOp.getNode())
7852 if (VT == MVT::v16i8) {
7853 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7854 if (NewOp.getNode())
7858 if (VT == MVT::v32i8) {
7859 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7860 if (NewOp.getNode())
7864 // Handle all 128-bit wide vectors with 4 elements, and match them with
7865 // several different shuffle types.
7866 if (NumElems == 4 && VT.is128BitVector())
7867 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7869 // Handle general 256-bit shuffles
7870 if (VT.is256BitVector())
7871 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7876 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7877 MVT VT = Op.getSimpleValueType();
7880 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7883 if (VT.getSizeInBits() == 8) {
7884 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7885 Op.getOperand(0), Op.getOperand(1));
7886 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7887 DAG.getValueType(VT));
7888 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7891 if (VT.getSizeInBits() == 16) {
7892 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7893 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7895 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7896 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7897 DAG.getNode(ISD::BITCAST, dl,
7901 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7902 Op.getOperand(0), Op.getOperand(1));
7903 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7904 DAG.getValueType(VT));
7905 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7908 if (VT == MVT::f32) {
7909 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7910 // the result back to FR32 register. It's only worth matching if the
7911 // result has a single use which is a store or a bitcast to i32. And in
7912 // the case of a store, it's not worth it if the index is a constant 0,
7913 // because a MOVSSmr can be used instead, which is smaller and faster.
7914 if (!Op.hasOneUse())
7916 SDNode *User = *Op.getNode()->use_begin();
7917 if ((User->getOpcode() != ISD::STORE ||
7918 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7919 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7920 (User->getOpcode() != ISD::BITCAST ||
7921 User->getValueType(0) != MVT::i32))
7923 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7924 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7927 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7930 if (VT == MVT::i32 || VT == MVT::i64) {
7931 // ExtractPS/pextrq works with constant index.
7932 if (isa<ConstantSDNode>(Op.getOperand(1)))
7938 /// Extract one bit from mask vector, like v16i1 or v8i1.
7939 /// AVX-512 feature.
7941 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7942 SDValue Vec = Op.getOperand(0);
7944 MVT VecVT = Vec.getSimpleValueType();
7945 SDValue Idx = Op.getOperand(1);
7946 MVT EltVT = Op.getSimpleValueType();
7948 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7950 // variable index can't be handled in mask registers,
7951 // extend vector to VR512
7952 if (!isa<ConstantSDNode>(Idx)) {
7953 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7954 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7955 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7956 ExtVT.getVectorElementType(), Ext, Idx);
7957 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7960 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7961 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7962 unsigned MaxSift = rc->getSize()*8 - 1;
7963 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7964 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7965 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7966 DAG.getConstant(MaxSift, MVT::i8));
7967 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7968 DAG.getIntPtrConstant(0));
7972 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7973 SelectionDAG &DAG) const {
7975 SDValue Vec = Op.getOperand(0);
7976 MVT VecVT = Vec.getSimpleValueType();
7977 SDValue Idx = Op.getOperand(1);
7979 if (Op.getSimpleValueType() == MVT::i1)
7980 return ExtractBitFromMaskVector(Op, DAG);
7982 if (!isa<ConstantSDNode>(Idx)) {
7983 if (VecVT.is512BitVector() ||
7984 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7985 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7988 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7989 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7990 MaskEltVT.getSizeInBits());
7992 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7993 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7994 getZeroVector(MaskVT, Subtarget, DAG, dl),
7995 Idx, DAG.getConstant(0, getPointerTy()));
7996 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7997 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7998 Perm, DAG.getConstant(0, getPointerTy()));
8003 // If this is a 256-bit vector result, first extract the 128-bit vector and
8004 // then extract the element from the 128-bit vector.
8005 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8007 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8008 // Get the 128-bit vector.
8009 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8010 MVT EltVT = VecVT.getVectorElementType();
8012 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8014 //if (IdxVal >= NumElems/2)
8015 // IdxVal -= NumElems/2;
8016 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8017 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8018 DAG.getConstant(IdxVal, MVT::i32));
8021 assert(VecVT.is128BitVector() && "Unexpected vector length");
8023 if (Subtarget->hasSSE41()) {
8024 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8029 MVT VT = Op.getSimpleValueType();
8030 // TODO: handle v16i8.
8031 if (VT.getSizeInBits() == 16) {
8032 SDValue Vec = Op.getOperand(0);
8033 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8035 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8036 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8037 DAG.getNode(ISD::BITCAST, dl,
8040 // Transform it so it match pextrw which produces a 32-bit result.
8041 MVT EltVT = MVT::i32;
8042 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8043 Op.getOperand(0), Op.getOperand(1));
8044 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8045 DAG.getValueType(VT));
8046 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8049 if (VT.getSizeInBits() == 32) {
8050 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8054 // SHUFPS the element to the lowest double word, then movss.
8055 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8056 MVT VVT = Op.getOperand(0).getSimpleValueType();
8057 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8058 DAG.getUNDEF(VVT), Mask);
8059 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8060 DAG.getIntPtrConstant(0));
8063 if (VT.getSizeInBits() == 64) {
8064 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8065 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8066 // to match extract_elt for f64.
8067 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8071 // UNPCKHPD the element to the lowest double word, then movsd.
8072 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8073 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8074 int Mask[2] = { 1, -1 };
8075 MVT VVT = Op.getOperand(0).getSimpleValueType();
8076 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8077 DAG.getUNDEF(VVT), Mask);
8078 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8079 DAG.getIntPtrConstant(0));
8085 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8086 MVT VT = Op.getSimpleValueType();
8087 MVT EltVT = VT.getVectorElementType();
8090 SDValue N0 = Op.getOperand(0);
8091 SDValue N1 = Op.getOperand(1);
8092 SDValue N2 = Op.getOperand(2);
8094 if (!VT.is128BitVector())
8097 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8098 isa<ConstantSDNode>(N2)) {
8100 if (VT == MVT::v8i16)
8101 Opc = X86ISD::PINSRW;
8102 else if (VT == MVT::v16i8)
8103 Opc = X86ISD::PINSRB;
8105 Opc = X86ISD::PINSRB;
8107 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8109 if (N1.getValueType() != MVT::i32)
8110 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8111 if (N2.getValueType() != MVT::i32)
8112 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8113 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8116 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8117 // Bits [7:6] of the constant are the source select. This will always be
8118 // zero here. The DAG Combiner may combine an extract_elt index into these
8119 // bits. For example (insert (extract, 3), 2) could be matched by putting
8120 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8121 // Bits [5:4] of the constant are the destination select. This is the
8122 // value of the incoming immediate.
8123 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8124 // combine either bitwise AND or insert of float 0.0 to set these bits.
8125 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8126 // Create this as a scalar to vector..
8127 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8128 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8131 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8132 // PINSR* works with constant index.
8138 /// Insert one bit to mask vector, like v16i1 or v8i1.
8139 /// AVX-512 feature.
8141 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8143 SDValue Vec = Op.getOperand(0);
8144 SDValue Elt = Op.getOperand(1);
8145 SDValue Idx = Op.getOperand(2);
8146 MVT VecVT = Vec.getSimpleValueType();
8148 if (!isa<ConstantSDNode>(Idx)) {
8149 // Non constant index. Extend source and destination,
8150 // insert element and then truncate the result.
8151 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8152 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8153 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8154 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8155 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8156 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8159 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8160 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8161 if (Vec.getOpcode() == ISD::UNDEF)
8162 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8163 DAG.getConstant(IdxVal, MVT::i8));
8164 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8165 unsigned MaxSift = rc->getSize()*8 - 1;
8166 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8167 DAG.getConstant(MaxSift, MVT::i8));
8168 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8169 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8170 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8173 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8174 MVT VT = Op.getSimpleValueType();
8175 MVT EltVT = VT.getVectorElementType();
8177 if (EltVT == MVT::i1)
8178 return InsertBitToMaskVector(Op, DAG);
8181 SDValue N0 = Op.getOperand(0);
8182 SDValue N1 = Op.getOperand(1);
8183 SDValue N2 = Op.getOperand(2);
8185 // If this is a 256-bit vector result, first extract the 128-bit vector,
8186 // insert the element into the extracted half and then place it back.
8187 if (VT.is256BitVector() || VT.is512BitVector()) {
8188 if (!isa<ConstantSDNode>(N2))
8191 // Get the desired 128-bit vector half.
8192 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8193 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8195 // Insert the element into the desired half.
8196 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8197 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8199 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8200 DAG.getConstant(IdxIn128, MVT::i32));
8202 // Insert the changed part back to the 256-bit vector
8203 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8206 if (Subtarget->hasSSE41())
8207 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8209 if (EltVT == MVT::i8)
8212 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8213 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8214 // as its second argument.
8215 if (N1.getValueType() != MVT::i32)
8216 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8217 if (N2.getValueType() != MVT::i32)
8218 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8219 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8224 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8226 MVT OpVT = Op.getSimpleValueType();
8228 // If this is a 256-bit vector result, first insert into a 128-bit
8229 // vector and then insert into the 256-bit vector.
8230 if (!OpVT.is128BitVector()) {
8231 // Insert into a 128-bit vector.
8232 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8233 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8234 OpVT.getVectorNumElements() / SizeFactor);
8236 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8238 // Insert the 128-bit vector.
8239 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8242 if (OpVT == MVT::v1i64 &&
8243 Op.getOperand(0).getValueType() == MVT::i64)
8244 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8246 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8247 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8248 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8249 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8252 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8253 // a simple subregister reference or explicit instructions to grab
8254 // upper bits of a vector.
8255 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8256 SelectionDAG &DAG) {
8258 SDValue In = Op.getOperand(0);
8259 SDValue Idx = Op.getOperand(1);
8260 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8261 MVT ResVT = Op.getSimpleValueType();
8262 MVT InVT = In.getSimpleValueType();
8264 if (Subtarget->hasFp256()) {
8265 if (ResVT.is128BitVector() &&
8266 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8267 isa<ConstantSDNode>(Idx)) {
8268 return Extract128BitVector(In, IdxVal, DAG, dl);
8270 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8271 isa<ConstantSDNode>(Idx)) {
8272 return Extract256BitVector(In, IdxVal, DAG, dl);
8278 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8279 // simple superregister reference or explicit instructions to insert
8280 // the upper bits of a vector.
8281 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8282 SelectionDAG &DAG) {
8283 if (Subtarget->hasFp256()) {
8284 SDLoc dl(Op.getNode());
8285 SDValue Vec = Op.getNode()->getOperand(0);
8286 SDValue SubVec = Op.getNode()->getOperand(1);
8287 SDValue Idx = Op.getNode()->getOperand(2);
8289 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8290 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8291 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8292 isa<ConstantSDNode>(Idx)) {
8293 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8294 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8297 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8298 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8299 isa<ConstantSDNode>(Idx)) {
8300 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8301 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8307 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8308 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8309 // one of the above mentioned nodes. It has to be wrapped because otherwise
8310 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8311 // be used to form addressing mode. These wrapped nodes will be selected
8314 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8315 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8317 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8319 unsigned char OpFlag = 0;
8320 unsigned WrapperKind = X86ISD::Wrapper;
8321 CodeModel::Model M = getTargetMachine().getCodeModel();
8323 if (Subtarget->isPICStyleRIPRel() &&
8324 (M == CodeModel::Small || M == CodeModel::Kernel))
8325 WrapperKind = X86ISD::WrapperRIP;
8326 else if (Subtarget->isPICStyleGOT())
8327 OpFlag = X86II::MO_GOTOFF;
8328 else if (Subtarget->isPICStyleStubPIC())
8329 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8331 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8333 CP->getOffset(), OpFlag);
8335 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8336 // With PIC, the address is actually $g + Offset.
8338 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8339 DAG.getNode(X86ISD::GlobalBaseReg,
8340 SDLoc(), getPointerTy()),
8347 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8348 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8350 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8352 unsigned char OpFlag = 0;
8353 unsigned WrapperKind = X86ISD::Wrapper;
8354 CodeModel::Model M = getTargetMachine().getCodeModel();
8356 if (Subtarget->isPICStyleRIPRel() &&
8357 (M == CodeModel::Small || M == CodeModel::Kernel))
8358 WrapperKind = X86ISD::WrapperRIP;
8359 else if (Subtarget->isPICStyleGOT())
8360 OpFlag = X86II::MO_GOTOFF;
8361 else if (Subtarget->isPICStyleStubPIC())
8362 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8364 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8367 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8369 // With PIC, the address is actually $g + Offset.
8371 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8372 DAG.getNode(X86ISD::GlobalBaseReg,
8373 SDLoc(), getPointerTy()),
8380 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8381 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8383 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8385 unsigned char OpFlag = 0;
8386 unsigned WrapperKind = X86ISD::Wrapper;
8387 CodeModel::Model M = getTargetMachine().getCodeModel();
8389 if (Subtarget->isPICStyleRIPRel() &&
8390 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8391 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8392 OpFlag = X86II::MO_GOTPCREL;
8393 WrapperKind = X86ISD::WrapperRIP;
8394 } else if (Subtarget->isPICStyleGOT()) {
8395 OpFlag = X86II::MO_GOT;
8396 } else if (Subtarget->isPICStyleStubPIC()) {
8397 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8398 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8399 OpFlag = X86II::MO_DARWIN_NONLAZY;
8402 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8405 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8407 // With PIC, the address is actually $g + Offset.
8408 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8409 !Subtarget->is64Bit()) {
8410 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8411 DAG.getNode(X86ISD::GlobalBaseReg,
8412 SDLoc(), getPointerTy()),
8416 // For symbols that require a load from a stub to get the address, emit the
8418 if (isGlobalStubReference(OpFlag))
8419 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8420 MachinePointerInfo::getGOT(), false, false, false, 0);
8426 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8427 // Create the TargetBlockAddressAddress node.
8428 unsigned char OpFlags =
8429 Subtarget->ClassifyBlockAddressReference();
8430 CodeModel::Model M = getTargetMachine().getCodeModel();
8431 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8432 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8434 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8437 if (Subtarget->isPICStyleRIPRel() &&
8438 (M == CodeModel::Small || M == CodeModel::Kernel))
8439 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8441 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8443 // With PIC, the address is actually $g + Offset.
8444 if (isGlobalRelativeToPICBase(OpFlags)) {
8445 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8446 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8454 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8455 int64_t Offset, SelectionDAG &DAG) const {
8456 // Create the TargetGlobalAddress node, folding in the constant
8457 // offset if it is legal.
8458 unsigned char OpFlags =
8459 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8460 CodeModel::Model M = getTargetMachine().getCodeModel();
8462 if (OpFlags == X86II::MO_NO_FLAG &&
8463 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8464 // A direct static reference to a global.
8465 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8468 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8471 if (Subtarget->isPICStyleRIPRel() &&
8472 (M == CodeModel::Small || M == CodeModel::Kernel))
8473 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8475 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8477 // With PIC, the address is actually $g + Offset.
8478 if (isGlobalRelativeToPICBase(OpFlags)) {
8479 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8480 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8484 // For globals that require a load from a stub to get the address, emit the
8486 if (isGlobalStubReference(OpFlags))
8487 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8488 MachinePointerInfo::getGOT(), false, false, false, 0);
8490 // If there was a non-zero offset that we didn't fold, create an explicit
8493 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8494 DAG.getConstant(Offset, getPointerTy()));
8500 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8501 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8502 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8503 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8507 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8508 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8509 unsigned char OperandFlags, bool LocalDynamic = false) {
8510 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8511 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8513 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8514 GA->getValueType(0),
8518 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8522 SDValue Ops[] = { Chain, TGA, *InFlag };
8523 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8525 SDValue Ops[] = { Chain, TGA };
8526 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8529 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8530 MFI->setAdjustsStack(true);
8532 SDValue Flag = Chain.getValue(1);
8533 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8536 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8538 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8541 SDLoc dl(GA); // ? function entry point might be better
8542 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8543 DAG.getNode(X86ISD::GlobalBaseReg,
8544 SDLoc(), PtrVT), InFlag);
8545 InFlag = Chain.getValue(1);
8547 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8550 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8552 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8554 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8555 X86::RAX, X86II::MO_TLSGD);
8558 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8564 // Get the start address of the TLS block for this module.
8565 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8566 .getInfo<X86MachineFunctionInfo>();
8567 MFI->incNumLocalDynamicTLSAccesses();
8571 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8572 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8575 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8576 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8577 InFlag = Chain.getValue(1);
8578 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8579 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8582 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8586 unsigned char OperandFlags = X86II::MO_DTPOFF;
8587 unsigned WrapperKind = X86ISD::Wrapper;
8588 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8589 GA->getValueType(0),
8590 GA->getOffset(), OperandFlags);
8591 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8593 // Add x@dtpoff with the base.
8594 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8597 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8598 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8599 const EVT PtrVT, TLSModel::Model model,
8600 bool is64Bit, bool isPIC) {
8603 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8604 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8605 is64Bit ? 257 : 256));
8607 SDValue ThreadPointer =
8608 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8609 MachinePointerInfo(Ptr), false, false, false, 0);
8611 unsigned char OperandFlags = 0;
8612 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8614 unsigned WrapperKind = X86ISD::Wrapper;
8615 if (model == TLSModel::LocalExec) {
8616 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8617 } else if (model == TLSModel::InitialExec) {
8619 OperandFlags = X86II::MO_GOTTPOFF;
8620 WrapperKind = X86ISD::WrapperRIP;
8622 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8625 llvm_unreachable("Unexpected model");
8628 // emit "addl x@ntpoff,%eax" (local exec)
8629 // or "addl x@indntpoff,%eax" (initial exec)
8630 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8632 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8633 GA->getOffset(), OperandFlags);
8634 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8636 if (model == TLSModel::InitialExec) {
8637 if (isPIC && !is64Bit) {
8638 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8639 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8643 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8644 MachinePointerInfo::getGOT(), false, false, false, 0);
8647 // The address of the thread local variable is the add of the thread
8648 // pointer with the offset of the variable.
8649 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8653 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8655 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8656 const GlobalValue *GV = GA->getGlobal();
8658 if (Subtarget->isTargetELF()) {
8659 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8662 case TLSModel::GeneralDynamic:
8663 if (Subtarget->is64Bit())
8664 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8665 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8666 case TLSModel::LocalDynamic:
8667 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8668 Subtarget->is64Bit());
8669 case TLSModel::InitialExec:
8670 case TLSModel::LocalExec:
8671 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8672 Subtarget->is64Bit(),
8673 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8675 llvm_unreachable("Unknown TLS model.");
8678 if (Subtarget->isTargetDarwin()) {
8679 // Darwin only has one model of TLS. Lower to that.
8680 unsigned char OpFlag = 0;
8681 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8682 X86ISD::WrapperRIP : X86ISD::Wrapper;
8684 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8686 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8687 !Subtarget->is64Bit();
8689 OpFlag = X86II::MO_TLVP_PIC_BASE;
8691 OpFlag = X86II::MO_TLVP;
8693 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8694 GA->getValueType(0),
8695 GA->getOffset(), OpFlag);
8696 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8698 // With PIC32, the address is actually $g + Offset.
8700 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8701 DAG.getNode(X86ISD::GlobalBaseReg,
8702 SDLoc(), getPointerTy()),
8705 // Lowering the machine isd will make sure everything is in the right
8707 SDValue Chain = DAG.getEntryNode();
8708 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8709 SDValue Args[] = { Chain, Offset };
8710 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8712 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8713 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8714 MFI->setAdjustsStack(true);
8716 // And our return value (tls address) is in the standard call return value
8718 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8719 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8723 if (Subtarget->isTargetKnownWindowsMSVC() ||
8724 Subtarget->isTargetWindowsGNU()) {
8725 // Just use the implicit TLS architecture
8726 // Need to generate someting similar to:
8727 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8729 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8730 // mov rcx, qword [rdx+rcx*8]
8731 // mov eax, .tls$:tlsvar
8732 // [rax+rcx] contains the address
8733 // Windows 64bit: gs:0x58
8734 // Windows 32bit: fs:__tls_array
8736 // If GV is an alias then use the aliasee for determining
8737 // thread-localness.
8738 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8739 GV = GA->getAliasedGlobal();
8741 SDValue Chain = DAG.getEntryNode();
8743 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8744 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8745 // use its literal value of 0x2C.
8746 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8747 ? Type::getInt8PtrTy(*DAG.getContext(),
8749 : Type::getInt32PtrTy(*DAG.getContext(),
8753 Subtarget->is64Bit()
8754 ? DAG.getIntPtrConstant(0x58)
8755 : (Subtarget->isTargetWindowsGNU()
8756 ? DAG.getIntPtrConstant(0x2C)
8757 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8759 SDValue ThreadPointer =
8760 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8761 MachinePointerInfo(Ptr), false, false, false, 0);
8763 // Load the _tls_index variable
8764 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8765 if (Subtarget->is64Bit())
8766 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8767 IDX, MachinePointerInfo(), MVT::i32,
8770 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8771 false, false, false, 0);
8773 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8775 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8777 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8778 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8779 false, false, false, 0);
8781 // Get the offset of start of .tls section
8782 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8783 GA->getValueType(0),
8784 GA->getOffset(), X86II::MO_SECREL);
8785 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8787 // The address of the thread local variable is the add of the thread
8788 // pointer with the offset of the variable.
8789 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8792 llvm_unreachable("TLS not implemented for this target.");
8795 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8796 /// and take a 2 x i32 value to shift plus a shift amount.
8797 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8798 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8799 MVT VT = Op.getSimpleValueType();
8800 unsigned VTBits = VT.getSizeInBits();
8802 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8803 SDValue ShOpLo = Op.getOperand(0);
8804 SDValue ShOpHi = Op.getOperand(1);
8805 SDValue ShAmt = Op.getOperand(2);
8806 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8807 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8809 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8810 DAG.getConstant(VTBits - 1, MVT::i8));
8811 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8812 DAG.getConstant(VTBits - 1, MVT::i8))
8813 : DAG.getConstant(0, VT);
8816 if (Op.getOpcode() == ISD::SHL_PARTS) {
8817 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8818 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8820 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8821 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8824 // If the shift amount is larger or equal than the width of a part we can't
8825 // rely on the results of shld/shrd. Insert a test and select the appropriate
8826 // values for large shift amounts.
8827 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8828 DAG.getConstant(VTBits, MVT::i8));
8829 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8830 AndNode, DAG.getConstant(0, MVT::i8));
8833 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8834 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8835 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8837 if (Op.getOpcode() == ISD::SHL_PARTS) {
8838 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8839 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8841 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8842 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8845 SDValue Ops[2] = { Lo, Hi };
8846 return DAG.getMergeValues(Ops, dl);
8849 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8850 SelectionDAG &DAG) const {
8851 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8853 if (SrcVT.isVector())
8856 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8857 "Unknown SINT_TO_FP to lower!");
8859 // These are really Legal; return the operand so the caller accepts it as
8861 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8863 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8864 Subtarget->is64Bit()) {
8869 unsigned Size = SrcVT.getSizeInBits()/8;
8870 MachineFunction &MF = DAG.getMachineFunction();
8871 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8872 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8873 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8875 MachinePointerInfo::getFixedStack(SSFI),
8877 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8880 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8882 SelectionDAG &DAG) const {
8886 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8888 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8890 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8892 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8894 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8895 MachineMemOperand *MMO;
8897 int SSFI = FI->getIndex();
8899 DAG.getMachineFunction()
8900 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8901 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8903 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8904 StackSlot = StackSlot.getOperand(1);
8906 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8907 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8909 Tys, Ops, SrcVT, MMO);
8912 Chain = Result.getValue(1);
8913 SDValue InFlag = Result.getValue(2);
8915 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8916 // shouldn't be necessary except that RFP cannot be live across
8917 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8918 MachineFunction &MF = DAG.getMachineFunction();
8919 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8920 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8921 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8922 Tys = DAG.getVTList(MVT::Other);
8924 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8926 MachineMemOperand *MMO =
8927 DAG.getMachineFunction()
8928 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8929 MachineMemOperand::MOStore, SSFISize, SSFISize);
8931 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8932 Ops, Op.getValueType(), MMO);
8933 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8934 MachinePointerInfo::getFixedStack(SSFI),
8935 false, false, false, 0);
8941 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8942 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8943 SelectionDAG &DAG) const {
8944 // This algorithm is not obvious. Here it is what we're trying to output:
8947 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8948 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8952 pshufd $0x4e, %xmm0, %xmm1
8958 LLVMContext *Context = DAG.getContext();
8960 // Build some magic constants.
8961 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8962 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8963 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8965 SmallVector<Constant*,2> CV1;
8967 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8968 APInt(64, 0x4330000000000000ULL))));
8970 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8971 APInt(64, 0x4530000000000000ULL))));
8972 Constant *C1 = ConstantVector::get(CV1);
8973 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8975 // Load the 64-bit value into an XMM register.
8976 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8978 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8979 MachinePointerInfo::getConstantPool(),
8980 false, false, false, 16);
8981 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8982 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8985 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8986 MachinePointerInfo::getConstantPool(),
8987 false, false, false, 16);
8988 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8989 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8992 if (Subtarget->hasSSE3()) {
8993 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8994 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8996 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8997 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8999 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9000 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9004 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9005 DAG.getIntPtrConstant(0));
9008 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9009 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9010 SelectionDAG &DAG) const {
9012 // FP constant to bias correct the final result.
9013 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9016 // Load the 32-bit value into an XMM register.
9017 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9020 // Zero out the upper parts of the register.
9021 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9023 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9024 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9025 DAG.getIntPtrConstant(0));
9027 // Or the load with the bias.
9028 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9029 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9030 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9032 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9033 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9034 MVT::v2f64, Bias)));
9035 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9036 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9037 DAG.getIntPtrConstant(0));
9039 // Subtract the bias.
9040 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9042 // Handle final rounding.
9043 EVT DestVT = Op.getValueType();
9045 if (DestVT.bitsLT(MVT::f64))
9046 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9047 DAG.getIntPtrConstant(0));
9048 if (DestVT.bitsGT(MVT::f64))
9049 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9051 // Handle final rounding.
9055 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9056 SelectionDAG &DAG) const {
9057 SDValue N0 = Op.getOperand(0);
9058 MVT SVT = N0.getSimpleValueType();
9061 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9062 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9063 "Custom UINT_TO_FP is not supported!");
9065 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9066 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9067 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9070 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9071 SelectionDAG &DAG) const {
9072 SDValue N0 = Op.getOperand(0);
9075 if (Op.getValueType().isVector())
9076 return lowerUINT_TO_FP_vec(Op, DAG);
9078 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9079 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9080 // the optimization here.
9081 if (DAG.SignBitIsZero(N0))
9082 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9084 MVT SrcVT = N0.getSimpleValueType();
9085 MVT DstVT = Op.getSimpleValueType();
9086 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9087 return LowerUINT_TO_FP_i64(Op, DAG);
9088 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9089 return LowerUINT_TO_FP_i32(Op, DAG);
9090 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9093 // Make a 64-bit buffer, and use it to build an FILD.
9094 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9095 if (SrcVT == MVT::i32) {
9096 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9097 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9098 getPointerTy(), StackSlot, WordOff);
9099 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9100 StackSlot, MachinePointerInfo(),
9102 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9103 OffsetSlot, MachinePointerInfo(),
9105 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9109 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9110 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9111 StackSlot, MachinePointerInfo(),
9113 // For i64 source, we need to add the appropriate power of 2 if the input
9114 // was negative. This is the same as the optimization in
9115 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9116 // we must be careful to do the computation in x87 extended precision, not
9117 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9118 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9119 MachineMemOperand *MMO =
9120 DAG.getMachineFunction()
9121 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9122 MachineMemOperand::MOLoad, 8, 8);
9124 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9125 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9126 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9129 APInt FF(32, 0x5F800000ULL);
9131 // Check whether the sign bit is set.
9132 SDValue SignSet = DAG.getSetCC(dl,
9133 getSetCCResultType(*DAG.getContext(), MVT::i64),
9134 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9137 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9138 SDValue FudgePtr = DAG.getConstantPool(
9139 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9142 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9143 SDValue Zero = DAG.getIntPtrConstant(0);
9144 SDValue Four = DAG.getIntPtrConstant(4);
9145 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9147 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9149 // Load the value out, extending it from f32 to f80.
9150 // FIXME: Avoid the extend by constructing the right constant pool?
9151 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9152 FudgePtr, MachinePointerInfo::getConstantPool(),
9153 MVT::f32, false, false, 4);
9154 // Extend everything to 80 bits to force it to be done on x87.
9155 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9156 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9159 std::pair<SDValue,SDValue>
9160 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9161 bool IsSigned, bool IsReplace) const {
9164 EVT DstTy = Op.getValueType();
9166 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9167 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9171 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9172 DstTy.getSimpleVT() >= MVT::i16 &&
9173 "Unknown FP_TO_INT to lower!");
9175 // These are really Legal.
9176 if (DstTy == MVT::i32 &&
9177 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9178 return std::make_pair(SDValue(), SDValue());
9179 if (Subtarget->is64Bit() &&
9180 DstTy == MVT::i64 &&
9181 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9182 return std::make_pair(SDValue(), SDValue());
9184 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9185 // stack slot, or into the FTOL runtime function.
9186 MachineFunction &MF = DAG.getMachineFunction();
9187 unsigned MemSize = DstTy.getSizeInBits()/8;
9188 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9189 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9192 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9193 Opc = X86ISD::WIN_FTOL;
9195 switch (DstTy.getSimpleVT().SimpleTy) {
9196 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9197 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9198 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9199 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9202 SDValue Chain = DAG.getEntryNode();
9203 SDValue Value = Op.getOperand(0);
9204 EVT TheVT = Op.getOperand(0).getValueType();
9205 // FIXME This causes a redundant load/store if the SSE-class value is already
9206 // in memory, such as if it is on the callstack.
9207 if (isScalarFPTypeInSSEReg(TheVT)) {
9208 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9209 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9210 MachinePointerInfo::getFixedStack(SSFI),
9212 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9214 Chain, StackSlot, DAG.getValueType(TheVT)
9217 MachineMemOperand *MMO =
9218 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9219 MachineMemOperand::MOLoad, MemSize, MemSize);
9220 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9221 Chain = Value.getValue(1);
9222 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9223 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9226 MachineMemOperand *MMO =
9227 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9228 MachineMemOperand::MOStore, MemSize, MemSize);
9230 if (Opc != X86ISD::WIN_FTOL) {
9231 // Build the FP_TO_INT*_IN_MEM
9232 SDValue Ops[] = { Chain, Value, StackSlot };
9233 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9235 return std::make_pair(FIST, StackSlot);
9237 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9238 DAG.getVTList(MVT::Other, MVT::Glue),
9240 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9241 MVT::i32, ftol.getValue(1));
9242 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9243 MVT::i32, eax.getValue(2));
9244 SDValue Ops[] = { eax, edx };
9245 SDValue pair = IsReplace
9246 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9247 : DAG.getMergeValues(Ops, DL);
9248 return std::make_pair(pair, SDValue());
9252 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9253 const X86Subtarget *Subtarget) {
9254 MVT VT = Op->getSimpleValueType(0);
9255 SDValue In = Op->getOperand(0);
9256 MVT InVT = In.getSimpleValueType();
9259 // Optimize vectors in AVX mode:
9262 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9263 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9264 // Concat upper and lower parts.
9267 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9268 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9269 // Concat upper and lower parts.
9272 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9273 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9274 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9277 if (Subtarget->hasInt256())
9278 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9280 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9281 SDValue Undef = DAG.getUNDEF(InVT);
9282 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9283 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9284 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9286 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9287 VT.getVectorNumElements()/2);
9289 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9290 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9292 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9295 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9296 SelectionDAG &DAG) {
9297 MVT VT = Op->getSimpleValueType(0);
9298 SDValue In = Op->getOperand(0);
9299 MVT InVT = In.getSimpleValueType();
9301 unsigned int NumElts = VT.getVectorNumElements();
9302 if (NumElts != 8 && NumElts != 16)
9305 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9306 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9308 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9309 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9310 // Now we have only mask extension
9311 assert(InVT.getVectorElementType() == MVT::i1);
9312 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9313 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9314 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9315 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9316 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9317 MachinePointerInfo::getConstantPool(),
9318 false, false, false, Alignment);
9320 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9321 if (VT.is512BitVector())
9323 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9326 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9327 SelectionDAG &DAG) {
9328 if (Subtarget->hasFp256()) {
9329 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9337 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9338 SelectionDAG &DAG) {
9340 MVT VT = Op.getSimpleValueType();
9341 SDValue In = Op.getOperand(0);
9342 MVT SVT = In.getSimpleValueType();
9344 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9345 return LowerZERO_EXTEND_AVX512(Op, DAG);
9347 if (Subtarget->hasFp256()) {
9348 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9353 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9354 VT.getVectorNumElements() != SVT.getVectorNumElements());
9358 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9360 MVT VT = Op.getSimpleValueType();
9361 SDValue In = Op.getOperand(0);
9362 MVT InVT = In.getSimpleValueType();
9364 if (VT == MVT::i1) {
9365 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9366 "Invalid scalar TRUNCATE operation");
9367 if (InVT == MVT::i32)
9369 if (InVT.getSizeInBits() == 64)
9370 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9371 else if (InVT.getSizeInBits() < 32)
9372 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9373 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9375 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9376 "Invalid TRUNCATE operation");
9378 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9379 if (VT.getVectorElementType().getSizeInBits() >=8)
9380 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9382 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9383 unsigned NumElts = InVT.getVectorNumElements();
9384 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9385 if (InVT.getSizeInBits() < 512) {
9386 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9387 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9391 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9392 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9393 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9394 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9395 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9396 MachinePointerInfo::getConstantPool(),
9397 false, false, false, Alignment);
9398 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9399 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9400 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9403 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9404 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9405 if (Subtarget->hasInt256()) {
9406 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9407 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9408 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9410 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9411 DAG.getIntPtrConstant(0));
9414 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9415 DAG.getIntPtrConstant(0));
9416 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9417 DAG.getIntPtrConstant(2));
9418 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9419 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9420 static const int ShufMask[] = {0, 2, 4, 6};
9421 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9424 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9425 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9426 if (Subtarget->hasInt256()) {
9427 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9429 SmallVector<SDValue,32> pshufbMask;
9430 for (unsigned i = 0; i < 2; ++i) {
9431 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9432 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9433 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9434 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9435 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9436 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9437 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9438 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9439 for (unsigned j = 0; j < 8; ++j)
9440 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9442 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9443 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9444 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9446 static const int ShufMask[] = {0, 2, -1, -1};
9447 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9449 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9450 DAG.getIntPtrConstant(0));
9451 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9454 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9455 DAG.getIntPtrConstant(0));
9457 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9458 DAG.getIntPtrConstant(4));
9460 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9461 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9464 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9465 -1, -1, -1, -1, -1, -1, -1, -1};
9467 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9468 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9469 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9471 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9472 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9474 // The MOVLHPS Mask:
9475 static const int ShufMask2[] = {0, 1, 4, 5};
9476 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9477 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9480 // Handle truncation of V256 to V128 using shuffles.
9481 if (!VT.is128BitVector() || !InVT.is256BitVector())
9484 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9486 unsigned NumElems = VT.getVectorNumElements();
9487 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9489 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9490 // Prepare truncation shuffle mask
9491 for (unsigned i = 0; i != NumElems; ++i)
9493 SDValue V = DAG.getVectorShuffle(NVT, DL,
9494 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9495 DAG.getUNDEF(NVT), &MaskVec[0]);
9496 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9497 DAG.getIntPtrConstant(0));
9500 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9501 SelectionDAG &DAG) const {
9502 assert(!Op.getSimpleValueType().isVector());
9504 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9505 /*IsSigned=*/ true, /*IsReplace=*/ false);
9506 SDValue FIST = Vals.first, StackSlot = Vals.second;
9507 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9508 if (!FIST.getNode()) return Op;
9510 if (StackSlot.getNode())
9512 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9513 FIST, StackSlot, MachinePointerInfo(),
9514 false, false, false, 0);
9516 // The node is the result.
9520 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9521 SelectionDAG &DAG) const {
9522 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9523 /*IsSigned=*/ false, /*IsReplace=*/ false);
9524 SDValue FIST = Vals.first, StackSlot = Vals.second;
9525 assert(FIST.getNode() && "Unexpected failure");
9527 if (StackSlot.getNode())
9529 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9530 FIST, StackSlot, MachinePointerInfo(),
9531 false, false, false, 0);
9533 // The node is the result.
9537 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9539 MVT VT = Op.getSimpleValueType();
9540 SDValue In = Op.getOperand(0);
9541 MVT SVT = In.getSimpleValueType();
9543 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9545 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9546 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9547 In, DAG.getUNDEF(SVT)));
9550 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9551 LLVMContext *Context = DAG.getContext();
9553 MVT VT = Op.getSimpleValueType();
9555 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9556 if (VT.isVector()) {
9557 EltVT = VT.getVectorElementType();
9558 NumElts = VT.getVectorNumElements();
9561 if (EltVT == MVT::f64)
9562 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9563 APInt(64, ~(1ULL << 63))));
9565 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9566 APInt(32, ~(1U << 31))));
9567 C = ConstantVector::getSplat(NumElts, C);
9568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9569 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9570 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9571 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9572 MachinePointerInfo::getConstantPool(),
9573 false, false, false, Alignment);
9574 if (VT.isVector()) {
9575 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9576 return DAG.getNode(ISD::BITCAST, dl, VT,
9577 DAG.getNode(ISD::AND, dl, ANDVT,
9578 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9580 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9582 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9585 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9586 LLVMContext *Context = DAG.getContext();
9588 MVT VT = Op.getSimpleValueType();
9590 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9591 if (VT.isVector()) {
9592 EltVT = VT.getVectorElementType();
9593 NumElts = VT.getVectorNumElements();
9596 if (EltVT == MVT::f64)
9597 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9598 APInt(64, 1ULL << 63)));
9600 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9601 APInt(32, 1U << 31)));
9602 C = ConstantVector::getSplat(NumElts, C);
9603 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9604 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9605 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9606 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9607 MachinePointerInfo::getConstantPool(),
9608 false, false, false, Alignment);
9609 if (VT.isVector()) {
9610 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9611 return DAG.getNode(ISD::BITCAST, dl, VT,
9612 DAG.getNode(ISD::XOR, dl, XORVT,
9613 DAG.getNode(ISD::BITCAST, dl, XORVT,
9615 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9618 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9621 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9622 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9623 LLVMContext *Context = DAG.getContext();
9624 SDValue Op0 = Op.getOperand(0);
9625 SDValue Op1 = Op.getOperand(1);
9627 MVT VT = Op.getSimpleValueType();
9628 MVT SrcVT = Op1.getSimpleValueType();
9630 // If second operand is smaller, extend it first.
9631 if (SrcVT.bitsLT(VT)) {
9632 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9635 // And if it is bigger, shrink it first.
9636 if (SrcVT.bitsGT(VT)) {
9637 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9641 // At this point the operands and the result should have the same
9642 // type, and that won't be f80 since that is not custom lowered.
9644 // First get the sign bit of second operand.
9645 SmallVector<Constant*,4> CV;
9646 if (SrcVT == MVT::f64) {
9647 const fltSemantics &Sem = APFloat::IEEEdouble;
9648 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9649 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9651 const fltSemantics &Sem = APFloat::IEEEsingle;
9652 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9653 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9654 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9655 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9657 Constant *C = ConstantVector::get(CV);
9658 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9659 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9660 MachinePointerInfo::getConstantPool(),
9661 false, false, false, 16);
9662 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9664 // Shift sign bit right or left if the two operands have different types.
9665 if (SrcVT.bitsGT(VT)) {
9666 // Op0 is MVT::f32, Op1 is MVT::f64.
9667 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9668 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9669 DAG.getConstant(32, MVT::i32));
9670 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9671 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9672 DAG.getIntPtrConstant(0));
9675 // Clear first operand sign bit.
9677 if (VT == MVT::f64) {
9678 const fltSemantics &Sem = APFloat::IEEEdouble;
9679 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9680 APInt(64, ~(1ULL << 63)))));
9681 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9683 const fltSemantics &Sem = APFloat::IEEEsingle;
9684 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9685 APInt(32, ~(1U << 31)))));
9686 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9687 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9688 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9690 C = ConstantVector::get(CV);
9691 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9692 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9693 MachinePointerInfo::getConstantPool(),
9694 false, false, false, 16);
9695 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9697 // Or the value with the sign bit.
9698 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9701 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9702 SDValue N0 = Op.getOperand(0);
9704 MVT VT = Op.getSimpleValueType();
9706 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9707 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9708 DAG.getConstant(1, VT));
9709 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9712 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9714 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9715 SelectionDAG &DAG) {
9716 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9718 if (!Subtarget->hasSSE41())
9721 if (!Op->hasOneUse())
9724 SDNode *N = Op.getNode();
9727 SmallVector<SDValue, 8> Opnds;
9728 DenseMap<SDValue, unsigned> VecInMap;
9729 SmallVector<SDValue, 8> VecIns;
9730 EVT VT = MVT::Other;
9732 // Recognize a special case where a vector is casted into wide integer to
9734 Opnds.push_back(N->getOperand(0));
9735 Opnds.push_back(N->getOperand(1));
9737 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9738 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9739 // BFS traverse all OR'd operands.
9740 if (I->getOpcode() == ISD::OR) {
9741 Opnds.push_back(I->getOperand(0));
9742 Opnds.push_back(I->getOperand(1));
9743 // Re-evaluate the number of nodes to be traversed.
9744 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9748 // Quit if a non-EXTRACT_VECTOR_ELT
9749 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9752 // Quit if without a constant index.
9753 SDValue Idx = I->getOperand(1);
9754 if (!isa<ConstantSDNode>(Idx))
9757 SDValue ExtractedFromVec = I->getOperand(0);
9758 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9759 if (M == VecInMap.end()) {
9760 VT = ExtractedFromVec.getValueType();
9761 // Quit if not 128/256-bit vector.
9762 if (!VT.is128BitVector() && !VT.is256BitVector())
9764 // Quit if not the same type.
9765 if (VecInMap.begin() != VecInMap.end() &&
9766 VT != VecInMap.begin()->first.getValueType())
9768 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9769 VecIns.push_back(ExtractedFromVec);
9771 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9774 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9775 "Not extracted from 128-/256-bit vector.");
9777 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9779 for (DenseMap<SDValue, unsigned>::const_iterator
9780 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9781 // Quit if not all elements are used.
9782 if (I->second != FullMask)
9786 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9788 // Cast all vectors into TestVT for PTEST.
9789 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9790 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9792 // If more than one full vectors are evaluated, OR them first before PTEST.
9793 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9794 // Each iteration will OR 2 nodes and append the result until there is only
9795 // 1 node left, i.e. the final OR'd value of all vectors.
9796 SDValue LHS = VecIns[Slot];
9797 SDValue RHS = VecIns[Slot + 1];
9798 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9801 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9802 VecIns.back(), VecIns.back());
9805 /// \brief return true if \c Op has a use that doesn't just read flags.
9806 static bool hasNonFlagsUse(SDValue Op) {
9807 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9810 unsigned UOpNo = UI.getOperandNo();
9811 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9812 // Look pass truncate.
9813 UOpNo = User->use_begin().getOperandNo();
9814 User = *User->use_begin();
9817 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9818 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9824 /// Emit nodes that will be selected as "test Op0,Op0", or something
9826 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9827 SelectionDAG &DAG) const {
9828 if (Op.getValueType() == MVT::i1)
9829 // KORTEST instruction should be selected
9830 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9831 DAG.getConstant(0, Op.getValueType()));
9833 // CF and OF aren't always set the way we want. Determine which
9834 // of these we need.
9835 bool NeedCF = false;
9836 bool NeedOF = false;
9839 case X86::COND_A: case X86::COND_AE:
9840 case X86::COND_B: case X86::COND_BE:
9843 case X86::COND_G: case X86::COND_GE:
9844 case X86::COND_L: case X86::COND_LE:
9845 case X86::COND_O: case X86::COND_NO:
9849 // See if we can use the EFLAGS value from the operand instead of
9850 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9851 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9852 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9853 // Emit a CMP with 0, which is the TEST pattern.
9854 //if (Op.getValueType() == MVT::i1)
9855 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9856 // DAG.getConstant(0, MVT::i1));
9857 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9858 DAG.getConstant(0, Op.getValueType()));
9860 unsigned Opcode = 0;
9861 unsigned NumOperands = 0;
9863 // Truncate operations may prevent the merge of the SETCC instruction
9864 // and the arithmetic instruction before it. Attempt to truncate the operands
9865 // of the arithmetic instruction and use a reduced bit-width instruction.
9866 bool NeedTruncation = false;
9867 SDValue ArithOp = Op;
9868 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9869 SDValue Arith = Op->getOperand(0);
9870 // Both the trunc and the arithmetic op need to have one user each.
9871 if (Arith->hasOneUse())
9872 switch (Arith.getOpcode()) {
9879 NeedTruncation = true;
9885 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9886 // which may be the result of a CAST. We use the variable 'Op', which is the
9887 // non-casted variable when we check for possible users.
9888 switch (ArithOp.getOpcode()) {
9890 // Due to an isel shortcoming, be conservative if this add is likely to be
9891 // selected as part of a load-modify-store instruction. When the root node
9892 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9893 // uses of other nodes in the match, such as the ADD in this case. This
9894 // leads to the ADD being left around and reselected, with the result being
9895 // two adds in the output. Alas, even if none our users are stores, that
9896 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9897 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9898 // climbing the DAG back to the root, and it doesn't seem to be worth the
9900 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9901 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9902 if (UI->getOpcode() != ISD::CopyToReg &&
9903 UI->getOpcode() != ISD::SETCC &&
9904 UI->getOpcode() != ISD::STORE)
9907 if (ConstantSDNode *C =
9908 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9909 // An add of one will be selected as an INC.
9910 if (C->getAPIntValue() == 1) {
9911 Opcode = X86ISD::INC;
9916 // An add of negative one (subtract of one) will be selected as a DEC.
9917 if (C->getAPIntValue().isAllOnesValue()) {
9918 Opcode = X86ISD::DEC;
9924 // Otherwise use a regular EFLAGS-setting add.
9925 Opcode = X86ISD::ADD;
9930 // If we have a constant logical shift that's only used in a comparison
9931 // against zero turn it into an equivalent AND. This allows turning it into
9932 // a TEST instruction later.
9933 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9934 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9935 EVT VT = Op.getValueType();
9936 unsigned BitWidth = VT.getSizeInBits();
9937 unsigned ShAmt = Op->getConstantOperandVal(1);
9938 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9940 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9941 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9942 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9943 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9945 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9946 DAG.getConstant(Mask, VT));
9947 DAG.ReplaceAllUsesWith(Op, New);
9953 // If the primary and result isn't used, don't bother using X86ISD::AND,
9954 // because a TEST instruction will be better.
9955 if (!hasNonFlagsUse(Op))
9961 // Due to the ISEL shortcoming noted above, be conservative if this op is
9962 // likely to be selected as part of a load-modify-store instruction.
9963 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9964 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9965 if (UI->getOpcode() == ISD::STORE)
9968 // Otherwise use a regular EFLAGS-setting instruction.
9969 switch (ArithOp.getOpcode()) {
9970 default: llvm_unreachable("unexpected operator!");
9971 case ISD::SUB: Opcode = X86ISD::SUB; break;
9972 case ISD::XOR: Opcode = X86ISD::XOR; break;
9973 case ISD::AND: Opcode = X86ISD::AND; break;
9975 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9976 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9977 if (EFLAGS.getNode())
9980 Opcode = X86ISD::OR;
9994 return SDValue(Op.getNode(), 1);
10000 // If we found that truncation is beneficial, perform the truncation and
10002 if (NeedTruncation) {
10003 EVT VT = Op.getValueType();
10004 SDValue WideVal = Op->getOperand(0);
10005 EVT WideVT = WideVal.getValueType();
10006 unsigned ConvertedOp = 0;
10007 // Use a target machine opcode to prevent further DAGCombine
10008 // optimizations that may separate the arithmetic operations
10009 // from the setcc node.
10010 switch (WideVal.getOpcode()) {
10012 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10013 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10014 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10015 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10016 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10020 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10021 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10022 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10023 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10024 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10030 // Emit a CMP with 0, which is the TEST pattern.
10031 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10032 DAG.getConstant(0, Op.getValueType()));
10034 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10035 SmallVector<SDValue, 4> Ops;
10036 for (unsigned i = 0; i != NumOperands; ++i)
10037 Ops.push_back(Op.getOperand(i));
10039 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10040 DAG.ReplaceAllUsesWith(Op, New);
10041 return SDValue(New.getNode(), 1);
10044 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10046 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10047 SDLoc dl, SelectionDAG &DAG) const {
10048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10049 if (C->getAPIntValue() == 0)
10050 return EmitTest(Op0, X86CC, dl, DAG);
10052 if (Op0.getValueType() == MVT::i1)
10053 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10056 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10057 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10058 // Do the comparison at i32 if it's smaller, besides the Atom case.
10059 // This avoids subregister aliasing issues. Keep the smaller reference
10060 // if we're optimizing for size, however, as that'll allow better folding
10061 // of memory operations.
10062 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10063 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10064 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10065 !Subtarget->isAtom()) {
10066 unsigned ExtendOp =
10067 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10068 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10069 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10071 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10072 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10073 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10075 return SDValue(Sub.getNode(), 1);
10077 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10080 /// Convert a comparison if required by the subtarget.
10081 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10082 SelectionDAG &DAG) const {
10083 // If the subtarget does not support the FUCOMI instruction, floating-point
10084 // comparisons have to be converted.
10085 if (Subtarget->hasCMov() ||
10086 Cmp.getOpcode() != X86ISD::CMP ||
10087 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10088 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10091 // The instruction selector will select an FUCOM instruction instead of
10092 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10093 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10094 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10096 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10097 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10098 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10099 DAG.getConstant(8, MVT::i8));
10100 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10101 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10104 static bool isAllOnes(SDValue V) {
10105 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10106 return C && C->isAllOnesValue();
10109 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10110 /// if it's possible.
10111 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10112 SDLoc dl, SelectionDAG &DAG) const {
10113 SDValue Op0 = And.getOperand(0);
10114 SDValue Op1 = And.getOperand(1);
10115 if (Op0.getOpcode() == ISD::TRUNCATE)
10116 Op0 = Op0.getOperand(0);
10117 if (Op1.getOpcode() == ISD::TRUNCATE)
10118 Op1 = Op1.getOperand(0);
10121 if (Op1.getOpcode() == ISD::SHL)
10122 std::swap(Op0, Op1);
10123 if (Op0.getOpcode() == ISD::SHL) {
10124 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10125 if (And00C->getZExtValue() == 1) {
10126 // If we looked past a truncate, check that it's only truncating away
10128 unsigned BitWidth = Op0.getValueSizeInBits();
10129 unsigned AndBitWidth = And.getValueSizeInBits();
10130 if (BitWidth > AndBitWidth) {
10132 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10133 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10137 RHS = Op0.getOperand(1);
10139 } else if (Op1.getOpcode() == ISD::Constant) {
10140 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10141 uint64_t AndRHSVal = AndRHS->getZExtValue();
10142 SDValue AndLHS = Op0;
10144 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10145 LHS = AndLHS.getOperand(0);
10146 RHS = AndLHS.getOperand(1);
10149 // Use BT if the immediate can't be encoded in a TEST instruction.
10150 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10152 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10156 if (LHS.getNode()) {
10157 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10158 // instruction. Since the shift amount is in-range-or-undefined, we know
10159 // that doing a bittest on the i32 value is ok. We extend to i32 because
10160 // the encoding for the i16 version is larger than the i32 version.
10161 // Also promote i16 to i32 for performance / code size reason.
10162 if (LHS.getValueType() == MVT::i8 ||
10163 LHS.getValueType() == MVT::i16)
10164 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10166 // If the operand types disagree, extend the shift amount to match. Since
10167 // BT ignores high bits (like shifts) we can use anyextend.
10168 if (LHS.getValueType() != RHS.getValueType())
10169 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10171 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10172 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10173 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10174 DAG.getConstant(Cond, MVT::i8), BT);
10180 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10182 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10187 // SSE Condition code mapping:
10196 switch (SetCCOpcode) {
10197 default: llvm_unreachable("Unexpected SETCC condition");
10199 case ISD::SETEQ: SSECC = 0; break;
10201 case ISD::SETGT: Swap = true; // Fallthrough
10203 case ISD::SETOLT: SSECC = 1; break;
10205 case ISD::SETGE: Swap = true; // Fallthrough
10207 case ISD::SETOLE: SSECC = 2; break;
10208 case ISD::SETUO: SSECC = 3; break;
10210 case ISD::SETNE: SSECC = 4; break;
10211 case ISD::SETULE: Swap = true; // Fallthrough
10212 case ISD::SETUGE: SSECC = 5; break;
10213 case ISD::SETULT: Swap = true; // Fallthrough
10214 case ISD::SETUGT: SSECC = 6; break;
10215 case ISD::SETO: SSECC = 7; break;
10217 case ISD::SETONE: SSECC = 8; break;
10220 std::swap(Op0, Op1);
10225 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10226 // ones, and then concatenate the result back.
10227 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10228 MVT VT = Op.getSimpleValueType();
10230 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10231 "Unsupported value type for operation");
10233 unsigned NumElems = VT.getVectorNumElements();
10235 SDValue CC = Op.getOperand(2);
10237 // Extract the LHS vectors
10238 SDValue LHS = Op.getOperand(0);
10239 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10240 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10242 // Extract the RHS vectors
10243 SDValue RHS = Op.getOperand(1);
10244 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10245 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10247 // Issue the operation on the smaller types and concatenate the result back
10248 MVT EltVT = VT.getVectorElementType();
10249 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10250 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10251 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10252 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10255 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10256 const X86Subtarget *Subtarget) {
10257 SDValue Op0 = Op.getOperand(0);
10258 SDValue Op1 = Op.getOperand(1);
10259 SDValue CC = Op.getOperand(2);
10260 MVT VT = Op.getSimpleValueType();
10263 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10264 Op.getValueType().getScalarType() == MVT::i1 &&
10265 "Cannot set masked compare for this operation");
10267 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10269 bool Unsigned = false;
10272 switch (SetCCOpcode) {
10273 default: llvm_unreachable("Unexpected SETCC condition");
10274 case ISD::SETNE: SSECC = 4; break;
10275 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10276 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10277 case ISD::SETLT: Swap = true; //fall-through
10278 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10279 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10280 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10281 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10282 case ISD::SETULE: Unsigned = true; //fall-through
10283 case ISD::SETLE: SSECC = 2; break;
10287 std::swap(Op0, Op1);
10289 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10290 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10291 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10292 DAG.getConstant(SSECC, MVT::i8));
10295 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10296 /// operand \p Op1. If non-trivial (for example because it's not constant)
10297 /// return an empty value.
10298 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10300 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10304 MVT VT = Op1.getSimpleValueType();
10305 MVT EVT = VT.getVectorElementType();
10306 unsigned n = VT.getVectorNumElements();
10307 SmallVector<SDValue, 8> ULTOp1;
10309 for (unsigned i = 0; i < n; ++i) {
10310 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10311 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10314 // Avoid underflow.
10315 APInt Val = Elt->getAPIntValue();
10319 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10322 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10325 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10326 SelectionDAG &DAG) {
10327 SDValue Op0 = Op.getOperand(0);
10328 SDValue Op1 = Op.getOperand(1);
10329 SDValue CC = Op.getOperand(2);
10330 MVT VT = Op.getSimpleValueType();
10331 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10332 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10337 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10338 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10341 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10342 unsigned Opc = X86ISD::CMPP;
10343 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10344 assert(VT.getVectorNumElements() <= 16);
10345 Opc = X86ISD::CMPM;
10347 // In the two special cases we can't handle, emit two comparisons.
10350 unsigned CombineOpc;
10351 if (SetCCOpcode == ISD::SETUEQ) {
10352 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10354 assert(SetCCOpcode == ISD::SETONE);
10355 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10358 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10359 DAG.getConstant(CC0, MVT::i8));
10360 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10361 DAG.getConstant(CC1, MVT::i8));
10362 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10364 // Handle all other FP comparisons here.
10365 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10366 DAG.getConstant(SSECC, MVT::i8));
10369 // Break 256-bit integer vector compare into smaller ones.
10370 if (VT.is256BitVector() && !Subtarget->hasInt256())
10371 return Lower256IntVSETCC(Op, DAG);
10373 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10374 EVT OpVT = Op1.getValueType();
10375 if (Subtarget->hasAVX512()) {
10376 if (Op1.getValueType().is512BitVector() ||
10377 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10378 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10380 // In AVX-512 architecture setcc returns mask with i1 elements,
10381 // But there is no compare instruction for i8 and i16 elements.
10382 // We are not talking about 512-bit operands in this case, these
10383 // types are illegal.
10385 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10386 OpVT.getVectorElementType().getSizeInBits() >= 8))
10387 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10388 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10391 // We are handling one of the integer comparisons here. Since SSE only has
10392 // GT and EQ comparisons for integer, swapping operands and multiple
10393 // operations may be required for some comparisons.
10395 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10396 bool Subus = false;
10398 switch (SetCCOpcode) {
10399 default: llvm_unreachable("Unexpected SETCC condition");
10400 case ISD::SETNE: Invert = true;
10401 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10402 case ISD::SETLT: Swap = true;
10403 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10404 case ISD::SETGE: Swap = true;
10405 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10406 Invert = true; break;
10407 case ISD::SETULT: Swap = true;
10408 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10409 FlipSigns = true; break;
10410 case ISD::SETUGE: Swap = true;
10411 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10412 FlipSigns = true; Invert = true; break;
10415 // Special case: Use min/max operations for SETULE/SETUGE
10416 MVT VET = VT.getVectorElementType();
10418 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10419 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10422 switch (SetCCOpcode) {
10424 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10425 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10428 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10431 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10432 if (!MinMax && hasSubus) {
10433 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10435 // t = psubus Op0, Op1
10436 // pcmpeq t, <0..0>
10437 switch (SetCCOpcode) {
10439 case ISD::SETULT: {
10440 // If the comparison is against a constant we can turn this into a
10441 // setule. With psubus, setule does not require a swap. This is
10442 // beneficial because the constant in the register is no longer
10443 // destructed as the destination so it can be hoisted out of a loop.
10444 // Only do this pre-AVX since vpcmp* is no longer destructive.
10445 if (Subtarget->hasAVX())
10447 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10448 if (ULEOp1.getNode()) {
10450 Subus = true; Invert = false; Swap = false;
10454 // Psubus is better than flip-sign because it requires no inversion.
10455 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10456 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10460 Opc = X86ISD::SUBUS;
10466 std::swap(Op0, Op1);
10468 // Check that the operation in question is available (most are plain SSE2,
10469 // but PCMPGTQ and PCMPEQQ have different requirements).
10470 if (VT == MVT::v2i64) {
10471 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10472 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10474 // First cast everything to the right type.
10475 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10476 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10478 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10479 // bits of the inputs before performing those operations. The lower
10480 // compare is always unsigned.
10483 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10485 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10486 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10487 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10488 Sign, Zero, Sign, Zero);
10490 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10491 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10493 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10494 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10495 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10497 // Create masks for only the low parts/high parts of the 64 bit integers.
10498 static const int MaskHi[] = { 1, 1, 3, 3 };
10499 static const int MaskLo[] = { 0, 0, 2, 2 };
10500 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10501 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10502 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10504 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10505 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10508 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10510 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10513 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10514 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10515 // pcmpeqd + pshufd + pand.
10516 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10518 // First cast everything to the right type.
10519 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10520 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10523 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10525 // Make sure the lower and upper halves are both all-ones.
10526 static const int Mask[] = { 1, 0, 3, 2 };
10527 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10528 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10531 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10533 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10537 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10538 // bits of the inputs before performing those operations.
10540 EVT EltVT = VT.getVectorElementType();
10541 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10542 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10543 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10546 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10548 // If the logical-not of the result is required, perform that now.
10550 Result = DAG.getNOT(dl, Result, VT);
10553 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10556 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10557 getZeroVector(VT, Subtarget, DAG, dl));
10562 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10564 MVT VT = Op.getSimpleValueType();
10566 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10568 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10569 && "SetCC type must be 8-bit or 1-bit integer");
10570 SDValue Op0 = Op.getOperand(0);
10571 SDValue Op1 = Op.getOperand(1);
10573 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10575 // Optimize to BT if possible.
10576 // Lower (X & (1 << N)) == 0 to BT(X, N).
10577 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10578 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10579 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10580 Op1.getOpcode() == ISD::Constant &&
10581 cast<ConstantSDNode>(Op1)->isNullValue() &&
10582 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10583 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10584 if (NewSetCC.getNode())
10588 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10590 if (Op1.getOpcode() == ISD::Constant &&
10591 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10592 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10593 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10595 // If the input is a setcc, then reuse the input setcc or use a new one with
10596 // the inverted condition.
10597 if (Op0.getOpcode() == X86ISD::SETCC) {
10598 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10599 bool Invert = (CC == ISD::SETNE) ^
10600 cast<ConstantSDNode>(Op1)->isNullValue();
10604 CCode = X86::GetOppositeBranchCondition(CCode);
10605 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10606 DAG.getConstant(CCode, MVT::i8),
10607 Op0.getOperand(1));
10609 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10613 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10614 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10615 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10617 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10618 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10621 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10622 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10623 if (X86CC == X86::COND_INVALID)
10626 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10627 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10628 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10629 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10631 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10635 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10636 static bool isX86LogicalCmp(SDValue Op) {
10637 unsigned Opc = Op.getNode()->getOpcode();
10638 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10639 Opc == X86ISD::SAHF)
10641 if (Op.getResNo() == 1 &&
10642 (Opc == X86ISD::ADD ||
10643 Opc == X86ISD::SUB ||
10644 Opc == X86ISD::ADC ||
10645 Opc == X86ISD::SBB ||
10646 Opc == X86ISD::SMUL ||
10647 Opc == X86ISD::UMUL ||
10648 Opc == X86ISD::INC ||
10649 Opc == X86ISD::DEC ||
10650 Opc == X86ISD::OR ||
10651 Opc == X86ISD::XOR ||
10652 Opc == X86ISD::AND))
10655 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10661 static bool isZero(SDValue V) {
10662 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10663 return C && C->isNullValue();
10666 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10667 if (V.getOpcode() != ISD::TRUNCATE)
10670 SDValue VOp0 = V.getOperand(0);
10671 unsigned InBits = VOp0.getValueSizeInBits();
10672 unsigned Bits = V.getValueSizeInBits();
10673 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10676 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10677 bool addTest = true;
10678 SDValue Cond = Op.getOperand(0);
10679 SDValue Op1 = Op.getOperand(1);
10680 SDValue Op2 = Op.getOperand(2);
10682 EVT VT = Op1.getValueType();
10685 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10686 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10687 // sequence later on.
10688 if (Cond.getOpcode() == ISD::SETCC &&
10689 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10690 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10691 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10692 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10693 int SSECC = translateX86FSETCC(
10694 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10697 if (Subtarget->hasAVX512()) {
10698 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10699 DAG.getConstant(SSECC, MVT::i8));
10700 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10702 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10703 DAG.getConstant(SSECC, MVT::i8));
10704 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10705 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10706 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10710 if (Cond.getOpcode() == ISD::SETCC) {
10711 SDValue NewCond = LowerSETCC(Cond, DAG);
10712 if (NewCond.getNode())
10716 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10717 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10718 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10719 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10720 if (Cond.getOpcode() == X86ISD::SETCC &&
10721 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10722 isZero(Cond.getOperand(1).getOperand(1))) {
10723 SDValue Cmp = Cond.getOperand(1);
10725 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10727 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10728 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10729 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10731 SDValue CmpOp0 = Cmp.getOperand(0);
10732 // Apply further optimizations for special cases
10733 // (select (x != 0), -1, 0) -> neg & sbb
10734 // (select (x == 0), 0, -1) -> neg & sbb
10735 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10736 if (YC->isNullValue() &&
10737 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10738 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10739 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10740 DAG.getConstant(0, CmpOp0.getValueType()),
10742 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10743 DAG.getConstant(X86::COND_B, MVT::i8),
10744 SDValue(Neg.getNode(), 1));
10748 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10749 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10750 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10752 SDValue Res = // Res = 0 or -1.
10753 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10754 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10756 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10757 Res = DAG.getNOT(DL, Res, Res.getValueType());
10759 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10760 if (!N2C || !N2C->isNullValue())
10761 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10766 // Look past (and (setcc_carry (cmp ...)), 1).
10767 if (Cond.getOpcode() == ISD::AND &&
10768 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10769 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10770 if (C && C->getAPIntValue() == 1)
10771 Cond = Cond.getOperand(0);
10774 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10775 // setting operand in place of the X86ISD::SETCC.
10776 unsigned CondOpcode = Cond.getOpcode();
10777 if (CondOpcode == X86ISD::SETCC ||
10778 CondOpcode == X86ISD::SETCC_CARRY) {
10779 CC = Cond.getOperand(0);
10781 SDValue Cmp = Cond.getOperand(1);
10782 unsigned Opc = Cmp.getOpcode();
10783 MVT VT = Op.getSimpleValueType();
10785 bool IllegalFPCMov = false;
10786 if (VT.isFloatingPoint() && !VT.isVector() &&
10787 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10788 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10790 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10791 Opc == X86ISD::BT) { // FIXME
10795 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10796 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10797 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10798 Cond.getOperand(0).getValueType() != MVT::i8)) {
10799 SDValue LHS = Cond.getOperand(0);
10800 SDValue RHS = Cond.getOperand(1);
10801 unsigned X86Opcode;
10804 switch (CondOpcode) {
10805 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10806 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10807 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10808 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10809 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10810 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10811 default: llvm_unreachable("unexpected overflowing operator");
10813 if (CondOpcode == ISD::UMULO)
10814 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10817 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10819 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10821 if (CondOpcode == ISD::UMULO)
10822 Cond = X86Op.getValue(2);
10824 Cond = X86Op.getValue(1);
10826 CC = DAG.getConstant(X86Cond, MVT::i8);
10831 // Look pass the truncate if the high bits are known zero.
10832 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10833 Cond = Cond.getOperand(0);
10835 // We know the result of AND is compared against zero. Try to match
10837 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10838 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10839 if (NewSetCC.getNode()) {
10840 CC = NewSetCC.getOperand(0);
10841 Cond = NewSetCC.getOperand(1);
10848 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10849 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10852 // a < b ? -1 : 0 -> RES = ~setcc_carry
10853 // a < b ? 0 : -1 -> RES = setcc_carry
10854 // a >= b ? -1 : 0 -> RES = setcc_carry
10855 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10856 if (Cond.getOpcode() == X86ISD::SUB) {
10857 Cond = ConvertCmpIfNecessary(Cond, DAG);
10858 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10860 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10861 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10862 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10863 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10864 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10865 return DAG.getNOT(DL, Res, Res.getValueType());
10870 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10871 // widen the cmov and push the truncate through. This avoids introducing a new
10872 // branch during isel and doesn't add any extensions.
10873 if (Op.getValueType() == MVT::i8 &&
10874 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10875 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10876 if (T1.getValueType() == T2.getValueType() &&
10877 // Blacklist CopyFromReg to avoid partial register stalls.
10878 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10879 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10880 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10881 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10885 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10886 // condition is true.
10887 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10888 SDValue Ops[] = { Op2, Op1, CC, Cond };
10889 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10892 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10893 MVT VT = Op->getSimpleValueType(0);
10894 SDValue In = Op->getOperand(0);
10895 MVT InVT = In.getSimpleValueType();
10898 unsigned int NumElts = VT.getVectorNumElements();
10899 if (NumElts != 8 && NumElts != 16)
10902 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10903 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10906 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10908 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10909 Constant *C = ConstantInt::get(*DAG.getContext(),
10910 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10912 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10913 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10914 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10915 MachinePointerInfo::getConstantPool(),
10916 false, false, false, Alignment);
10917 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10918 if (VT.is512BitVector())
10920 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10923 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10924 SelectionDAG &DAG) {
10925 MVT VT = Op->getSimpleValueType(0);
10926 SDValue In = Op->getOperand(0);
10927 MVT InVT = In.getSimpleValueType();
10930 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10931 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10933 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10934 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10935 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10938 if (Subtarget->hasInt256())
10939 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10941 // Optimize vectors in AVX mode
10942 // Sign extend v8i16 to v8i32 and
10945 // Divide input vector into two parts
10946 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10947 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10948 // concat the vectors to original VT
10950 unsigned NumElems = InVT.getVectorNumElements();
10951 SDValue Undef = DAG.getUNDEF(InVT);
10953 SmallVector<int,8> ShufMask1(NumElems, -1);
10954 for (unsigned i = 0; i != NumElems/2; ++i)
10957 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10959 SmallVector<int,8> ShufMask2(NumElems, -1);
10960 for (unsigned i = 0; i != NumElems/2; ++i)
10961 ShufMask2[i] = i + NumElems/2;
10963 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10965 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10966 VT.getVectorNumElements()/2);
10968 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10969 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10971 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10974 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10975 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10976 // from the AND / OR.
10977 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10978 Opc = Op.getOpcode();
10979 if (Opc != ISD::OR && Opc != ISD::AND)
10981 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10982 Op.getOperand(0).hasOneUse() &&
10983 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10984 Op.getOperand(1).hasOneUse());
10987 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10988 // 1 and that the SETCC node has a single use.
10989 static bool isXor1OfSetCC(SDValue Op) {
10990 if (Op.getOpcode() != ISD::XOR)
10992 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10993 if (N1C && N1C->getAPIntValue() == 1) {
10994 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10995 Op.getOperand(0).hasOneUse();
11000 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11001 bool addTest = true;
11002 SDValue Chain = Op.getOperand(0);
11003 SDValue Cond = Op.getOperand(1);
11004 SDValue Dest = Op.getOperand(2);
11007 bool Inverted = false;
11009 if (Cond.getOpcode() == ISD::SETCC) {
11010 // Check for setcc([su]{add,sub,mul}o == 0).
11011 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11012 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11013 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11014 Cond.getOperand(0).getResNo() == 1 &&
11015 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11016 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11017 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11018 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11019 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11020 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11022 Cond = Cond.getOperand(0);
11024 SDValue NewCond = LowerSETCC(Cond, DAG);
11025 if (NewCond.getNode())
11030 // FIXME: LowerXALUO doesn't handle these!!
11031 else if (Cond.getOpcode() == X86ISD::ADD ||
11032 Cond.getOpcode() == X86ISD::SUB ||
11033 Cond.getOpcode() == X86ISD::SMUL ||
11034 Cond.getOpcode() == X86ISD::UMUL)
11035 Cond = LowerXALUO(Cond, DAG);
11038 // Look pass (and (setcc_carry (cmp ...)), 1).
11039 if (Cond.getOpcode() == ISD::AND &&
11040 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11041 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11042 if (C && C->getAPIntValue() == 1)
11043 Cond = Cond.getOperand(0);
11046 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11047 // setting operand in place of the X86ISD::SETCC.
11048 unsigned CondOpcode = Cond.getOpcode();
11049 if (CondOpcode == X86ISD::SETCC ||
11050 CondOpcode == X86ISD::SETCC_CARRY) {
11051 CC = Cond.getOperand(0);
11053 SDValue Cmp = Cond.getOperand(1);
11054 unsigned Opc = Cmp.getOpcode();
11055 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11056 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11060 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11064 // These can only come from an arithmetic instruction with overflow,
11065 // e.g. SADDO, UADDO.
11066 Cond = Cond.getNode()->getOperand(1);
11072 CondOpcode = Cond.getOpcode();
11073 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11074 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11075 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11076 Cond.getOperand(0).getValueType() != MVT::i8)) {
11077 SDValue LHS = Cond.getOperand(0);
11078 SDValue RHS = Cond.getOperand(1);
11079 unsigned X86Opcode;
11082 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11083 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11085 switch (CondOpcode) {
11086 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11090 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11093 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11094 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11096 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11098 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11101 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11102 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11103 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11104 default: llvm_unreachable("unexpected overflowing operator");
11107 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11108 if (CondOpcode == ISD::UMULO)
11109 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11112 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11114 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11116 if (CondOpcode == ISD::UMULO)
11117 Cond = X86Op.getValue(2);
11119 Cond = X86Op.getValue(1);
11121 CC = DAG.getConstant(X86Cond, MVT::i8);
11125 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11126 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11127 if (CondOpc == ISD::OR) {
11128 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11129 // two branches instead of an explicit OR instruction with a
11131 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11132 isX86LogicalCmp(Cmp)) {
11133 CC = Cond.getOperand(0).getOperand(0);
11134 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11135 Chain, Dest, CC, Cmp);
11136 CC = Cond.getOperand(1).getOperand(0);
11140 } else { // ISD::AND
11141 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11142 // two branches instead of an explicit AND instruction with a
11143 // separate test. However, we only do this if this block doesn't
11144 // have a fall-through edge, because this requires an explicit
11145 // jmp when the condition is false.
11146 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11147 isX86LogicalCmp(Cmp) &&
11148 Op.getNode()->hasOneUse()) {
11149 X86::CondCode CCode =
11150 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11151 CCode = X86::GetOppositeBranchCondition(CCode);
11152 CC = DAG.getConstant(CCode, MVT::i8);
11153 SDNode *User = *Op.getNode()->use_begin();
11154 // Look for an unconditional branch following this conditional branch.
11155 // We need this because we need to reverse the successors in order
11156 // to implement FCMP_OEQ.
11157 if (User->getOpcode() == ISD::BR) {
11158 SDValue FalseBB = User->getOperand(1);
11160 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11161 assert(NewBR == User);
11165 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11166 Chain, Dest, CC, Cmp);
11167 X86::CondCode CCode =
11168 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11169 CCode = X86::GetOppositeBranchCondition(CCode);
11170 CC = DAG.getConstant(CCode, MVT::i8);
11176 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11177 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11178 // It should be transformed during dag combiner except when the condition
11179 // is set by a arithmetics with overflow node.
11180 X86::CondCode CCode =
11181 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11182 CCode = X86::GetOppositeBranchCondition(CCode);
11183 CC = DAG.getConstant(CCode, MVT::i8);
11184 Cond = Cond.getOperand(0).getOperand(1);
11186 } else if (Cond.getOpcode() == ISD::SETCC &&
11187 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11188 // For FCMP_OEQ, we can emit
11189 // two branches instead of an explicit AND instruction with a
11190 // separate test. However, we only do this if this block doesn't
11191 // have a fall-through edge, because this requires an explicit
11192 // jmp when the condition is false.
11193 if (Op.getNode()->hasOneUse()) {
11194 SDNode *User = *Op.getNode()->use_begin();
11195 // Look for an unconditional branch following this conditional branch.
11196 // We need this because we need to reverse the successors in order
11197 // to implement FCMP_OEQ.
11198 if (User->getOpcode() == ISD::BR) {
11199 SDValue FalseBB = User->getOperand(1);
11201 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11202 assert(NewBR == User);
11206 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11207 Cond.getOperand(0), Cond.getOperand(1));
11208 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11209 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11210 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11211 Chain, Dest, CC, Cmp);
11212 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11217 } else if (Cond.getOpcode() == ISD::SETCC &&
11218 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11219 // For FCMP_UNE, we can emit
11220 // two branches instead of an explicit AND instruction with a
11221 // separate test. However, we only do this if this block doesn't
11222 // have a fall-through edge, because this requires an explicit
11223 // jmp when the condition is false.
11224 if (Op.getNode()->hasOneUse()) {
11225 SDNode *User = *Op.getNode()->use_begin();
11226 // Look for an unconditional branch following this conditional branch.
11227 // We need this because we need to reverse the successors in order
11228 // to implement FCMP_UNE.
11229 if (User->getOpcode() == ISD::BR) {
11230 SDValue FalseBB = User->getOperand(1);
11232 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11233 assert(NewBR == User);
11236 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11237 Cond.getOperand(0), Cond.getOperand(1));
11238 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11239 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11240 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11241 Chain, Dest, CC, Cmp);
11242 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11252 // Look pass the truncate if the high bits are known zero.
11253 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11254 Cond = Cond.getOperand(0);
11256 // We know the result of AND is compared against zero. Try to match
11258 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11259 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11260 if (NewSetCC.getNode()) {
11261 CC = NewSetCC.getOperand(0);
11262 Cond = NewSetCC.getOperand(1);
11269 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11270 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11272 Cond = ConvertCmpIfNecessary(Cond, DAG);
11273 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11274 Chain, Dest, CC, Cond);
11277 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11278 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11279 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11280 // that the guard pages used by the OS virtual memory manager are allocated in
11281 // correct sequence.
11283 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11284 SelectionDAG &DAG) const {
11285 MachineFunction &MF = DAG.getMachineFunction();
11286 bool SplitStack = MF.shouldSplitStack();
11287 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11292 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11293 SDNode* Node = Op.getNode();
11295 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11296 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11297 " not tell us which reg is the stack pointer!");
11298 EVT VT = Node->getValueType(0);
11299 SDValue Tmp1 = SDValue(Node, 0);
11300 SDValue Tmp2 = SDValue(Node, 1);
11301 SDValue Tmp3 = Node->getOperand(2);
11302 SDValue Chain = Tmp1.getOperand(0);
11304 // Chain the dynamic stack allocation so that it doesn't modify the stack
11305 // pointer when other instructions are using the stack.
11306 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11309 SDValue Size = Tmp2.getOperand(1);
11310 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11311 Chain = SP.getValue(1);
11312 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11313 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11314 unsigned StackAlign = TFI.getStackAlignment();
11315 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11316 if (Align > StackAlign)
11317 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11318 DAG.getConstant(-(uint64_t)Align, VT));
11319 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11321 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11322 DAG.getIntPtrConstant(0, true), SDValue(),
11325 SDValue Ops[2] = { Tmp1, Tmp2 };
11326 return DAG.getMergeValues(Ops, dl);
11330 SDValue Chain = Op.getOperand(0);
11331 SDValue Size = Op.getOperand(1);
11332 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11333 EVT VT = Op.getNode()->getValueType(0);
11335 bool Is64Bit = Subtarget->is64Bit();
11336 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11339 MachineRegisterInfo &MRI = MF.getRegInfo();
11342 // The 64 bit implementation of segmented stacks needs to clobber both r10
11343 // r11. This makes it impossible to use it along with nested parameters.
11344 const Function *F = MF.getFunction();
11346 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11348 if (I->hasNestAttr())
11349 report_fatal_error("Cannot use segmented stacks with functions that "
11350 "have nested arguments.");
11353 const TargetRegisterClass *AddrRegClass =
11354 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11355 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11356 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11357 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11358 DAG.getRegister(Vreg, SPTy));
11359 SDValue Ops1[2] = { Value, Chain };
11360 return DAG.getMergeValues(Ops1, dl);
11363 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11365 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11366 Flag = Chain.getValue(1);
11367 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11369 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11371 const X86RegisterInfo *RegInfo =
11372 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11373 unsigned SPReg = RegInfo->getStackRegister();
11374 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11375 Chain = SP.getValue(1);
11378 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11379 DAG.getConstant(-(uint64_t)Align, VT));
11380 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11383 SDValue Ops1[2] = { SP, Chain };
11384 return DAG.getMergeValues(Ops1, dl);
11388 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11389 MachineFunction &MF = DAG.getMachineFunction();
11390 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11392 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11395 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11396 // vastart just stores the address of the VarArgsFrameIndex slot into the
11397 // memory location argument.
11398 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11400 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11401 MachinePointerInfo(SV), false, false, 0);
11405 // gp_offset (0 - 6 * 8)
11406 // fp_offset (48 - 48 + 8 * 16)
11407 // overflow_arg_area (point to parameters coming in memory).
11409 SmallVector<SDValue, 8> MemOps;
11410 SDValue FIN = Op.getOperand(1);
11412 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11413 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11415 FIN, MachinePointerInfo(SV), false, false, 0);
11416 MemOps.push_back(Store);
11419 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11420 FIN, DAG.getIntPtrConstant(4));
11421 Store = DAG.getStore(Op.getOperand(0), DL,
11422 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11424 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11425 MemOps.push_back(Store);
11427 // Store ptr to overflow_arg_area
11428 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11429 FIN, DAG.getIntPtrConstant(4));
11430 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11432 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11433 MachinePointerInfo(SV, 8),
11435 MemOps.push_back(Store);
11437 // Store ptr to reg_save_area.
11438 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11439 FIN, DAG.getIntPtrConstant(8));
11440 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11442 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11443 MachinePointerInfo(SV, 16), false, false, 0);
11444 MemOps.push_back(Store);
11445 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11448 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11449 assert(Subtarget->is64Bit() &&
11450 "LowerVAARG only handles 64-bit va_arg!");
11451 assert((Subtarget->isTargetLinux() ||
11452 Subtarget->isTargetDarwin()) &&
11453 "Unhandled target in LowerVAARG");
11454 assert(Op.getNode()->getNumOperands() == 4);
11455 SDValue Chain = Op.getOperand(0);
11456 SDValue SrcPtr = Op.getOperand(1);
11457 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11458 unsigned Align = Op.getConstantOperandVal(3);
11461 EVT ArgVT = Op.getNode()->getValueType(0);
11462 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11463 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11466 // Decide which area this value should be read from.
11467 // TODO: Implement the AMD64 ABI in its entirety. This simple
11468 // selection mechanism works only for the basic types.
11469 if (ArgVT == MVT::f80) {
11470 llvm_unreachable("va_arg for f80 not yet implemented");
11471 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11472 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11473 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11474 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11476 llvm_unreachable("Unhandled argument type in LowerVAARG");
11479 if (ArgMode == 2) {
11480 // Sanity Check: Make sure using fp_offset makes sense.
11481 assert(!getTargetMachine().Options.UseSoftFloat &&
11482 !(DAG.getMachineFunction()
11483 .getFunction()->getAttributes()
11484 .hasAttribute(AttributeSet::FunctionIndex,
11485 Attribute::NoImplicitFloat)) &&
11486 Subtarget->hasSSE1());
11489 // Insert VAARG_64 node into the DAG
11490 // VAARG_64 returns two values: Variable Argument Address, Chain
11491 SmallVector<SDValue, 11> InstOps;
11492 InstOps.push_back(Chain);
11493 InstOps.push_back(SrcPtr);
11494 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11495 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11496 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11497 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11498 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11499 VTs, InstOps, MVT::i64,
11500 MachinePointerInfo(SV),
11502 /*Volatile=*/false,
11504 /*WriteMem=*/true);
11505 Chain = VAARG.getValue(1);
11507 // Load the next argument and return it
11508 return DAG.getLoad(ArgVT, dl,
11511 MachinePointerInfo(),
11512 false, false, false, 0);
11515 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11516 SelectionDAG &DAG) {
11517 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11518 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11519 SDValue Chain = Op.getOperand(0);
11520 SDValue DstPtr = Op.getOperand(1);
11521 SDValue SrcPtr = Op.getOperand(2);
11522 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11523 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11526 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11527 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11529 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11532 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11533 // amount is a constant. Takes immediate version of shift as input.
11534 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11535 SDValue SrcOp, uint64_t ShiftAmt,
11536 SelectionDAG &DAG) {
11537 MVT ElementType = VT.getVectorElementType();
11539 // Check for ShiftAmt >= element width
11540 if (ShiftAmt >= ElementType.getSizeInBits()) {
11541 if (Opc == X86ISD::VSRAI)
11542 ShiftAmt = ElementType.getSizeInBits() - 1;
11544 return DAG.getConstant(0, VT);
11547 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11548 && "Unknown target vector shift-by-constant node");
11550 // Fold this packed vector shift into a build vector if SrcOp is a
11551 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11552 if (VT == SrcOp.getSimpleValueType() &&
11553 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11554 SmallVector<SDValue, 8> Elts;
11555 unsigned NumElts = SrcOp->getNumOperands();
11556 ConstantSDNode *ND;
11559 default: llvm_unreachable(nullptr);
11560 case X86ISD::VSHLI:
11561 for (unsigned i=0; i!=NumElts; ++i) {
11562 SDValue CurrentOp = SrcOp->getOperand(i);
11563 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11564 Elts.push_back(CurrentOp);
11567 ND = cast<ConstantSDNode>(CurrentOp);
11568 const APInt &C = ND->getAPIntValue();
11569 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11572 case X86ISD::VSRLI:
11573 for (unsigned i=0; i!=NumElts; ++i) {
11574 SDValue CurrentOp = SrcOp->getOperand(i);
11575 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11576 Elts.push_back(CurrentOp);
11579 ND = cast<ConstantSDNode>(CurrentOp);
11580 const APInt &C = ND->getAPIntValue();
11581 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11584 case X86ISD::VSRAI:
11585 for (unsigned i=0; i!=NumElts; ++i) {
11586 SDValue CurrentOp = SrcOp->getOperand(i);
11587 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11588 Elts.push_back(CurrentOp);
11591 ND = cast<ConstantSDNode>(CurrentOp);
11592 const APInt &C = ND->getAPIntValue();
11593 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11598 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11601 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11604 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11605 // may or may not be a constant. Takes immediate version of shift as input.
11606 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11607 SDValue SrcOp, SDValue ShAmt,
11608 SelectionDAG &DAG) {
11609 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11611 // Catch shift-by-constant.
11612 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11613 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11614 CShAmt->getZExtValue(), DAG);
11616 // Change opcode to non-immediate version
11618 default: llvm_unreachable("Unknown target vector shift node");
11619 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11620 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11621 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11624 // Need to build a vector containing shift amount
11625 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11628 ShOps[1] = DAG.getConstant(0, MVT::i32);
11629 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11630 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11632 // The return type has to be a 128-bit type with the same element
11633 // type as the input type.
11634 MVT EltVT = VT.getVectorElementType();
11635 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11637 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11638 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11641 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11643 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11645 default: return SDValue(); // Don't custom lower most intrinsics.
11646 // Comparison intrinsics.
11647 case Intrinsic::x86_sse_comieq_ss:
11648 case Intrinsic::x86_sse_comilt_ss:
11649 case Intrinsic::x86_sse_comile_ss:
11650 case Intrinsic::x86_sse_comigt_ss:
11651 case Intrinsic::x86_sse_comige_ss:
11652 case Intrinsic::x86_sse_comineq_ss:
11653 case Intrinsic::x86_sse_ucomieq_ss:
11654 case Intrinsic::x86_sse_ucomilt_ss:
11655 case Intrinsic::x86_sse_ucomile_ss:
11656 case Intrinsic::x86_sse_ucomigt_ss:
11657 case Intrinsic::x86_sse_ucomige_ss:
11658 case Intrinsic::x86_sse_ucomineq_ss:
11659 case Intrinsic::x86_sse2_comieq_sd:
11660 case Intrinsic::x86_sse2_comilt_sd:
11661 case Intrinsic::x86_sse2_comile_sd:
11662 case Intrinsic::x86_sse2_comigt_sd:
11663 case Intrinsic::x86_sse2_comige_sd:
11664 case Intrinsic::x86_sse2_comineq_sd:
11665 case Intrinsic::x86_sse2_ucomieq_sd:
11666 case Intrinsic::x86_sse2_ucomilt_sd:
11667 case Intrinsic::x86_sse2_ucomile_sd:
11668 case Intrinsic::x86_sse2_ucomigt_sd:
11669 case Intrinsic::x86_sse2_ucomige_sd:
11670 case Intrinsic::x86_sse2_ucomineq_sd: {
11674 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11675 case Intrinsic::x86_sse_comieq_ss:
11676 case Intrinsic::x86_sse2_comieq_sd:
11677 Opc = X86ISD::COMI;
11680 case Intrinsic::x86_sse_comilt_ss:
11681 case Intrinsic::x86_sse2_comilt_sd:
11682 Opc = X86ISD::COMI;
11685 case Intrinsic::x86_sse_comile_ss:
11686 case Intrinsic::x86_sse2_comile_sd:
11687 Opc = X86ISD::COMI;
11690 case Intrinsic::x86_sse_comigt_ss:
11691 case Intrinsic::x86_sse2_comigt_sd:
11692 Opc = X86ISD::COMI;
11695 case Intrinsic::x86_sse_comige_ss:
11696 case Intrinsic::x86_sse2_comige_sd:
11697 Opc = X86ISD::COMI;
11700 case Intrinsic::x86_sse_comineq_ss:
11701 case Intrinsic::x86_sse2_comineq_sd:
11702 Opc = X86ISD::COMI;
11705 case Intrinsic::x86_sse_ucomieq_ss:
11706 case Intrinsic::x86_sse2_ucomieq_sd:
11707 Opc = X86ISD::UCOMI;
11710 case Intrinsic::x86_sse_ucomilt_ss:
11711 case Intrinsic::x86_sse2_ucomilt_sd:
11712 Opc = X86ISD::UCOMI;
11715 case Intrinsic::x86_sse_ucomile_ss:
11716 case Intrinsic::x86_sse2_ucomile_sd:
11717 Opc = X86ISD::UCOMI;
11720 case Intrinsic::x86_sse_ucomigt_ss:
11721 case Intrinsic::x86_sse2_ucomigt_sd:
11722 Opc = X86ISD::UCOMI;
11725 case Intrinsic::x86_sse_ucomige_ss:
11726 case Intrinsic::x86_sse2_ucomige_sd:
11727 Opc = X86ISD::UCOMI;
11730 case Intrinsic::x86_sse_ucomineq_ss:
11731 case Intrinsic::x86_sse2_ucomineq_sd:
11732 Opc = X86ISD::UCOMI;
11737 SDValue LHS = Op.getOperand(1);
11738 SDValue RHS = Op.getOperand(2);
11739 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11740 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11741 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11742 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11743 DAG.getConstant(X86CC, MVT::i8), Cond);
11744 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11747 // Arithmetic intrinsics.
11748 case Intrinsic::x86_sse2_pmulu_dq:
11749 case Intrinsic::x86_avx2_pmulu_dq:
11750 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11751 Op.getOperand(1), Op.getOperand(2));
11753 case Intrinsic::x86_sse41_pmuldq:
11754 case Intrinsic::x86_avx2_pmul_dq:
11755 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11756 Op.getOperand(1), Op.getOperand(2));
11758 case Intrinsic::x86_sse2_pmulhu_w:
11759 case Intrinsic::x86_avx2_pmulhu_w:
11760 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11761 Op.getOperand(1), Op.getOperand(2));
11763 case Intrinsic::x86_sse2_pmulh_w:
11764 case Intrinsic::x86_avx2_pmulh_w:
11765 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11766 Op.getOperand(1), Op.getOperand(2));
11768 // SSE2/AVX2 sub with unsigned saturation intrinsics
11769 case Intrinsic::x86_sse2_psubus_b:
11770 case Intrinsic::x86_sse2_psubus_w:
11771 case Intrinsic::x86_avx2_psubus_b:
11772 case Intrinsic::x86_avx2_psubus_w:
11773 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11774 Op.getOperand(1), Op.getOperand(2));
11776 // SSE3/AVX horizontal add/sub intrinsics
11777 case Intrinsic::x86_sse3_hadd_ps:
11778 case Intrinsic::x86_sse3_hadd_pd:
11779 case Intrinsic::x86_avx_hadd_ps_256:
11780 case Intrinsic::x86_avx_hadd_pd_256:
11781 case Intrinsic::x86_sse3_hsub_ps:
11782 case Intrinsic::x86_sse3_hsub_pd:
11783 case Intrinsic::x86_avx_hsub_ps_256:
11784 case Intrinsic::x86_avx_hsub_pd_256:
11785 case Intrinsic::x86_ssse3_phadd_w_128:
11786 case Intrinsic::x86_ssse3_phadd_d_128:
11787 case Intrinsic::x86_avx2_phadd_w:
11788 case Intrinsic::x86_avx2_phadd_d:
11789 case Intrinsic::x86_ssse3_phsub_w_128:
11790 case Intrinsic::x86_ssse3_phsub_d_128:
11791 case Intrinsic::x86_avx2_phsub_w:
11792 case Intrinsic::x86_avx2_phsub_d: {
11795 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11796 case Intrinsic::x86_sse3_hadd_ps:
11797 case Intrinsic::x86_sse3_hadd_pd:
11798 case Intrinsic::x86_avx_hadd_ps_256:
11799 case Intrinsic::x86_avx_hadd_pd_256:
11800 Opcode = X86ISD::FHADD;
11802 case Intrinsic::x86_sse3_hsub_ps:
11803 case Intrinsic::x86_sse3_hsub_pd:
11804 case Intrinsic::x86_avx_hsub_ps_256:
11805 case Intrinsic::x86_avx_hsub_pd_256:
11806 Opcode = X86ISD::FHSUB;
11808 case Intrinsic::x86_ssse3_phadd_w_128:
11809 case Intrinsic::x86_ssse3_phadd_d_128:
11810 case Intrinsic::x86_avx2_phadd_w:
11811 case Intrinsic::x86_avx2_phadd_d:
11812 Opcode = X86ISD::HADD;
11814 case Intrinsic::x86_ssse3_phsub_w_128:
11815 case Intrinsic::x86_ssse3_phsub_d_128:
11816 case Intrinsic::x86_avx2_phsub_w:
11817 case Intrinsic::x86_avx2_phsub_d:
11818 Opcode = X86ISD::HSUB;
11821 return DAG.getNode(Opcode, dl, Op.getValueType(),
11822 Op.getOperand(1), Op.getOperand(2));
11825 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11826 case Intrinsic::x86_sse2_pmaxu_b:
11827 case Intrinsic::x86_sse41_pmaxuw:
11828 case Intrinsic::x86_sse41_pmaxud:
11829 case Intrinsic::x86_avx2_pmaxu_b:
11830 case Intrinsic::x86_avx2_pmaxu_w:
11831 case Intrinsic::x86_avx2_pmaxu_d:
11832 case Intrinsic::x86_sse2_pminu_b:
11833 case Intrinsic::x86_sse41_pminuw:
11834 case Intrinsic::x86_sse41_pminud:
11835 case Intrinsic::x86_avx2_pminu_b:
11836 case Intrinsic::x86_avx2_pminu_w:
11837 case Intrinsic::x86_avx2_pminu_d:
11838 case Intrinsic::x86_sse41_pmaxsb:
11839 case Intrinsic::x86_sse2_pmaxs_w:
11840 case Intrinsic::x86_sse41_pmaxsd:
11841 case Intrinsic::x86_avx2_pmaxs_b:
11842 case Intrinsic::x86_avx2_pmaxs_w:
11843 case Intrinsic::x86_avx2_pmaxs_d:
11844 case Intrinsic::x86_sse41_pminsb:
11845 case Intrinsic::x86_sse2_pmins_w:
11846 case Intrinsic::x86_sse41_pminsd:
11847 case Intrinsic::x86_avx2_pmins_b:
11848 case Intrinsic::x86_avx2_pmins_w:
11849 case Intrinsic::x86_avx2_pmins_d: {
11852 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11853 case Intrinsic::x86_sse2_pmaxu_b:
11854 case Intrinsic::x86_sse41_pmaxuw:
11855 case Intrinsic::x86_sse41_pmaxud:
11856 case Intrinsic::x86_avx2_pmaxu_b:
11857 case Intrinsic::x86_avx2_pmaxu_w:
11858 case Intrinsic::x86_avx2_pmaxu_d:
11859 Opcode = X86ISD::UMAX;
11861 case Intrinsic::x86_sse2_pminu_b:
11862 case Intrinsic::x86_sse41_pminuw:
11863 case Intrinsic::x86_sse41_pminud:
11864 case Intrinsic::x86_avx2_pminu_b:
11865 case Intrinsic::x86_avx2_pminu_w:
11866 case Intrinsic::x86_avx2_pminu_d:
11867 Opcode = X86ISD::UMIN;
11869 case Intrinsic::x86_sse41_pmaxsb:
11870 case Intrinsic::x86_sse2_pmaxs_w:
11871 case Intrinsic::x86_sse41_pmaxsd:
11872 case Intrinsic::x86_avx2_pmaxs_b:
11873 case Intrinsic::x86_avx2_pmaxs_w:
11874 case Intrinsic::x86_avx2_pmaxs_d:
11875 Opcode = X86ISD::SMAX;
11877 case Intrinsic::x86_sse41_pminsb:
11878 case Intrinsic::x86_sse2_pmins_w:
11879 case Intrinsic::x86_sse41_pminsd:
11880 case Intrinsic::x86_avx2_pmins_b:
11881 case Intrinsic::x86_avx2_pmins_w:
11882 case Intrinsic::x86_avx2_pmins_d:
11883 Opcode = X86ISD::SMIN;
11886 return DAG.getNode(Opcode, dl, Op.getValueType(),
11887 Op.getOperand(1), Op.getOperand(2));
11890 // SSE/SSE2/AVX floating point max/min intrinsics.
11891 case Intrinsic::x86_sse_max_ps:
11892 case Intrinsic::x86_sse2_max_pd:
11893 case Intrinsic::x86_avx_max_ps_256:
11894 case Intrinsic::x86_avx_max_pd_256:
11895 case Intrinsic::x86_sse_min_ps:
11896 case Intrinsic::x86_sse2_min_pd:
11897 case Intrinsic::x86_avx_min_ps_256:
11898 case Intrinsic::x86_avx_min_pd_256: {
11901 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11902 case Intrinsic::x86_sse_max_ps:
11903 case Intrinsic::x86_sse2_max_pd:
11904 case Intrinsic::x86_avx_max_ps_256:
11905 case Intrinsic::x86_avx_max_pd_256:
11906 Opcode = X86ISD::FMAX;
11908 case Intrinsic::x86_sse_min_ps:
11909 case Intrinsic::x86_sse2_min_pd:
11910 case Intrinsic::x86_avx_min_ps_256:
11911 case Intrinsic::x86_avx_min_pd_256:
11912 Opcode = X86ISD::FMIN;
11915 return DAG.getNode(Opcode, dl, Op.getValueType(),
11916 Op.getOperand(1), Op.getOperand(2));
11919 // AVX2 variable shift intrinsics
11920 case Intrinsic::x86_avx2_psllv_d:
11921 case Intrinsic::x86_avx2_psllv_q:
11922 case Intrinsic::x86_avx2_psllv_d_256:
11923 case Intrinsic::x86_avx2_psllv_q_256:
11924 case Intrinsic::x86_avx2_psrlv_d:
11925 case Intrinsic::x86_avx2_psrlv_q:
11926 case Intrinsic::x86_avx2_psrlv_d_256:
11927 case Intrinsic::x86_avx2_psrlv_q_256:
11928 case Intrinsic::x86_avx2_psrav_d:
11929 case Intrinsic::x86_avx2_psrav_d_256: {
11932 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11933 case Intrinsic::x86_avx2_psllv_d:
11934 case Intrinsic::x86_avx2_psllv_q:
11935 case Intrinsic::x86_avx2_psllv_d_256:
11936 case Intrinsic::x86_avx2_psllv_q_256:
11939 case Intrinsic::x86_avx2_psrlv_d:
11940 case Intrinsic::x86_avx2_psrlv_q:
11941 case Intrinsic::x86_avx2_psrlv_d_256:
11942 case Intrinsic::x86_avx2_psrlv_q_256:
11945 case Intrinsic::x86_avx2_psrav_d:
11946 case Intrinsic::x86_avx2_psrav_d_256:
11950 return DAG.getNode(Opcode, dl, Op.getValueType(),
11951 Op.getOperand(1), Op.getOperand(2));
11954 case Intrinsic::x86_ssse3_pshuf_b_128:
11955 case Intrinsic::x86_avx2_pshuf_b:
11956 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11957 Op.getOperand(1), Op.getOperand(2));
11959 case Intrinsic::x86_ssse3_psign_b_128:
11960 case Intrinsic::x86_ssse3_psign_w_128:
11961 case Intrinsic::x86_ssse3_psign_d_128:
11962 case Intrinsic::x86_avx2_psign_b:
11963 case Intrinsic::x86_avx2_psign_w:
11964 case Intrinsic::x86_avx2_psign_d:
11965 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11966 Op.getOperand(1), Op.getOperand(2));
11968 case Intrinsic::x86_sse41_insertps:
11969 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11970 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11972 case Intrinsic::x86_avx_vperm2f128_ps_256:
11973 case Intrinsic::x86_avx_vperm2f128_pd_256:
11974 case Intrinsic::x86_avx_vperm2f128_si_256:
11975 case Intrinsic::x86_avx2_vperm2i128:
11976 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11977 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11979 case Intrinsic::x86_avx2_permd:
11980 case Intrinsic::x86_avx2_permps:
11981 // Operands intentionally swapped. Mask is last operand to intrinsic,
11982 // but second operand for node/instruction.
11983 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11984 Op.getOperand(2), Op.getOperand(1));
11986 case Intrinsic::x86_sse_sqrt_ps:
11987 case Intrinsic::x86_sse2_sqrt_pd:
11988 case Intrinsic::x86_avx_sqrt_ps_256:
11989 case Intrinsic::x86_avx_sqrt_pd_256:
11990 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11992 // ptest and testp intrinsics. The intrinsic these come from are designed to
11993 // return an integer value, not just an instruction so lower it to the ptest
11994 // or testp pattern and a setcc for the result.
11995 case Intrinsic::x86_sse41_ptestz:
11996 case Intrinsic::x86_sse41_ptestc:
11997 case Intrinsic::x86_sse41_ptestnzc:
11998 case Intrinsic::x86_avx_ptestz_256:
11999 case Intrinsic::x86_avx_ptestc_256:
12000 case Intrinsic::x86_avx_ptestnzc_256:
12001 case Intrinsic::x86_avx_vtestz_ps:
12002 case Intrinsic::x86_avx_vtestc_ps:
12003 case Intrinsic::x86_avx_vtestnzc_ps:
12004 case Intrinsic::x86_avx_vtestz_pd:
12005 case Intrinsic::x86_avx_vtestc_pd:
12006 case Intrinsic::x86_avx_vtestnzc_pd:
12007 case Intrinsic::x86_avx_vtestz_ps_256:
12008 case Intrinsic::x86_avx_vtestc_ps_256:
12009 case Intrinsic::x86_avx_vtestnzc_ps_256:
12010 case Intrinsic::x86_avx_vtestz_pd_256:
12011 case Intrinsic::x86_avx_vtestc_pd_256:
12012 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12013 bool IsTestPacked = false;
12016 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12017 case Intrinsic::x86_avx_vtestz_ps:
12018 case Intrinsic::x86_avx_vtestz_pd:
12019 case Intrinsic::x86_avx_vtestz_ps_256:
12020 case Intrinsic::x86_avx_vtestz_pd_256:
12021 IsTestPacked = true; // Fallthrough
12022 case Intrinsic::x86_sse41_ptestz:
12023 case Intrinsic::x86_avx_ptestz_256:
12025 X86CC = X86::COND_E;
12027 case Intrinsic::x86_avx_vtestc_ps:
12028 case Intrinsic::x86_avx_vtestc_pd:
12029 case Intrinsic::x86_avx_vtestc_ps_256:
12030 case Intrinsic::x86_avx_vtestc_pd_256:
12031 IsTestPacked = true; // Fallthrough
12032 case Intrinsic::x86_sse41_ptestc:
12033 case Intrinsic::x86_avx_ptestc_256:
12035 X86CC = X86::COND_B;
12037 case Intrinsic::x86_avx_vtestnzc_ps:
12038 case Intrinsic::x86_avx_vtestnzc_pd:
12039 case Intrinsic::x86_avx_vtestnzc_ps_256:
12040 case Intrinsic::x86_avx_vtestnzc_pd_256:
12041 IsTestPacked = true; // Fallthrough
12042 case Intrinsic::x86_sse41_ptestnzc:
12043 case Intrinsic::x86_avx_ptestnzc_256:
12045 X86CC = X86::COND_A;
12049 SDValue LHS = Op.getOperand(1);
12050 SDValue RHS = Op.getOperand(2);
12051 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12052 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12053 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12054 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12055 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12057 case Intrinsic::x86_avx512_kortestz_w:
12058 case Intrinsic::x86_avx512_kortestc_w: {
12059 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12060 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12061 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12062 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12063 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12064 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12065 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12068 // SSE/AVX shift intrinsics
12069 case Intrinsic::x86_sse2_psll_w:
12070 case Intrinsic::x86_sse2_psll_d:
12071 case Intrinsic::x86_sse2_psll_q:
12072 case Intrinsic::x86_avx2_psll_w:
12073 case Intrinsic::x86_avx2_psll_d:
12074 case Intrinsic::x86_avx2_psll_q:
12075 case Intrinsic::x86_sse2_psrl_w:
12076 case Intrinsic::x86_sse2_psrl_d:
12077 case Intrinsic::x86_sse2_psrl_q:
12078 case Intrinsic::x86_avx2_psrl_w:
12079 case Intrinsic::x86_avx2_psrl_d:
12080 case Intrinsic::x86_avx2_psrl_q:
12081 case Intrinsic::x86_sse2_psra_w:
12082 case Intrinsic::x86_sse2_psra_d:
12083 case Intrinsic::x86_avx2_psra_w:
12084 case Intrinsic::x86_avx2_psra_d: {
12087 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12088 case Intrinsic::x86_sse2_psll_w:
12089 case Intrinsic::x86_sse2_psll_d:
12090 case Intrinsic::x86_sse2_psll_q:
12091 case Intrinsic::x86_avx2_psll_w:
12092 case Intrinsic::x86_avx2_psll_d:
12093 case Intrinsic::x86_avx2_psll_q:
12094 Opcode = X86ISD::VSHL;
12096 case Intrinsic::x86_sse2_psrl_w:
12097 case Intrinsic::x86_sse2_psrl_d:
12098 case Intrinsic::x86_sse2_psrl_q:
12099 case Intrinsic::x86_avx2_psrl_w:
12100 case Intrinsic::x86_avx2_psrl_d:
12101 case Intrinsic::x86_avx2_psrl_q:
12102 Opcode = X86ISD::VSRL;
12104 case Intrinsic::x86_sse2_psra_w:
12105 case Intrinsic::x86_sse2_psra_d:
12106 case Intrinsic::x86_avx2_psra_w:
12107 case Intrinsic::x86_avx2_psra_d:
12108 Opcode = X86ISD::VSRA;
12111 return DAG.getNode(Opcode, dl, Op.getValueType(),
12112 Op.getOperand(1), Op.getOperand(2));
12115 // SSE/AVX immediate shift intrinsics
12116 case Intrinsic::x86_sse2_pslli_w:
12117 case Intrinsic::x86_sse2_pslli_d:
12118 case Intrinsic::x86_sse2_pslli_q:
12119 case Intrinsic::x86_avx2_pslli_w:
12120 case Intrinsic::x86_avx2_pslli_d:
12121 case Intrinsic::x86_avx2_pslli_q:
12122 case Intrinsic::x86_sse2_psrli_w:
12123 case Intrinsic::x86_sse2_psrli_d:
12124 case Intrinsic::x86_sse2_psrli_q:
12125 case Intrinsic::x86_avx2_psrli_w:
12126 case Intrinsic::x86_avx2_psrli_d:
12127 case Intrinsic::x86_avx2_psrli_q:
12128 case Intrinsic::x86_sse2_psrai_w:
12129 case Intrinsic::x86_sse2_psrai_d:
12130 case Intrinsic::x86_avx2_psrai_w:
12131 case Intrinsic::x86_avx2_psrai_d: {
12134 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12135 case Intrinsic::x86_sse2_pslli_w:
12136 case Intrinsic::x86_sse2_pslli_d:
12137 case Intrinsic::x86_sse2_pslli_q:
12138 case Intrinsic::x86_avx2_pslli_w:
12139 case Intrinsic::x86_avx2_pslli_d:
12140 case Intrinsic::x86_avx2_pslli_q:
12141 Opcode = X86ISD::VSHLI;
12143 case Intrinsic::x86_sse2_psrli_w:
12144 case Intrinsic::x86_sse2_psrli_d:
12145 case Intrinsic::x86_sse2_psrli_q:
12146 case Intrinsic::x86_avx2_psrli_w:
12147 case Intrinsic::x86_avx2_psrli_d:
12148 case Intrinsic::x86_avx2_psrli_q:
12149 Opcode = X86ISD::VSRLI;
12151 case Intrinsic::x86_sse2_psrai_w:
12152 case Intrinsic::x86_sse2_psrai_d:
12153 case Intrinsic::x86_avx2_psrai_w:
12154 case Intrinsic::x86_avx2_psrai_d:
12155 Opcode = X86ISD::VSRAI;
12158 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12159 Op.getOperand(1), Op.getOperand(2), DAG);
12162 case Intrinsic::x86_sse42_pcmpistria128:
12163 case Intrinsic::x86_sse42_pcmpestria128:
12164 case Intrinsic::x86_sse42_pcmpistric128:
12165 case Intrinsic::x86_sse42_pcmpestric128:
12166 case Intrinsic::x86_sse42_pcmpistrio128:
12167 case Intrinsic::x86_sse42_pcmpestrio128:
12168 case Intrinsic::x86_sse42_pcmpistris128:
12169 case Intrinsic::x86_sse42_pcmpestris128:
12170 case Intrinsic::x86_sse42_pcmpistriz128:
12171 case Intrinsic::x86_sse42_pcmpestriz128: {
12175 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12176 case Intrinsic::x86_sse42_pcmpistria128:
12177 Opcode = X86ISD::PCMPISTRI;
12178 X86CC = X86::COND_A;
12180 case Intrinsic::x86_sse42_pcmpestria128:
12181 Opcode = X86ISD::PCMPESTRI;
12182 X86CC = X86::COND_A;
12184 case Intrinsic::x86_sse42_pcmpistric128:
12185 Opcode = X86ISD::PCMPISTRI;
12186 X86CC = X86::COND_B;
12188 case Intrinsic::x86_sse42_pcmpestric128:
12189 Opcode = X86ISD::PCMPESTRI;
12190 X86CC = X86::COND_B;
12192 case Intrinsic::x86_sse42_pcmpistrio128:
12193 Opcode = X86ISD::PCMPISTRI;
12194 X86CC = X86::COND_O;
12196 case Intrinsic::x86_sse42_pcmpestrio128:
12197 Opcode = X86ISD::PCMPESTRI;
12198 X86CC = X86::COND_O;
12200 case Intrinsic::x86_sse42_pcmpistris128:
12201 Opcode = X86ISD::PCMPISTRI;
12202 X86CC = X86::COND_S;
12204 case Intrinsic::x86_sse42_pcmpestris128:
12205 Opcode = X86ISD::PCMPESTRI;
12206 X86CC = X86::COND_S;
12208 case Intrinsic::x86_sse42_pcmpistriz128:
12209 Opcode = X86ISD::PCMPISTRI;
12210 X86CC = X86::COND_E;
12212 case Intrinsic::x86_sse42_pcmpestriz128:
12213 Opcode = X86ISD::PCMPESTRI;
12214 X86CC = X86::COND_E;
12217 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12218 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12219 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12220 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12221 DAG.getConstant(X86CC, MVT::i8),
12222 SDValue(PCMP.getNode(), 1));
12223 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12226 case Intrinsic::x86_sse42_pcmpistri128:
12227 case Intrinsic::x86_sse42_pcmpestri128: {
12229 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12230 Opcode = X86ISD::PCMPISTRI;
12232 Opcode = X86ISD::PCMPESTRI;
12234 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12235 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12236 return DAG.getNode(Opcode, dl, VTs, NewOps);
12238 case Intrinsic::x86_fma_vfmadd_ps:
12239 case Intrinsic::x86_fma_vfmadd_pd:
12240 case Intrinsic::x86_fma_vfmsub_ps:
12241 case Intrinsic::x86_fma_vfmsub_pd:
12242 case Intrinsic::x86_fma_vfnmadd_ps:
12243 case Intrinsic::x86_fma_vfnmadd_pd:
12244 case Intrinsic::x86_fma_vfnmsub_ps:
12245 case Intrinsic::x86_fma_vfnmsub_pd:
12246 case Intrinsic::x86_fma_vfmaddsub_ps:
12247 case Intrinsic::x86_fma_vfmaddsub_pd:
12248 case Intrinsic::x86_fma_vfmsubadd_ps:
12249 case Intrinsic::x86_fma_vfmsubadd_pd:
12250 case Intrinsic::x86_fma_vfmadd_ps_256:
12251 case Intrinsic::x86_fma_vfmadd_pd_256:
12252 case Intrinsic::x86_fma_vfmsub_ps_256:
12253 case Intrinsic::x86_fma_vfmsub_pd_256:
12254 case Intrinsic::x86_fma_vfnmadd_ps_256:
12255 case Intrinsic::x86_fma_vfnmadd_pd_256:
12256 case Intrinsic::x86_fma_vfnmsub_ps_256:
12257 case Intrinsic::x86_fma_vfnmsub_pd_256:
12258 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12259 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12260 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12261 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12262 case Intrinsic::x86_fma_vfmadd_ps_512:
12263 case Intrinsic::x86_fma_vfmadd_pd_512:
12264 case Intrinsic::x86_fma_vfmsub_ps_512:
12265 case Intrinsic::x86_fma_vfmsub_pd_512:
12266 case Intrinsic::x86_fma_vfnmadd_ps_512:
12267 case Intrinsic::x86_fma_vfnmadd_pd_512:
12268 case Intrinsic::x86_fma_vfnmsub_ps_512:
12269 case Intrinsic::x86_fma_vfnmsub_pd_512:
12270 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12271 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12272 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12273 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12276 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12277 case Intrinsic::x86_fma_vfmadd_ps:
12278 case Intrinsic::x86_fma_vfmadd_pd:
12279 case Intrinsic::x86_fma_vfmadd_ps_256:
12280 case Intrinsic::x86_fma_vfmadd_pd_256:
12281 case Intrinsic::x86_fma_vfmadd_ps_512:
12282 case Intrinsic::x86_fma_vfmadd_pd_512:
12283 Opc = X86ISD::FMADD;
12285 case Intrinsic::x86_fma_vfmsub_ps:
12286 case Intrinsic::x86_fma_vfmsub_pd:
12287 case Intrinsic::x86_fma_vfmsub_ps_256:
12288 case Intrinsic::x86_fma_vfmsub_pd_256:
12289 case Intrinsic::x86_fma_vfmsub_ps_512:
12290 case Intrinsic::x86_fma_vfmsub_pd_512:
12291 Opc = X86ISD::FMSUB;
12293 case Intrinsic::x86_fma_vfnmadd_ps:
12294 case Intrinsic::x86_fma_vfnmadd_pd:
12295 case Intrinsic::x86_fma_vfnmadd_ps_256:
12296 case Intrinsic::x86_fma_vfnmadd_pd_256:
12297 case Intrinsic::x86_fma_vfnmadd_ps_512:
12298 case Intrinsic::x86_fma_vfnmadd_pd_512:
12299 Opc = X86ISD::FNMADD;
12301 case Intrinsic::x86_fma_vfnmsub_ps:
12302 case Intrinsic::x86_fma_vfnmsub_pd:
12303 case Intrinsic::x86_fma_vfnmsub_ps_256:
12304 case Intrinsic::x86_fma_vfnmsub_pd_256:
12305 case Intrinsic::x86_fma_vfnmsub_ps_512:
12306 case Intrinsic::x86_fma_vfnmsub_pd_512:
12307 Opc = X86ISD::FNMSUB;
12309 case Intrinsic::x86_fma_vfmaddsub_ps:
12310 case Intrinsic::x86_fma_vfmaddsub_pd:
12311 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12312 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12313 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12314 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12315 Opc = X86ISD::FMADDSUB;
12317 case Intrinsic::x86_fma_vfmsubadd_ps:
12318 case Intrinsic::x86_fma_vfmsubadd_pd:
12319 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12320 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12321 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12322 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12323 Opc = X86ISD::FMSUBADD;
12327 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12328 Op.getOperand(2), Op.getOperand(3));
12333 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12334 SDValue Base, SDValue Index,
12335 SDValue ScaleOp, SDValue Chain,
12336 const X86Subtarget * Subtarget) {
12338 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12339 assert(C && "Invalid scale type");
12340 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12341 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12342 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12343 Index.getSimpleValueType().getVectorNumElements());
12344 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12345 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12346 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12347 SDValue Segment = DAG.getRegister(0, MVT::i32);
12348 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12349 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12350 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12351 return DAG.getMergeValues(RetOps, dl);
12354 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12355 SDValue Src, SDValue Mask, SDValue Base,
12356 SDValue Index, SDValue ScaleOp, SDValue Chain,
12357 const X86Subtarget * Subtarget) {
12359 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12360 assert(C && "Invalid scale type");
12361 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12362 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12363 Index.getSimpleValueType().getVectorNumElements());
12364 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12365 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12366 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12367 SDValue Segment = DAG.getRegister(0, MVT::i32);
12368 if (Src.getOpcode() == ISD::UNDEF)
12369 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12370 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12371 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12372 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12373 return DAG.getMergeValues(RetOps, dl);
12376 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12377 SDValue Src, SDValue Base, SDValue Index,
12378 SDValue ScaleOp, SDValue Chain) {
12380 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12381 assert(C && "Invalid scale type");
12382 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12383 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12384 SDValue Segment = DAG.getRegister(0, MVT::i32);
12385 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12386 Index.getSimpleValueType().getVectorNumElements());
12387 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12388 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12389 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12390 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12391 return SDValue(Res, 1);
12394 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12395 SDValue Src, SDValue Mask, SDValue Base,
12396 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12398 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12399 assert(C && "Invalid scale type");
12400 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12401 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12402 SDValue Segment = DAG.getRegister(0, MVT::i32);
12403 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12404 Index.getSimpleValueType().getVectorNumElements());
12405 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12406 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12407 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12408 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12409 return SDValue(Res, 1);
12412 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12413 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12414 // also used to custom lower READCYCLECOUNTER nodes.
12415 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12416 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12417 SmallVectorImpl<SDValue> &Results) {
12418 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12419 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12422 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12423 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12424 // and the EAX register is loaded with the low-order 32 bits.
12425 if (Subtarget->is64Bit()) {
12426 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12427 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12430 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12431 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12434 SDValue Chain = HI.getValue(1);
12436 if (Opcode == X86ISD::RDTSCP_DAG) {
12437 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12439 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12440 // the ECX register. Add 'ecx' explicitly to the chain.
12441 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12443 // Explicitly store the content of ECX at the location passed in input
12444 // to the 'rdtscp' intrinsic.
12445 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12446 MachinePointerInfo(), false, false, 0);
12449 if (Subtarget->is64Bit()) {
12450 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12451 // the EAX register is loaded with the low-order 32 bits.
12452 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12453 DAG.getConstant(32, MVT::i8));
12454 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12455 Results.push_back(Chain);
12459 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12460 SDValue Ops[] = { LO, HI };
12461 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12462 Results.push_back(Pair);
12463 Results.push_back(Chain);
12466 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12467 SelectionDAG &DAG) {
12468 SmallVector<SDValue, 2> Results;
12470 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12472 return DAG.getMergeValues(Results, DL);
12475 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12476 SelectionDAG &DAG) {
12478 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12480 default: return SDValue(); // Don't custom lower most intrinsics.
12482 // RDRAND/RDSEED intrinsics.
12483 case Intrinsic::x86_rdrand_16:
12484 case Intrinsic::x86_rdrand_32:
12485 case Intrinsic::x86_rdrand_64:
12486 case Intrinsic::x86_rdseed_16:
12487 case Intrinsic::x86_rdseed_32:
12488 case Intrinsic::x86_rdseed_64: {
12489 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12490 IntNo == Intrinsic::x86_rdseed_32 ||
12491 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12493 // Emit the node with the right value type.
12494 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12495 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12497 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12498 // Otherwise return the value from Rand, which is always 0, casted to i32.
12499 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12500 DAG.getConstant(1, Op->getValueType(1)),
12501 DAG.getConstant(X86::COND_B, MVT::i32),
12502 SDValue(Result.getNode(), 1) };
12503 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12504 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12507 // Return { result, isValid, chain }.
12508 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12509 SDValue(Result.getNode(), 2));
12511 //int_gather(index, base, scale);
12512 case Intrinsic::x86_avx512_gather_qpd_512:
12513 case Intrinsic::x86_avx512_gather_qps_512:
12514 case Intrinsic::x86_avx512_gather_dpd_512:
12515 case Intrinsic::x86_avx512_gather_qpi_512:
12516 case Intrinsic::x86_avx512_gather_qpq_512:
12517 case Intrinsic::x86_avx512_gather_dpq_512:
12518 case Intrinsic::x86_avx512_gather_dps_512:
12519 case Intrinsic::x86_avx512_gather_dpi_512: {
12522 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12523 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12524 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12525 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12526 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12527 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12528 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12529 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12530 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12532 SDValue Chain = Op.getOperand(0);
12533 SDValue Index = Op.getOperand(2);
12534 SDValue Base = Op.getOperand(3);
12535 SDValue Scale = Op.getOperand(4);
12536 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12538 //int_gather_mask(v1, mask, index, base, scale);
12539 case Intrinsic::x86_avx512_gather_qps_mask_512:
12540 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12541 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12542 case Intrinsic::x86_avx512_gather_dps_mask_512:
12543 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12544 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12545 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12546 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12549 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12550 case Intrinsic::x86_avx512_gather_qps_mask_512:
12551 Opc = X86::VGATHERQPSZrm; break;
12552 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12553 Opc = X86::VGATHERQPDZrm; break;
12554 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12555 Opc = X86::VGATHERDPDZrm; break;
12556 case Intrinsic::x86_avx512_gather_dps_mask_512:
12557 Opc = X86::VGATHERDPSZrm; break;
12558 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12559 Opc = X86::VPGATHERQDZrm; break;
12560 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12561 Opc = X86::VPGATHERQQZrm; break;
12562 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12563 Opc = X86::VPGATHERDDZrm; break;
12564 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12565 Opc = X86::VPGATHERDQZrm; break;
12567 SDValue Chain = Op.getOperand(0);
12568 SDValue Src = Op.getOperand(2);
12569 SDValue Mask = Op.getOperand(3);
12570 SDValue Index = Op.getOperand(4);
12571 SDValue Base = Op.getOperand(5);
12572 SDValue Scale = Op.getOperand(6);
12573 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12576 //int_scatter(base, index, v1, scale);
12577 case Intrinsic::x86_avx512_scatter_qpd_512:
12578 case Intrinsic::x86_avx512_scatter_qps_512:
12579 case Intrinsic::x86_avx512_scatter_dpd_512:
12580 case Intrinsic::x86_avx512_scatter_qpi_512:
12581 case Intrinsic::x86_avx512_scatter_qpq_512:
12582 case Intrinsic::x86_avx512_scatter_dpq_512:
12583 case Intrinsic::x86_avx512_scatter_dps_512:
12584 case Intrinsic::x86_avx512_scatter_dpi_512: {
12587 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12588 case Intrinsic::x86_avx512_scatter_qpd_512:
12589 Opc = X86::VSCATTERQPDZmr; break;
12590 case Intrinsic::x86_avx512_scatter_qps_512:
12591 Opc = X86::VSCATTERQPSZmr; break;
12592 case Intrinsic::x86_avx512_scatter_dpd_512:
12593 Opc = X86::VSCATTERDPDZmr; break;
12594 case Intrinsic::x86_avx512_scatter_dps_512:
12595 Opc = X86::VSCATTERDPSZmr; break;
12596 case Intrinsic::x86_avx512_scatter_qpi_512:
12597 Opc = X86::VPSCATTERQDZmr; break;
12598 case Intrinsic::x86_avx512_scatter_qpq_512:
12599 Opc = X86::VPSCATTERQQZmr; break;
12600 case Intrinsic::x86_avx512_scatter_dpq_512:
12601 Opc = X86::VPSCATTERDQZmr; break;
12602 case Intrinsic::x86_avx512_scatter_dpi_512:
12603 Opc = X86::VPSCATTERDDZmr; break;
12605 SDValue Chain = Op.getOperand(0);
12606 SDValue Base = Op.getOperand(2);
12607 SDValue Index = Op.getOperand(3);
12608 SDValue Src = Op.getOperand(4);
12609 SDValue Scale = Op.getOperand(5);
12610 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12612 //int_scatter_mask(base, mask, index, v1, scale);
12613 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12614 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12615 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12616 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12617 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12618 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12619 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12620 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12623 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12624 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12625 Opc = X86::VSCATTERQPDZmr; break;
12626 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12627 Opc = X86::VSCATTERQPSZmr; break;
12628 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12629 Opc = X86::VSCATTERDPDZmr; break;
12630 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12631 Opc = X86::VSCATTERDPSZmr; break;
12632 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12633 Opc = X86::VPSCATTERQDZmr; break;
12634 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12635 Opc = X86::VPSCATTERQQZmr; break;
12636 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12637 Opc = X86::VPSCATTERDQZmr; break;
12638 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12639 Opc = X86::VPSCATTERDDZmr; break;
12641 SDValue Chain = Op.getOperand(0);
12642 SDValue Base = Op.getOperand(2);
12643 SDValue Mask = Op.getOperand(3);
12644 SDValue Index = Op.getOperand(4);
12645 SDValue Src = Op.getOperand(5);
12646 SDValue Scale = Op.getOperand(6);
12647 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12649 // Read Time Stamp Counter (RDTSC).
12650 case Intrinsic::x86_rdtsc:
12651 // Read Time Stamp Counter and Processor ID (RDTSCP).
12652 case Intrinsic::x86_rdtscp: {
12655 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12656 case Intrinsic::x86_rdtsc:
12657 Opc = X86ISD::RDTSC_DAG; break;
12658 case Intrinsic::x86_rdtscp:
12659 Opc = X86ISD::RDTSCP_DAG; break;
12661 SmallVector<SDValue, 2> Results;
12662 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12663 return DAG.getMergeValues(Results, dl);
12665 // XTEST intrinsics.
12666 case Intrinsic::x86_xtest: {
12667 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12668 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12669 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12670 DAG.getConstant(X86::COND_NE, MVT::i8),
12672 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12673 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12674 Ret, SDValue(InTrans.getNode(), 1));
12679 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12680 SelectionDAG &DAG) const {
12681 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12682 MFI->setReturnAddressIsTaken(true);
12684 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12687 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12689 EVT PtrVT = getPointerTy();
12692 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12693 const X86RegisterInfo *RegInfo =
12694 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12695 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12696 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12697 DAG.getNode(ISD::ADD, dl, PtrVT,
12698 FrameAddr, Offset),
12699 MachinePointerInfo(), false, false, false, 0);
12702 // Just load the return address.
12703 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12704 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12705 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12708 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12709 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12710 MFI->setFrameAddressIsTaken(true);
12712 EVT VT = Op.getValueType();
12713 SDLoc dl(Op); // FIXME probably not meaningful
12714 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12715 const X86RegisterInfo *RegInfo =
12716 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12717 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12718 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12719 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12720 "Invalid Frame Register!");
12721 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12723 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12724 MachinePointerInfo(),
12725 false, false, false, 0);
12729 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12730 SelectionDAG &DAG) const {
12731 const X86RegisterInfo *RegInfo =
12732 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12733 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12736 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12737 SDValue Chain = Op.getOperand(0);
12738 SDValue Offset = Op.getOperand(1);
12739 SDValue Handler = Op.getOperand(2);
12742 EVT PtrVT = getPointerTy();
12743 const X86RegisterInfo *RegInfo =
12744 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12745 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12746 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12747 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12748 "Invalid Frame Register!");
12749 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12750 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12752 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12753 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12754 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12755 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12757 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12759 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12760 DAG.getRegister(StoreAddrReg, PtrVT));
12763 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12764 SelectionDAG &DAG) const {
12766 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12767 DAG.getVTList(MVT::i32, MVT::Other),
12768 Op.getOperand(0), Op.getOperand(1));
12771 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12772 SelectionDAG &DAG) const {
12774 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12775 Op.getOperand(0), Op.getOperand(1));
12778 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12779 return Op.getOperand(0);
12782 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12783 SelectionDAG &DAG) const {
12784 SDValue Root = Op.getOperand(0);
12785 SDValue Trmp = Op.getOperand(1); // trampoline
12786 SDValue FPtr = Op.getOperand(2); // nested function
12787 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12790 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12791 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12793 if (Subtarget->is64Bit()) {
12794 SDValue OutChains[6];
12796 // Large code-model.
12797 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12798 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12800 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12801 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12803 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12805 // Load the pointer to the nested function into R11.
12806 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12807 SDValue Addr = Trmp;
12808 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12809 Addr, MachinePointerInfo(TrmpAddr),
12812 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12813 DAG.getConstant(2, MVT::i64));
12814 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12815 MachinePointerInfo(TrmpAddr, 2),
12818 // Load the 'nest' parameter value into R10.
12819 // R10 is specified in X86CallingConv.td
12820 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12821 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12822 DAG.getConstant(10, MVT::i64));
12823 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12824 Addr, MachinePointerInfo(TrmpAddr, 10),
12827 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12828 DAG.getConstant(12, MVT::i64));
12829 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12830 MachinePointerInfo(TrmpAddr, 12),
12833 // Jump to the nested function.
12834 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12835 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12836 DAG.getConstant(20, MVT::i64));
12837 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12838 Addr, MachinePointerInfo(TrmpAddr, 20),
12841 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12842 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12843 DAG.getConstant(22, MVT::i64));
12844 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12845 MachinePointerInfo(TrmpAddr, 22),
12848 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12850 const Function *Func =
12851 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12852 CallingConv::ID CC = Func->getCallingConv();
12857 llvm_unreachable("Unsupported calling convention");
12858 case CallingConv::C:
12859 case CallingConv::X86_StdCall: {
12860 // Pass 'nest' parameter in ECX.
12861 // Must be kept in sync with X86CallingConv.td
12862 NestReg = X86::ECX;
12864 // Check that ECX wasn't needed by an 'inreg' parameter.
12865 FunctionType *FTy = Func->getFunctionType();
12866 const AttributeSet &Attrs = Func->getAttributes();
12868 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12869 unsigned InRegCount = 0;
12872 for (FunctionType::param_iterator I = FTy->param_begin(),
12873 E = FTy->param_end(); I != E; ++I, ++Idx)
12874 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12875 // FIXME: should only count parameters that are lowered to integers.
12876 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12878 if (InRegCount > 2) {
12879 report_fatal_error("Nest register in use - reduce number of inreg"
12885 case CallingConv::X86_FastCall:
12886 case CallingConv::X86_ThisCall:
12887 case CallingConv::Fast:
12888 // Pass 'nest' parameter in EAX.
12889 // Must be kept in sync with X86CallingConv.td
12890 NestReg = X86::EAX;
12894 SDValue OutChains[4];
12895 SDValue Addr, Disp;
12897 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12898 DAG.getConstant(10, MVT::i32));
12899 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12901 // This is storing the opcode for MOV32ri.
12902 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12903 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12904 OutChains[0] = DAG.getStore(Root, dl,
12905 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12906 Trmp, MachinePointerInfo(TrmpAddr),
12909 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12910 DAG.getConstant(1, MVT::i32));
12911 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12912 MachinePointerInfo(TrmpAddr, 1),
12915 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12916 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12917 DAG.getConstant(5, MVT::i32));
12918 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12919 MachinePointerInfo(TrmpAddr, 5),
12922 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12923 DAG.getConstant(6, MVT::i32));
12924 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12925 MachinePointerInfo(TrmpAddr, 6),
12928 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12932 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12933 SelectionDAG &DAG) const {
12935 The rounding mode is in bits 11:10 of FPSR, and has the following
12937 00 Round to nearest
12942 FLT_ROUNDS, on the other hand, expects the following:
12949 To perform the conversion, we do:
12950 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12953 MachineFunction &MF = DAG.getMachineFunction();
12954 const TargetMachine &TM = MF.getTarget();
12955 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12956 unsigned StackAlignment = TFI.getStackAlignment();
12957 MVT VT = Op.getSimpleValueType();
12960 // Save FP Control Word to stack slot
12961 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12962 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12964 MachineMemOperand *MMO =
12965 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12966 MachineMemOperand::MOStore, 2, 2);
12968 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12969 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12970 DAG.getVTList(MVT::Other),
12971 Ops, MVT::i16, MMO);
12973 // Load FP Control Word from stack slot
12974 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12975 MachinePointerInfo(), false, false, false, 0);
12977 // Transform as necessary
12979 DAG.getNode(ISD::SRL, DL, MVT::i16,
12980 DAG.getNode(ISD::AND, DL, MVT::i16,
12981 CWD, DAG.getConstant(0x800, MVT::i16)),
12982 DAG.getConstant(11, MVT::i8));
12984 DAG.getNode(ISD::SRL, DL, MVT::i16,
12985 DAG.getNode(ISD::AND, DL, MVT::i16,
12986 CWD, DAG.getConstant(0x400, MVT::i16)),
12987 DAG.getConstant(9, MVT::i8));
12990 DAG.getNode(ISD::AND, DL, MVT::i16,
12991 DAG.getNode(ISD::ADD, DL, MVT::i16,
12992 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12993 DAG.getConstant(1, MVT::i16)),
12994 DAG.getConstant(3, MVT::i16));
12996 return DAG.getNode((VT.getSizeInBits() < 16 ?
12997 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13000 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13001 MVT VT = Op.getSimpleValueType();
13003 unsigned NumBits = VT.getSizeInBits();
13006 Op = Op.getOperand(0);
13007 if (VT == MVT::i8) {
13008 // Zero extend to i32 since there is not an i8 bsr.
13010 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13013 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13014 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13015 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13017 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13020 DAG.getConstant(NumBits+NumBits-1, OpVT),
13021 DAG.getConstant(X86::COND_E, MVT::i8),
13024 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13026 // Finally xor with NumBits-1.
13027 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13030 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13034 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13035 MVT VT = Op.getSimpleValueType();
13037 unsigned NumBits = VT.getSizeInBits();
13040 Op = Op.getOperand(0);
13041 if (VT == MVT::i8) {
13042 // Zero extend to i32 since there is not an i8 bsr.
13044 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13047 // Issue a bsr (scan bits in reverse).
13048 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13049 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13051 // And xor with NumBits-1.
13052 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13055 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13059 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13060 MVT VT = Op.getSimpleValueType();
13061 unsigned NumBits = VT.getSizeInBits();
13063 Op = Op.getOperand(0);
13065 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13066 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13067 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13069 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13072 DAG.getConstant(NumBits, VT),
13073 DAG.getConstant(X86::COND_E, MVT::i8),
13076 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13079 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13080 // ones, and then concatenate the result back.
13081 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13082 MVT VT = Op.getSimpleValueType();
13084 assert(VT.is256BitVector() && VT.isInteger() &&
13085 "Unsupported value type for operation");
13087 unsigned NumElems = VT.getVectorNumElements();
13090 // Extract the LHS vectors
13091 SDValue LHS = Op.getOperand(0);
13092 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13093 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13095 // Extract the RHS vectors
13096 SDValue RHS = Op.getOperand(1);
13097 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13098 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13100 MVT EltVT = VT.getVectorElementType();
13101 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13103 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13104 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13105 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13108 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13109 assert(Op.getSimpleValueType().is256BitVector() &&
13110 Op.getSimpleValueType().isInteger() &&
13111 "Only handle AVX 256-bit vector integer operation");
13112 return Lower256IntArith(Op, DAG);
13115 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13116 assert(Op.getSimpleValueType().is256BitVector() &&
13117 Op.getSimpleValueType().isInteger() &&
13118 "Only handle AVX 256-bit vector integer operation");
13119 return Lower256IntArith(Op, DAG);
13122 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13123 SelectionDAG &DAG) {
13125 MVT VT = Op.getSimpleValueType();
13127 // Decompose 256-bit ops into smaller 128-bit ops.
13128 if (VT.is256BitVector() && !Subtarget->hasInt256())
13129 return Lower256IntArith(Op, DAG);
13131 SDValue A = Op.getOperand(0);
13132 SDValue B = Op.getOperand(1);
13134 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13135 if (VT == MVT::v4i32) {
13136 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13137 "Should not custom lower when pmuldq is available!");
13139 // Extract the odd parts.
13140 static const int UnpackMask[] = { 1, -1, 3, -1 };
13141 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13142 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13144 // Multiply the even parts.
13145 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13146 // Now multiply odd parts.
13147 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13149 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13150 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13152 // Merge the two vectors back together with a shuffle. This expands into 2
13154 static const int ShufMask[] = { 0, 4, 2, 6 };
13155 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13158 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13159 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13161 // Ahi = psrlqi(a, 32);
13162 // Bhi = psrlqi(b, 32);
13164 // AloBlo = pmuludq(a, b);
13165 // AloBhi = pmuludq(a, Bhi);
13166 // AhiBlo = pmuludq(Ahi, b);
13168 // AloBhi = psllqi(AloBhi, 32);
13169 // AhiBlo = psllqi(AhiBlo, 32);
13170 // return AloBlo + AloBhi + AhiBlo;
13172 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13173 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13175 // Bit cast to 32-bit vectors for MULUDQ
13176 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13177 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13178 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13179 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13180 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13181 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13183 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13184 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13185 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13187 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13188 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13190 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13191 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13194 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13195 SelectionDAG &DAG) {
13196 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13197 EVT VT = Op0.getValueType();
13200 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13201 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13203 // Get the high parts.
13204 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13205 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13206 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13208 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13210 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13211 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13213 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13214 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13215 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13216 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13217 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13219 // Shuffle it back into the right order.
13220 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13221 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13222 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13223 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13225 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13226 // unsigned multiply.
13227 if (IsSigned && !Subtarget->hasSSE41()) {
13229 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13230 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13231 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13232 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13233 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13235 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13236 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13239 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13242 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13243 const X86Subtarget *Subtarget) {
13244 MVT VT = Op.getSimpleValueType();
13246 SDValue R = Op.getOperand(0);
13247 SDValue Amt = Op.getOperand(1);
13249 // Optimize shl/srl/sra with constant shift amount.
13250 if (isSplatVector(Amt.getNode())) {
13251 SDValue SclrAmt = Amt->getOperand(0);
13252 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13253 uint64_t ShiftAmt = C->getZExtValue();
13255 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13256 (Subtarget->hasInt256() &&
13257 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13258 (Subtarget->hasAVX512() &&
13259 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13260 if (Op.getOpcode() == ISD::SHL)
13261 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13263 if (Op.getOpcode() == ISD::SRL)
13264 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13266 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13267 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13271 if (VT == MVT::v16i8) {
13272 if (Op.getOpcode() == ISD::SHL) {
13273 // Make a large shift.
13274 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13275 MVT::v8i16, R, ShiftAmt,
13277 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13278 // Zero out the rightmost bits.
13279 SmallVector<SDValue, 16> V(16,
13280 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13282 return DAG.getNode(ISD::AND, dl, VT, SHL,
13283 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13285 if (Op.getOpcode() == ISD::SRL) {
13286 // Make a large shift.
13287 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13288 MVT::v8i16, R, ShiftAmt,
13290 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13291 // Zero out the leftmost bits.
13292 SmallVector<SDValue, 16> V(16,
13293 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13295 return DAG.getNode(ISD::AND, dl, VT, SRL,
13296 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13298 if (Op.getOpcode() == ISD::SRA) {
13299 if (ShiftAmt == 7) {
13300 // R s>> 7 === R s< 0
13301 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13302 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13305 // R s>> a === ((R u>> a) ^ m) - m
13306 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13307 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13309 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13310 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13311 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13314 llvm_unreachable("Unknown shift opcode.");
13317 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13318 if (Op.getOpcode() == ISD::SHL) {
13319 // Make a large shift.
13320 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13321 MVT::v16i16, R, ShiftAmt,
13323 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13324 // Zero out the rightmost bits.
13325 SmallVector<SDValue, 32> V(32,
13326 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13328 return DAG.getNode(ISD::AND, dl, VT, SHL,
13329 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13331 if (Op.getOpcode() == ISD::SRL) {
13332 // Make a large shift.
13333 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13334 MVT::v16i16, R, ShiftAmt,
13336 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13337 // Zero out the leftmost bits.
13338 SmallVector<SDValue, 32> V(32,
13339 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13341 return DAG.getNode(ISD::AND, dl, VT, SRL,
13342 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13344 if (Op.getOpcode() == ISD::SRA) {
13345 if (ShiftAmt == 7) {
13346 // R s>> 7 === R s< 0
13347 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13348 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13351 // R s>> a === ((R u>> a) ^ m) - m
13352 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13353 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13355 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13356 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13357 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13360 llvm_unreachable("Unknown shift opcode.");
13365 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13366 if (!Subtarget->is64Bit() &&
13367 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13368 Amt.getOpcode() == ISD::BITCAST &&
13369 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13370 Amt = Amt.getOperand(0);
13371 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13372 VT.getVectorNumElements();
13373 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13374 uint64_t ShiftAmt = 0;
13375 for (unsigned i = 0; i != Ratio; ++i) {
13376 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13380 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13382 // Check remaining shift amounts.
13383 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13384 uint64_t ShAmt = 0;
13385 for (unsigned j = 0; j != Ratio; ++j) {
13386 ConstantSDNode *C =
13387 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13391 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13393 if (ShAmt != ShiftAmt)
13396 switch (Op.getOpcode()) {
13398 llvm_unreachable("Unknown shift opcode!");
13400 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13403 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13406 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13414 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13415 const X86Subtarget* Subtarget) {
13416 MVT VT = Op.getSimpleValueType();
13418 SDValue R = Op.getOperand(0);
13419 SDValue Amt = Op.getOperand(1);
13421 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13422 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13423 (Subtarget->hasInt256() &&
13424 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13425 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13426 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13428 EVT EltVT = VT.getVectorElementType();
13430 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13431 unsigned NumElts = VT.getVectorNumElements();
13433 for (i = 0; i != NumElts; ++i) {
13434 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13438 for (j = i; j != NumElts; ++j) {
13439 SDValue Arg = Amt.getOperand(j);
13440 if (Arg.getOpcode() == ISD::UNDEF) continue;
13441 if (Arg != Amt.getOperand(i))
13444 if (i != NumElts && j == NumElts)
13445 BaseShAmt = Amt.getOperand(i);
13447 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13448 Amt = Amt.getOperand(0);
13449 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13450 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13451 SDValue InVec = Amt.getOperand(0);
13452 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13453 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13455 for (; i != NumElts; ++i) {
13456 SDValue Arg = InVec.getOperand(i);
13457 if (Arg.getOpcode() == ISD::UNDEF) continue;
13461 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13462 if (ConstantSDNode *C =
13463 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13464 unsigned SplatIdx =
13465 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13466 if (C->getZExtValue() == SplatIdx)
13467 BaseShAmt = InVec.getOperand(1);
13470 if (!BaseShAmt.getNode())
13471 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13472 DAG.getIntPtrConstant(0));
13476 if (BaseShAmt.getNode()) {
13477 if (EltVT.bitsGT(MVT::i32))
13478 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13479 else if (EltVT.bitsLT(MVT::i32))
13480 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13482 switch (Op.getOpcode()) {
13484 llvm_unreachable("Unknown shift opcode!");
13486 switch (VT.SimpleTy) {
13487 default: return SDValue();
13496 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13499 switch (VT.SimpleTy) {
13500 default: return SDValue();
13507 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13510 switch (VT.SimpleTy) {
13511 default: return SDValue();
13520 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13526 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13527 if (!Subtarget->is64Bit() &&
13528 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13529 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13530 Amt.getOpcode() == ISD::BITCAST &&
13531 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13532 Amt = Amt.getOperand(0);
13533 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13534 VT.getVectorNumElements();
13535 std::vector<SDValue> Vals(Ratio);
13536 for (unsigned i = 0; i != Ratio; ++i)
13537 Vals[i] = Amt.getOperand(i);
13538 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13539 for (unsigned j = 0; j != Ratio; ++j)
13540 if (Vals[j] != Amt.getOperand(i + j))
13543 switch (Op.getOpcode()) {
13545 llvm_unreachable("Unknown shift opcode!");
13547 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13549 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13551 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13558 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13559 SelectionDAG &DAG) {
13561 MVT VT = Op.getSimpleValueType();
13563 SDValue R = Op.getOperand(0);
13564 SDValue Amt = Op.getOperand(1);
13567 if (!Subtarget->hasSSE2())
13570 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13574 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13578 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13580 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13581 if (Subtarget->hasInt256()) {
13582 if (Op.getOpcode() == ISD::SRL &&
13583 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13584 VT == MVT::v4i64 || VT == MVT::v8i32))
13586 if (Op.getOpcode() == ISD::SHL &&
13587 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13588 VT == MVT::v4i64 || VT == MVT::v8i32))
13590 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13594 // If possible, lower this packed shift into a vector multiply instead of
13595 // expanding it into a sequence of scalar shifts.
13596 // Do this only if the vector shift count is a constant build_vector.
13597 if (Op.getOpcode() == ISD::SHL &&
13598 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13599 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13600 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13601 SmallVector<SDValue, 8> Elts;
13602 EVT SVT = VT.getScalarType();
13603 unsigned SVTBits = SVT.getSizeInBits();
13604 const APInt &One = APInt(SVTBits, 1);
13605 unsigned NumElems = VT.getVectorNumElements();
13607 for (unsigned i=0; i !=NumElems; ++i) {
13608 SDValue Op = Amt->getOperand(i);
13609 if (Op->getOpcode() == ISD::UNDEF) {
13610 Elts.push_back(Op);
13614 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13615 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13616 uint64_t ShAmt = C.getZExtValue();
13617 if (ShAmt >= SVTBits) {
13618 Elts.push_back(DAG.getUNDEF(SVT));
13621 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13623 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13624 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13627 // Lower SHL with variable shift amount.
13628 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13629 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13631 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13632 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13633 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13634 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13637 // If possible, lower this shift as a sequence of two shifts by
13638 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13640 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13642 // Could be rewritten as:
13643 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13645 // The advantage is that the two shifts from the example would be
13646 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13647 // the vector shift into four scalar shifts plus four pairs of vector
13649 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13650 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13651 unsigned TargetOpcode = X86ISD::MOVSS;
13652 bool CanBeSimplified;
13653 // The splat value for the first packed shift (the 'X' from the example).
13654 SDValue Amt1 = Amt->getOperand(0);
13655 // The splat value for the second packed shift (the 'Y' from the example).
13656 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13657 Amt->getOperand(2);
13659 // See if it is possible to replace this node with a sequence of
13660 // two shifts followed by a MOVSS/MOVSD
13661 if (VT == MVT::v4i32) {
13662 // Check if it is legal to use a MOVSS.
13663 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13664 Amt2 == Amt->getOperand(3);
13665 if (!CanBeSimplified) {
13666 // Otherwise, check if we can still simplify this node using a MOVSD.
13667 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13668 Amt->getOperand(2) == Amt->getOperand(3);
13669 TargetOpcode = X86ISD::MOVSD;
13670 Amt2 = Amt->getOperand(2);
13673 // Do similar checks for the case where the machine value type
13675 CanBeSimplified = Amt1 == Amt->getOperand(1);
13676 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13677 CanBeSimplified = Amt2 == Amt->getOperand(i);
13679 if (!CanBeSimplified) {
13680 TargetOpcode = X86ISD::MOVSD;
13681 CanBeSimplified = true;
13682 Amt2 = Amt->getOperand(4);
13683 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13684 CanBeSimplified = Amt1 == Amt->getOperand(i);
13685 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13686 CanBeSimplified = Amt2 == Amt->getOperand(j);
13690 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13691 isa<ConstantSDNode>(Amt2)) {
13692 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13693 EVT CastVT = MVT::v4i32;
13695 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13696 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13698 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13699 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13700 if (TargetOpcode == X86ISD::MOVSD)
13701 CastVT = MVT::v2i64;
13702 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13703 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13704 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13706 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13710 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13711 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13714 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13715 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13717 // Turn 'a' into a mask suitable for VSELECT
13718 SDValue VSelM = DAG.getConstant(0x80, VT);
13719 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13720 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13722 SDValue CM1 = DAG.getConstant(0x0f, VT);
13723 SDValue CM2 = DAG.getConstant(0x3f, VT);
13725 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13726 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13727 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13728 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13729 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13732 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13733 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13734 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13736 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13737 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13738 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13739 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13740 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13743 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13744 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13745 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13747 // return VSELECT(r, r+r, a);
13748 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13749 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13753 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13754 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13755 // solution better.
13756 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13757 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13759 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13760 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13761 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13762 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13763 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13766 // Decompose 256-bit shifts into smaller 128-bit shifts.
13767 if (VT.is256BitVector()) {
13768 unsigned NumElems = VT.getVectorNumElements();
13769 MVT EltVT = VT.getVectorElementType();
13770 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13772 // Extract the two vectors
13773 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13774 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13776 // Recreate the shift amount vectors
13777 SDValue Amt1, Amt2;
13778 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13779 // Constant shift amount
13780 SmallVector<SDValue, 4> Amt1Csts;
13781 SmallVector<SDValue, 4> Amt2Csts;
13782 for (unsigned i = 0; i != NumElems/2; ++i)
13783 Amt1Csts.push_back(Amt->getOperand(i));
13784 for (unsigned i = NumElems/2; i != NumElems; ++i)
13785 Amt2Csts.push_back(Amt->getOperand(i));
13787 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13788 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13790 // Variable shift amount
13791 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13792 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13795 // Issue new vector shifts for the smaller types
13796 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13797 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13799 // Concatenate the result back
13800 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13806 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13807 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13808 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13809 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13810 // has only one use.
13811 SDNode *N = Op.getNode();
13812 SDValue LHS = N->getOperand(0);
13813 SDValue RHS = N->getOperand(1);
13814 unsigned BaseOp = 0;
13817 switch (Op.getOpcode()) {
13818 default: llvm_unreachable("Unknown ovf instruction!");
13820 // A subtract of one will be selected as a INC. Note that INC doesn't
13821 // set CF, so we can't do this for UADDO.
13822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13824 BaseOp = X86ISD::INC;
13825 Cond = X86::COND_O;
13828 BaseOp = X86ISD::ADD;
13829 Cond = X86::COND_O;
13832 BaseOp = X86ISD::ADD;
13833 Cond = X86::COND_B;
13836 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13837 // set CF, so we can't do this for USUBO.
13838 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13840 BaseOp = X86ISD::DEC;
13841 Cond = X86::COND_O;
13844 BaseOp = X86ISD::SUB;
13845 Cond = X86::COND_O;
13848 BaseOp = X86ISD::SUB;
13849 Cond = X86::COND_B;
13852 BaseOp = X86ISD::SMUL;
13853 Cond = X86::COND_O;
13855 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13856 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13858 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13861 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13862 DAG.getConstant(X86::COND_O, MVT::i32),
13863 SDValue(Sum.getNode(), 2));
13865 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13869 // Also sets EFLAGS.
13870 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13871 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13874 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13875 DAG.getConstant(Cond, MVT::i32),
13876 SDValue(Sum.getNode(), 1));
13878 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13881 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13882 SelectionDAG &DAG) const {
13884 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13885 MVT VT = Op.getSimpleValueType();
13887 if (!Subtarget->hasSSE2() || !VT.isVector())
13890 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13891 ExtraVT.getScalarType().getSizeInBits();
13893 switch (VT.SimpleTy) {
13894 default: return SDValue();
13897 if (!Subtarget->hasFp256())
13899 if (!Subtarget->hasInt256()) {
13900 // needs to be split
13901 unsigned NumElems = VT.getVectorNumElements();
13903 // Extract the LHS vectors
13904 SDValue LHS = Op.getOperand(0);
13905 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13906 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13908 MVT EltVT = VT.getVectorElementType();
13909 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13911 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13912 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13913 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13915 SDValue Extra = DAG.getValueType(ExtraVT);
13917 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13918 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13920 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13925 SDValue Op0 = Op.getOperand(0);
13926 SDValue Op00 = Op0.getOperand(0);
13928 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13929 if (Op0.getOpcode() == ISD::BITCAST &&
13930 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13931 // (sext (vzext x)) -> (vsext x)
13932 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13933 if (Tmp1.getNode()) {
13934 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13935 // This folding is only valid when the in-reg type is a vector of i8,
13937 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13938 ExtraEltVT == MVT::i32) {
13939 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13940 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13941 "This optimization is invalid without a VZEXT.");
13942 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13948 // If the above didn't work, then just use Shift-Left + Shift-Right.
13949 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13951 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13957 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13958 SelectionDAG &DAG) {
13960 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13961 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13962 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13963 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13965 // The only fence that needs an instruction is a sequentially-consistent
13966 // cross-thread fence.
13967 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13968 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13969 // no-sse2). There isn't any reason to disable it if the target processor
13971 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13972 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13974 SDValue Chain = Op.getOperand(0);
13975 SDValue Zero = DAG.getConstant(0, MVT::i32);
13977 DAG.getRegister(X86::ESP, MVT::i32), // Base
13978 DAG.getTargetConstant(1, MVT::i8), // Scale
13979 DAG.getRegister(0, MVT::i32), // Index
13980 DAG.getTargetConstant(0, MVT::i32), // Disp
13981 DAG.getRegister(0, MVT::i32), // Segment.
13985 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13986 return SDValue(Res, 0);
13989 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13990 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13993 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13994 SelectionDAG &DAG) {
13995 MVT T = Op.getSimpleValueType();
13999 switch(T.SimpleTy) {
14000 default: llvm_unreachable("Invalid value type!");
14001 case MVT::i8: Reg = X86::AL; size = 1; break;
14002 case MVT::i16: Reg = X86::AX; size = 2; break;
14003 case MVT::i32: Reg = X86::EAX; size = 4; break;
14005 assert(Subtarget->is64Bit() && "Node not type legal!");
14006 Reg = X86::RAX; size = 8;
14009 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14010 Op.getOperand(2), SDValue());
14011 SDValue Ops[] = { cpIn.getValue(0),
14014 DAG.getTargetConstant(size, MVT::i8),
14015 cpIn.getValue(1) };
14016 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14017 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14018 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14021 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14025 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14026 SelectionDAG &DAG) {
14027 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14028 MVT DstVT = Op.getSimpleValueType();
14029 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14030 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14031 assert((DstVT == MVT::i64 ||
14032 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14033 "Unexpected custom BITCAST");
14034 // i64 <=> MMX conversions are Legal.
14035 if (SrcVT==MVT::i64 && DstVT.isVector())
14037 if (DstVT==MVT::i64 && SrcVT.isVector())
14039 // MMX <=> MMX conversions are Legal.
14040 if (SrcVT.isVector() && DstVT.isVector())
14042 // All other conversions need to be expanded.
14046 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14047 SDNode *Node = Op.getNode();
14049 EVT T = Node->getValueType(0);
14050 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14051 DAG.getConstant(0, T), Node->getOperand(2));
14052 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14053 cast<AtomicSDNode>(Node)->getMemoryVT(),
14054 Node->getOperand(0),
14055 Node->getOperand(1), negOp,
14056 cast<AtomicSDNode>(Node)->getMemOperand(),
14057 cast<AtomicSDNode>(Node)->getOrdering(),
14058 cast<AtomicSDNode>(Node)->getSynchScope());
14061 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14062 SDNode *Node = Op.getNode();
14064 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14066 // Convert seq_cst store -> xchg
14067 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14068 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14069 // (The only way to get a 16-byte store is cmpxchg16b)
14070 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14071 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14072 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14073 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14074 cast<AtomicSDNode>(Node)->getMemoryVT(),
14075 Node->getOperand(0),
14076 Node->getOperand(1), Node->getOperand(2),
14077 cast<AtomicSDNode>(Node)->getMemOperand(),
14078 cast<AtomicSDNode>(Node)->getOrdering(),
14079 cast<AtomicSDNode>(Node)->getSynchScope());
14080 return Swap.getValue(1);
14082 // Other atomic stores have a simple pattern.
14086 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14087 EVT VT = Op.getNode()->getSimpleValueType(0);
14089 // Let legalize expand this if it isn't a legal type yet.
14090 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14093 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14096 bool ExtraOp = false;
14097 switch (Op.getOpcode()) {
14098 default: llvm_unreachable("Invalid code");
14099 case ISD::ADDC: Opc = X86ISD::ADD; break;
14100 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14101 case ISD::SUBC: Opc = X86ISD::SUB; break;
14102 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14106 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14108 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14109 Op.getOperand(1), Op.getOperand(2));
14112 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14113 SelectionDAG &DAG) {
14114 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14116 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14117 // which returns the values as { float, float } (in XMM0) or
14118 // { double, double } (which is returned in XMM0, XMM1).
14120 SDValue Arg = Op.getOperand(0);
14121 EVT ArgVT = Arg.getValueType();
14122 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14124 TargetLowering::ArgListTy Args;
14125 TargetLowering::ArgListEntry Entry;
14129 Entry.isSExt = false;
14130 Entry.isZExt = false;
14131 Args.push_back(Entry);
14133 bool isF64 = ArgVT == MVT::f64;
14134 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14135 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14136 // the results are returned via SRet in memory.
14137 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14138 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14139 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14141 Type *RetTy = isF64
14142 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14143 : (Type*)VectorType::get(ArgTy, 4);
14145 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14146 false, false, false, false, 0,
14147 CallingConv::C, /*isTaillCall=*/false,
14148 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14149 Callee, Args, DAG, dl);
14150 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14153 // Returned in xmm0 and xmm1.
14154 return CallResult.first;
14156 // Returned in bits 0:31 and 32:64 xmm0.
14157 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14158 CallResult.first, DAG.getIntPtrConstant(0));
14159 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14160 CallResult.first, DAG.getIntPtrConstant(1));
14161 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14162 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14165 /// LowerOperation - Provide custom lowering hooks for some operations.
14167 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14168 switch (Op.getOpcode()) {
14169 default: llvm_unreachable("Should not custom lower this!");
14170 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14171 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14172 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14173 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14174 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14175 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14176 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14177 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14178 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14179 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14180 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14181 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14182 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14183 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14184 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14185 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14186 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14187 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14188 case ISD::SHL_PARTS:
14189 case ISD::SRA_PARTS:
14190 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14191 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14192 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14193 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14194 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14195 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14196 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14197 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14198 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14199 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14200 case ISD::FABS: return LowerFABS(Op, DAG);
14201 case ISD::FNEG: return LowerFNEG(Op, DAG);
14202 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14203 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14204 case ISD::SETCC: return LowerSETCC(Op, DAG);
14205 case ISD::SELECT: return LowerSELECT(Op, DAG);
14206 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14207 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14208 case ISD::VASTART: return LowerVASTART(Op, DAG);
14209 case ISD::VAARG: return LowerVAARG(Op, DAG);
14210 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14211 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14212 case ISD::INTRINSIC_VOID:
14213 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14214 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14215 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14216 case ISD::FRAME_TO_ARGS_OFFSET:
14217 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14218 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14219 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14220 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14221 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14222 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14223 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14224 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14225 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14226 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14227 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14228 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14229 case ISD::UMUL_LOHI:
14230 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14233 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14239 case ISD::UMULO: return LowerXALUO(Op, DAG);
14240 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14241 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14245 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14246 case ISD::ADD: return LowerADD(Op, DAG);
14247 case ISD::SUB: return LowerSUB(Op, DAG);
14248 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14252 static void ReplaceATOMIC_LOAD(SDNode *Node,
14253 SmallVectorImpl<SDValue> &Results,
14254 SelectionDAG &DAG) {
14256 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14258 // Convert wide load -> cmpxchg8b/cmpxchg16b
14259 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14260 // (The only way to get a 16-byte load is cmpxchg16b)
14261 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14262 SDValue Zero = DAG.getConstant(0, VT);
14263 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14264 Node->getOperand(0),
14265 Node->getOperand(1), Zero, Zero,
14266 cast<AtomicSDNode>(Node)->getMemOperand(),
14267 cast<AtomicSDNode>(Node)->getOrdering(),
14268 cast<AtomicSDNode>(Node)->getOrdering(),
14269 cast<AtomicSDNode>(Node)->getSynchScope());
14270 Results.push_back(Swap.getValue(0));
14271 Results.push_back(Swap.getValue(1));
14275 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14276 SelectionDAG &DAG, unsigned NewOp) {
14278 assert (Node->getValueType(0) == MVT::i64 &&
14279 "Only know how to expand i64 atomics");
14281 SDValue Chain = Node->getOperand(0);
14282 SDValue In1 = Node->getOperand(1);
14283 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14284 Node->getOperand(2), DAG.getIntPtrConstant(0));
14285 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14286 Node->getOperand(2), DAG.getIntPtrConstant(1));
14287 SDValue Ops[] = { Chain, In1, In2L, In2H };
14288 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14290 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14291 cast<MemSDNode>(Node)->getMemOperand());
14292 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14293 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14294 Results.push_back(Result.getValue(2));
14297 /// ReplaceNodeResults - Replace a node with an illegal result type
14298 /// with a new node built out of custom code.
14299 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14300 SmallVectorImpl<SDValue>&Results,
14301 SelectionDAG &DAG) const {
14303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14304 switch (N->getOpcode()) {
14306 llvm_unreachable("Do not know how to custom type legalize this operation!");
14307 case ISD::SIGN_EXTEND_INREG:
14312 // We don't want to expand or promote these.
14314 case ISD::FP_TO_SINT:
14315 case ISD::FP_TO_UINT: {
14316 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14318 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14321 std::pair<SDValue,SDValue> Vals =
14322 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14323 SDValue FIST = Vals.first, StackSlot = Vals.second;
14324 if (FIST.getNode()) {
14325 EVT VT = N->getValueType(0);
14326 // Return a load from the stack slot.
14327 if (StackSlot.getNode())
14328 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14329 MachinePointerInfo(),
14330 false, false, false, 0));
14332 Results.push_back(FIST);
14336 case ISD::UINT_TO_FP: {
14337 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14338 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14339 N->getValueType(0) != MVT::v2f32)
14341 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14343 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14345 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14346 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14347 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14348 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14349 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14350 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14353 case ISD::FP_ROUND: {
14354 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14356 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14357 Results.push_back(V);
14360 case ISD::INTRINSIC_W_CHAIN: {
14361 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14363 default : llvm_unreachable("Do not know how to custom type "
14364 "legalize this intrinsic operation!");
14365 case Intrinsic::x86_rdtsc:
14366 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14368 case Intrinsic::x86_rdtscp:
14369 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14373 case ISD::READCYCLECOUNTER: {
14374 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14377 case ISD::ATOMIC_CMP_SWAP: {
14378 EVT T = N->getValueType(0);
14379 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14380 bool Regs64bit = T == MVT::i128;
14381 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14382 SDValue cpInL, cpInH;
14383 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14384 DAG.getConstant(0, HalfT));
14385 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14386 DAG.getConstant(1, HalfT));
14387 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14388 Regs64bit ? X86::RAX : X86::EAX,
14390 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14391 Regs64bit ? X86::RDX : X86::EDX,
14392 cpInH, cpInL.getValue(1));
14393 SDValue swapInL, swapInH;
14394 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14395 DAG.getConstant(0, HalfT));
14396 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14397 DAG.getConstant(1, HalfT));
14398 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14399 Regs64bit ? X86::RBX : X86::EBX,
14400 swapInL, cpInH.getValue(1));
14401 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14402 Regs64bit ? X86::RCX : X86::ECX,
14403 swapInH, swapInL.getValue(1));
14404 SDValue Ops[] = { swapInH.getValue(0),
14406 swapInH.getValue(1) };
14407 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14408 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14409 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14410 X86ISD::LCMPXCHG8_DAG;
14411 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14412 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14413 Regs64bit ? X86::RAX : X86::EAX,
14414 HalfT, Result.getValue(1));
14415 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14416 Regs64bit ? X86::RDX : X86::EDX,
14417 HalfT, cpOutL.getValue(2));
14418 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14419 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14420 Results.push_back(cpOutH.getValue(1));
14423 case ISD::ATOMIC_LOAD_ADD:
14424 case ISD::ATOMIC_LOAD_AND:
14425 case ISD::ATOMIC_LOAD_NAND:
14426 case ISD::ATOMIC_LOAD_OR:
14427 case ISD::ATOMIC_LOAD_SUB:
14428 case ISD::ATOMIC_LOAD_XOR:
14429 case ISD::ATOMIC_LOAD_MAX:
14430 case ISD::ATOMIC_LOAD_MIN:
14431 case ISD::ATOMIC_LOAD_UMAX:
14432 case ISD::ATOMIC_LOAD_UMIN:
14433 case ISD::ATOMIC_SWAP: {
14435 switch (N->getOpcode()) {
14436 default: llvm_unreachable("Unexpected opcode");
14437 case ISD::ATOMIC_LOAD_ADD:
14438 Opc = X86ISD::ATOMADD64_DAG;
14440 case ISD::ATOMIC_LOAD_AND:
14441 Opc = X86ISD::ATOMAND64_DAG;
14443 case ISD::ATOMIC_LOAD_NAND:
14444 Opc = X86ISD::ATOMNAND64_DAG;
14446 case ISD::ATOMIC_LOAD_OR:
14447 Opc = X86ISD::ATOMOR64_DAG;
14449 case ISD::ATOMIC_LOAD_SUB:
14450 Opc = X86ISD::ATOMSUB64_DAG;
14452 case ISD::ATOMIC_LOAD_XOR:
14453 Opc = X86ISD::ATOMXOR64_DAG;
14455 case ISD::ATOMIC_LOAD_MAX:
14456 Opc = X86ISD::ATOMMAX64_DAG;
14458 case ISD::ATOMIC_LOAD_MIN:
14459 Opc = X86ISD::ATOMMIN64_DAG;
14461 case ISD::ATOMIC_LOAD_UMAX:
14462 Opc = X86ISD::ATOMUMAX64_DAG;
14464 case ISD::ATOMIC_LOAD_UMIN:
14465 Opc = X86ISD::ATOMUMIN64_DAG;
14467 case ISD::ATOMIC_SWAP:
14468 Opc = X86ISD::ATOMSWAP64_DAG;
14471 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14474 case ISD::ATOMIC_LOAD:
14475 ReplaceATOMIC_LOAD(N, Results, DAG);
14479 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14481 default: return nullptr;
14482 case X86ISD::BSF: return "X86ISD::BSF";
14483 case X86ISD::BSR: return "X86ISD::BSR";
14484 case X86ISD::SHLD: return "X86ISD::SHLD";
14485 case X86ISD::SHRD: return "X86ISD::SHRD";
14486 case X86ISD::FAND: return "X86ISD::FAND";
14487 case X86ISD::FANDN: return "X86ISD::FANDN";
14488 case X86ISD::FOR: return "X86ISD::FOR";
14489 case X86ISD::FXOR: return "X86ISD::FXOR";
14490 case X86ISD::FSRL: return "X86ISD::FSRL";
14491 case X86ISD::FILD: return "X86ISD::FILD";
14492 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14493 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14494 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14495 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14496 case X86ISD::FLD: return "X86ISD::FLD";
14497 case X86ISD::FST: return "X86ISD::FST";
14498 case X86ISD::CALL: return "X86ISD::CALL";
14499 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14500 case X86ISD::BT: return "X86ISD::BT";
14501 case X86ISD::CMP: return "X86ISD::CMP";
14502 case X86ISD::COMI: return "X86ISD::COMI";
14503 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14504 case X86ISD::CMPM: return "X86ISD::CMPM";
14505 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14506 case X86ISD::SETCC: return "X86ISD::SETCC";
14507 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14508 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14509 case X86ISD::CMOV: return "X86ISD::CMOV";
14510 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14511 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14512 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14513 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14514 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14515 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14516 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14517 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14518 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14519 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14520 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14521 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14522 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14523 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14524 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14525 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14526 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14527 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14528 case X86ISD::HADD: return "X86ISD::HADD";
14529 case X86ISD::HSUB: return "X86ISD::HSUB";
14530 case X86ISD::FHADD: return "X86ISD::FHADD";
14531 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14532 case X86ISD::UMAX: return "X86ISD::UMAX";
14533 case X86ISD::UMIN: return "X86ISD::UMIN";
14534 case X86ISD::SMAX: return "X86ISD::SMAX";
14535 case X86ISD::SMIN: return "X86ISD::SMIN";
14536 case X86ISD::FMAX: return "X86ISD::FMAX";
14537 case X86ISD::FMIN: return "X86ISD::FMIN";
14538 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14539 case X86ISD::FMINC: return "X86ISD::FMINC";
14540 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14541 case X86ISD::FRCP: return "X86ISD::FRCP";
14542 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14543 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14544 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14545 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14546 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14547 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14548 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14549 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14550 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14551 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14552 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14553 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14554 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14555 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14556 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14557 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14558 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14559 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14560 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14561 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14562 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14563 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14564 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14565 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14566 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14567 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14568 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14569 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14570 case X86ISD::VSHL: return "X86ISD::VSHL";
14571 case X86ISD::VSRL: return "X86ISD::VSRL";
14572 case X86ISD::VSRA: return "X86ISD::VSRA";
14573 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14574 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14575 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14576 case X86ISD::CMPP: return "X86ISD::CMPP";
14577 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14578 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14579 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14580 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14581 case X86ISD::ADD: return "X86ISD::ADD";
14582 case X86ISD::SUB: return "X86ISD::SUB";
14583 case X86ISD::ADC: return "X86ISD::ADC";
14584 case X86ISD::SBB: return "X86ISD::SBB";
14585 case X86ISD::SMUL: return "X86ISD::SMUL";
14586 case X86ISD::UMUL: return "X86ISD::UMUL";
14587 case X86ISD::INC: return "X86ISD::INC";
14588 case X86ISD::DEC: return "X86ISD::DEC";
14589 case X86ISD::OR: return "X86ISD::OR";
14590 case X86ISD::XOR: return "X86ISD::XOR";
14591 case X86ISD::AND: return "X86ISD::AND";
14592 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14593 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14594 case X86ISD::PTEST: return "X86ISD::PTEST";
14595 case X86ISD::TESTP: return "X86ISD::TESTP";
14596 case X86ISD::TESTM: return "X86ISD::TESTM";
14597 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14598 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14599 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14600 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14601 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14602 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14603 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14604 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14605 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14606 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14607 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14608 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14609 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14610 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14611 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14612 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14613 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14614 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14615 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14616 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14617 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14618 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14619 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14620 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14621 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14622 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14623 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14624 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14625 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14626 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14627 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14628 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14629 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14630 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14631 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14632 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14633 case X86ISD::SAHF: return "X86ISD::SAHF";
14634 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14635 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14636 case X86ISD::FMADD: return "X86ISD::FMADD";
14637 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14638 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14639 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14640 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14641 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14642 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14643 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14644 case X86ISD::XTEST: return "X86ISD::XTEST";
14648 // isLegalAddressingMode - Return true if the addressing mode represented
14649 // by AM is legal for this target, for a load/store of the specified type.
14650 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14652 // X86 supports extremely general addressing modes.
14653 CodeModel::Model M = getTargetMachine().getCodeModel();
14654 Reloc::Model R = getTargetMachine().getRelocationModel();
14656 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14657 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14662 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14664 // If a reference to this global requires an extra load, we can't fold it.
14665 if (isGlobalStubReference(GVFlags))
14668 // If BaseGV requires a register for the PIC base, we cannot also have a
14669 // BaseReg specified.
14670 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14673 // If lower 4G is not available, then we must use rip-relative addressing.
14674 if ((M != CodeModel::Small || R != Reloc::Static) &&
14675 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14679 switch (AM.Scale) {
14685 // These scales always work.
14690 // These scales are formed with basereg+scalereg. Only accept if there is
14695 default: // Other stuff never works.
14702 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14703 unsigned Bits = Ty->getScalarSizeInBits();
14705 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14706 // particularly cheaper than those without.
14710 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14711 // variable shifts just as cheap as scalar ones.
14712 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14715 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14716 // fully general vector.
14720 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14721 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14723 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14724 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14725 return NumBits1 > NumBits2;
14728 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14729 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14732 if (!isTypeLegal(EVT::getEVT(Ty1)))
14735 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14737 // Assuming the caller doesn't have a zeroext or signext return parameter,
14738 // truncation all the way down to i1 is valid.
14742 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14743 return isInt<32>(Imm);
14746 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14747 // Can also use sub to handle negated immediates.
14748 return isInt<32>(Imm);
14751 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14752 if (!VT1.isInteger() || !VT2.isInteger())
14754 unsigned NumBits1 = VT1.getSizeInBits();
14755 unsigned NumBits2 = VT2.getSizeInBits();
14756 return NumBits1 > NumBits2;
14759 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14760 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14761 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14764 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14765 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14766 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14769 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14770 EVT VT1 = Val.getValueType();
14771 if (isZExtFree(VT1, VT2))
14774 if (Val.getOpcode() != ISD::LOAD)
14777 if (!VT1.isSimple() || !VT1.isInteger() ||
14778 !VT2.isSimple() || !VT2.isInteger())
14781 switch (VT1.getSimpleVT().SimpleTy) {
14786 // X86 has 8, 16, and 32-bit zero-extending loads.
14794 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14795 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14798 VT = VT.getScalarType();
14800 if (!VT.isSimple())
14803 switch (VT.getSimpleVT().SimpleTy) {
14814 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14815 // i16 instructions are longer (0x66 prefix) and potentially slower.
14816 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14819 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14820 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14821 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14822 /// are assumed to be legal.
14824 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14826 if (!VT.isSimple())
14829 MVT SVT = VT.getSimpleVT();
14831 // Very little shuffling can be done for 64-bit vectors right now.
14832 if (VT.getSizeInBits() == 64)
14835 // FIXME: pshufb, blends, shifts.
14836 return (SVT.getVectorNumElements() == 2 ||
14837 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14838 isMOVLMask(M, SVT) ||
14839 isSHUFPMask(M, SVT) ||
14840 isPSHUFDMask(M, SVT) ||
14841 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14842 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14843 isPALIGNRMask(M, SVT, Subtarget) ||
14844 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14845 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14846 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14847 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14851 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14853 if (!VT.isSimple())
14856 MVT SVT = VT.getSimpleVT();
14857 unsigned NumElts = SVT.getVectorNumElements();
14858 // FIXME: This collection of masks seems suspect.
14861 if (NumElts == 4 && SVT.is128BitVector()) {
14862 return (isMOVLMask(Mask, SVT) ||
14863 isCommutedMOVLMask(Mask, SVT, true) ||
14864 isSHUFPMask(Mask, SVT) ||
14865 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14870 //===----------------------------------------------------------------------===//
14871 // X86 Scheduler Hooks
14872 //===----------------------------------------------------------------------===//
14874 /// Utility function to emit xbegin specifying the start of an RTM region.
14875 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14876 const TargetInstrInfo *TII) {
14877 DebugLoc DL = MI->getDebugLoc();
14879 const BasicBlock *BB = MBB->getBasicBlock();
14880 MachineFunction::iterator I = MBB;
14883 // For the v = xbegin(), we generate
14894 MachineBasicBlock *thisMBB = MBB;
14895 MachineFunction *MF = MBB->getParent();
14896 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14897 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14898 MF->insert(I, mainMBB);
14899 MF->insert(I, sinkMBB);
14901 // Transfer the remainder of BB and its successor edges to sinkMBB.
14902 sinkMBB->splice(sinkMBB->begin(), MBB,
14903 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14904 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14908 // # fallthrough to mainMBB
14909 // # abortion to sinkMBB
14910 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14911 thisMBB->addSuccessor(mainMBB);
14912 thisMBB->addSuccessor(sinkMBB);
14916 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14917 mainMBB->addSuccessor(sinkMBB);
14920 // EAX is live into the sinkMBB
14921 sinkMBB->addLiveIn(X86::EAX);
14922 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14923 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14926 MI->eraseFromParent();
14930 // Get CMPXCHG opcode for the specified data type.
14931 static unsigned getCmpXChgOpcode(EVT VT) {
14932 switch (VT.getSimpleVT().SimpleTy) {
14933 case MVT::i8: return X86::LCMPXCHG8;
14934 case MVT::i16: return X86::LCMPXCHG16;
14935 case MVT::i32: return X86::LCMPXCHG32;
14936 case MVT::i64: return X86::LCMPXCHG64;
14940 llvm_unreachable("Invalid operand size!");
14943 // Get LOAD opcode for the specified data type.
14944 static unsigned getLoadOpcode(EVT VT) {
14945 switch (VT.getSimpleVT().SimpleTy) {
14946 case MVT::i8: return X86::MOV8rm;
14947 case MVT::i16: return X86::MOV16rm;
14948 case MVT::i32: return X86::MOV32rm;
14949 case MVT::i64: return X86::MOV64rm;
14953 llvm_unreachable("Invalid operand size!");
14956 // Get opcode of the non-atomic one from the specified atomic instruction.
14957 static unsigned getNonAtomicOpcode(unsigned Opc) {
14959 case X86::ATOMAND8: return X86::AND8rr;
14960 case X86::ATOMAND16: return X86::AND16rr;
14961 case X86::ATOMAND32: return X86::AND32rr;
14962 case X86::ATOMAND64: return X86::AND64rr;
14963 case X86::ATOMOR8: return X86::OR8rr;
14964 case X86::ATOMOR16: return X86::OR16rr;
14965 case X86::ATOMOR32: return X86::OR32rr;
14966 case X86::ATOMOR64: return X86::OR64rr;
14967 case X86::ATOMXOR8: return X86::XOR8rr;
14968 case X86::ATOMXOR16: return X86::XOR16rr;
14969 case X86::ATOMXOR32: return X86::XOR32rr;
14970 case X86::ATOMXOR64: return X86::XOR64rr;
14972 llvm_unreachable("Unhandled atomic-load-op opcode!");
14975 // Get opcode of the non-atomic one from the specified atomic instruction with
14977 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14978 unsigned &ExtraOpc) {
14980 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14981 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14982 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14983 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14984 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14985 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14986 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14987 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14988 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14989 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14990 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14991 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14992 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14993 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14994 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14995 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14996 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14997 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14998 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14999 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15001 llvm_unreachable("Unhandled atomic-load-op opcode!");
15004 // Get opcode of the non-atomic one from the specified atomic instruction for
15005 // 64-bit data type on 32-bit target.
15006 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15008 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15009 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15010 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15011 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15012 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15013 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15014 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15015 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15016 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15017 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15019 llvm_unreachable("Unhandled atomic-load-op opcode!");
15022 // Get opcode of the non-atomic one from the specified atomic instruction for
15023 // 64-bit data type on 32-bit target with extra opcode.
15024 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15026 unsigned &ExtraOpc) {
15028 case X86::ATOMNAND6432:
15029 ExtraOpc = X86::NOT32r;
15030 HiOpc = X86::AND32rr;
15031 return X86::AND32rr;
15033 llvm_unreachable("Unhandled atomic-load-op opcode!");
15036 // Get pseudo CMOV opcode from the specified data type.
15037 static unsigned getPseudoCMOVOpc(EVT VT) {
15038 switch (VT.getSimpleVT().SimpleTy) {
15039 case MVT::i8: return X86::CMOV_GR8;
15040 case MVT::i16: return X86::CMOV_GR16;
15041 case MVT::i32: return X86::CMOV_GR32;
15045 llvm_unreachable("Unknown CMOV opcode!");
15048 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15049 // They will be translated into a spin-loop or compare-exchange loop from
15052 // dst = atomic-fetch-op MI.addr, MI.val
15058 // t1 = LOAD MI.addr
15060 // t4 = phi(t1, t3 / loop)
15061 // t2 = OP MI.val, t4
15063 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15069 MachineBasicBlock *
15070 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15071 MachineBasicBlock *MBB) const {
15072 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15073 DebugLoc DL = MI->getDebugLoc();
15075 MachineFunction *MF = MBB->getParent();
15076 MachineRegisterInfo &MRI = MF->getRegInfo();
15078 const BasicBlock *BB = MBB->getBasicBlock();
15079 MachineFunction::iterator I = MBB;
15082 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15083 "Unexpected number of operands");
15085 assert(MI->hasOneMemOperand() &&
15086 "Expected atomic-load-op to have one memoperand");
15088 // Memory Reference
15089 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15090 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15092 unsigned DstReg, SrcReg;
15093 unsigned MemOpndSlot;
15095 unsigned CurOp = 0;
15097 DstReg = MI->getOperand(CurOp++).getReg();
15098 MemOpndSlot = CurOp;
15099 CurOp += X86::AddrNumOperands;
15100 SrcReg = MI->getOperand(CurOp++).getReg();
15102 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15103 MVT::SimpleValueType VT = *RC->vt_begin();
15104 unsigned t1 = MRI.createVirtualRegister(RC);
15105 unsigned t2 = MRI.createVirtualRegister(RC);
15106 unsigned t3 = MRI.createVirtualRegister(RC);
15107 unsigned t4 = MRI.createVirtualRegister(RC);
15108 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15110 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15111 unsigned LOADOpc = getLoadOpcode(VT);
15113 // For the atomic load-arith operator, we generate
15116 // t1 = LOAD [MI.addr]
15118 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15119 // t1 = OP MI.val, EAX
15121 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15127 MachineBasicBlock *thisMBB = MBB;
15128 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15129 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15130 MF->insert(I, mainMBB);
15131 MF->insert(I, sinkMBB);
15133 MachineInstrBuilder MIB;
15135 // Transfer the remainder of BB and its successor edges to sinkMBB.
15136 sinkMBB->splice(sinkMBB->begin(), MBB,
15137 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15138 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15141 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15142 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15143 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15145 NewMO.setIsKill(false);
15146 MIB.addOperand(NewMO);
15148 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15149 unsigned flags = (*MMOI)->getFlags();
15150 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15151 MachineMemOperand *MMO =
15152 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15153 (*MMOI)->getSize(),
15154 (*MMOI)->getBaseAlignment(),
15155 (*MMOI)->getTBAAInfo(),
15156 (*MMOI)->getRanges());
15157 MIB.addMemOperand(MMO);
15160 thisMBB->addSuccessor(mainMBB);
15163 MachineBasicBlock *origMainMBB = mainMBB;
15166 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15167 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15169 unsigned Opc = MI->getOpcode();
15172 llvm_unreachable("Unhandled atomic-load-op opcode!");
15173 case X86::ATOMAND8:
15174 case X86::ATOMAND16:
15175 case X86::ATOMAND32:
15176 case X86::ATOMAND64:
15178 case X86::ATOMOR16:
15179 case X86::ATOMOR32:
15180 case X86::ATOMOR64:
15181 case X86::ATOMXOR8:
15182 case X86::ATOMXOR16:
15183 case X86::ATOMXOR32:
15184 case X86::ATOMXOR64: {
15185 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15186 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15190 case X86::ATOMNAND8:
15191 case X86::ATOMNAND16:
15192 case X86::ATOMNAND32:
15193 case X86::ATOMNAND64: {
15194 unsigned Tmp = MRI.createVirtualRegister(RC);
15196 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15197 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15199 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15202 case X86::ATOMMAX8:
15203 case X86::ATOMMAX16:
15204 case X86::ATOMMAX32:
15205 case X86::ATOMMAX64:
15206 case X86::ATOMMIN8:
15207 case X86::ATOMMIN16:
15208 case X86::ATOMMIN32:
15209 case X86::ATOMMIN64:
15210 case X86::ATOMUMAX8:
15211 case X86::ATOMUMAX16:
15212 case X86::ATOMUMAX32:
15213 case X86::ATOMUMAX64:
15214 case X86::ATOMUMIN8:
15215 case X86::ATOMUMIN16:
15216 case X86::ATOMUMIN32:
15217 case X86::ATOMUMIN64: {
15219 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15221 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15225 if (Subtarget->hasCMov()) {
15226 if (VT != MVT::i8) {
15228 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15232 // Promote i8 to i32 to use CMOV32
15233 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15234 const TargetRegisterClass *RC32 =
15235 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15236 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15237 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15238 unsigned Tmp = MRI.createVirtualRegister(RC32);
15240 unsigned Undef = MRI.createVirtualRegister(RC32);
15241 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15243 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15246 .addImm(X86::sub_8bit);
15247 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15250 .addImm(X86::sub_8bit);
15252 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15256 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15257 .addReg(Tmp, 0, X86::sub_8bit);
15260 // Use pseudo select and lower them.
15261 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15262 "Invalid atomic-load-op transformation!");
15263 unsigned SelOpc = getPseudoCMOVOpc(VT);
15264 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15265 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15266 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15267 .addReg(SrcReg).addReg(t4)
15269 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15270 // Replace the original PHI node as mainMBB is changed after CMOV
15272 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15273 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15274 Phi->eraseFromParent();
15280 // Copy PhyReg back from virtual register.
15281 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15284 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15285 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15286 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15288 NewMO.setIsKill(false);
15289 MIB.addOperand(NewMO);
15292 MIB.setMemRefs(MMOBegin, MMOEnd);
15294 // Copy PhyReg back to virtual register.
15295 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15298 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15300 mainMBB->addSuccessor(origMainMBB);
15301 mainMBB->addSuccessor(sinkMBB);
15304 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15305 TII->get(TargetOpcode::COPY), DstReg)
15308 MI->eraseFromParent();
15312 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15313 // instructions. They will be translated into a spin-loop or compare-exchange
15317 // dst = atomic-fetch-op MI.addr, MI.val
15323 // t1L = LOAD [MI.addr + 0]
15324 // t1H = LOAD [MI.addr + 4]
15326 // t4L = phi(t1L, t3L / loop)
15327 // t4H = phi(t1H, t3H / loop)
15328 // t2L = OP MI.val.lo, t4L
15329 // t2H = OP MI.val.hi, t4H
15334 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15342 MachineBasicBlock *
15343 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15344 MachineBasicBlock *MBB) const {
15345 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15346 DebugLoc DL = MI->getDebugLoc();
15348 MachineFunction *MF = MBB->getParent();
15349 MachineRegisterInfo &MRI = MF->getRegInfo();
15351 const BasicBlock *BB = MBB->getBasicBlock();
15352 MachineFunction::iterator I = MBB;
15355 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15356 "Unexpected number of operands");
15358 assert(MI->hasOneMemOperand() &&
15359 "Expected atomic-load-op32 to have one memoperand");
15361 // Memory Reference
15362 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15363 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15365 unsigned DstLoReg, DstHiReg;
15366 unsigned SrcLoReg, SrcHiReg;
15367 unsigned MemOpndSlot;
15369 unsigned CurOp = 0;
15371 DstLoReg = MI->getOperand(CurOp++).getReg();
15372 DstHiReg = MI->getOperand(CurOp++).getReg();
15373 MemOpndSlot = CurOp;
15374 CurOp += X86::AddrNumOperands;
15375 SrcLoReg = MI->getOperand(CurOp++).getReg();
15376 SrcHiReg = MI->getOperand(CurOp++).getReg();
15378 const TargetRegisterClass *RC = &X86::GR32RegClass;
15379 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15381 unsigned t1L = MRI.createVirtualRegister(RC);
15382 unsigned t1H = MRI.createVirtualRegister(RC);
15383 unsigned t2L = MRI.createVirtualRegister(RC);
15384 unsigned t2H = MRI.createVirtualRegister(RC);
15385 unsigned t3L = MRI.createVirtualRegister(RC);
15386 unsigned t3H = MRI.createVirtualRegister(RC);
15387 unsigned t4L = MRI.createVirtualRegister(RC);
15388 unsigned t4H = MRI.createVirtualRegister(RC);
15390 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15391 unsigned LOADOpc = X86::MOV32rm;
15393 // For the atomic load-arith operator, we generate
15396 // t1L = LOAD [MI.addr + 0]
15397 // t1H = LOAD [MI.addr + 4]
15399 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15400 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15401 // t2L = OP MI.val.lo, t4L
15402 // t2H = OP MI.val.hi, t4H
15405 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15413 MachineBasicBlock *thisMBB = MBB;
15414 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15415 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15416 MF->insert(I, mainMBB);
15417 MF->insert(I, sinkMBB);
15419 MachineInstrBuilder MIB;
15421 // Transfer the remainder of BB and its successor edges to sinkMBB.
15422 sinkMBB->splice(sinkMBB->begin(), MBB,
15423 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15424 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15428 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15429 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15430 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15432 NewMO.setIsKill(false);
15433 MIB.addOperand(NewMO);
15435 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15436 unsigned flags = (*MMOI)->getFlags();
15437 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15438 MachineMemOperand *MMO =
15439 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15440 (*MMOI)->getSize(),
15441 (*MMOI)->getBaseAlignment(),
15442 (*MMOI)->getTBAAInfo(),
15443 (*MMOI)->getRanges());
15444 MIB.addMemOperand(MMO);
15446 MachineInstr *LowMI = MIB;
15449 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15450 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15451 if (i == X86::AddrDisp) {
15452 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15454 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15456 NewMO.setIsKill(false);
15457 MIB.addOperand(NewMO);
15460 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15462 thisMBB->addSuccessor(mainMBB);
15465 MachineBasicBlock *origMainMBB = mainMBB;
15468 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15469 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15470 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15471 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15473 unsigned Opc = MI->getOpcode();
15476 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15477 case X86::ATOMAND6432:
15478 case X86::ATOMOR6432:
15479 case X86::ATOMXOR6432:
15480 case X86::ATOMADD6432:
15481 case X86::ATOMSUB6432: {
15483 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15484 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15486 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15490 case X86::ATOMNAND6432: {
15491 unsigned HiOpc, NOTOpc;
15492 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15493 unsigned TmpL = MRI.createVirtualRegister(RC);
15494 unsigned TmpH = MRI.createVirtualRegister(RC);
15495 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15497 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15499 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15500 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15503 case X86::ATOMMAX6432:
15504 case X86::ATOMMIN6432:
15505 case X86::ATOMUMAX6432:
15506 case X86::ATOMUMIN6432: {
15508 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15509 unsigned cL = MRI.createVirtualRegister(RC8);
15510 unsigned cH = MRI.createVirtualRegister(RC8);
15511 unsigned cL32 = MRI.createVirtualRegister(RC);
15512 unsigned cH32 = MRI.createVirtualRegister(RC);
15513 unsigned cc = MRI.createVirtualRegister(RC);
15514 // cl := cmp src_lo, lo
15515 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15516 .addReg(SrcLoReg).addReg(t4L);
15517 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15518 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15519 // ch := cmp src_hi, hi
15520 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15521 .addReg(SrcHiReg).addReg(t4H);
15522 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15523 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15524 // cc := if (src_hi == hi) ? cl : ch;
15525 if (Subtarget->hasCMov()) {
15526 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15527 .addReg(cH32).addReg(cL32);
15529 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15530 .addReg(cH32).addReg(cL32)
15531 .addImm(X86::COND_E);
15532 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15534 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15535 if (Subtarget->hasCMov()) {
15536 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15537 .addReg(SrcLoReg).addReg(t4L);
15538 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15539 .addReg(SrcHiReg).addReg(t4H);
15541 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15542 .addReg(SrcLoReg).addReg(t4L)
15543 .addImm(X86::COND_NE);
15544 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15545 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15546 // 2nd CMOV lowering.
15547 mainMBB->addLiveIn(X86::EFLAGS);
15548 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15549 .addReg(SrcHiReg).addReg(t4H)
15550 .addImm(X86::COND_NE);
15551 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15552 // Replace the original PHI node as mainMBB is changed after CMOV
15554 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15555 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15556 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15557 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15558 PhiL->eraseFromParent();
15559 PhiH->eraseFromParent();
15563 case X86::ATOMSWAP6432: {
15565 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15566 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15567 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15572 // Copy EDX:EAX back from HiReg:LoReg
15573 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15574 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15575 // Copy ECX:EBX from t1H:t1L
15576 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15577 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15579 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15580 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15581 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15583 NewMO.setIsKill(false);
15584 MIB.addOperand(NewMO);
15586 MIB.setMemRefs(MMOBegin, MMOEnd);
15588 // Copy EDX:EAX back to t3H:t3L
15589 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15590 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15592 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15594 mainMBB->addSuccessor(origMainMBB);
15595 mainMBB->addSuccessor(sinkMBB);
15598 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15599 TII->get(TargetOpcode::COPY), DstLoReg)
15601 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15602 TII->get(TargetOpcode::COPY), DstHiReg)
15605 MI->eraseFromParent();
15609 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15610 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15611 // in the .td file.
15612 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15613 const TargetInstrInfo *TII) {
15615 switch (MI->getOpcode()) {
15616 default: llvm_unreachable("illegal opcode!");
15617 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15618 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15619 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15620 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15621 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15622 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15623 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15624 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15627 DebugLoc dl = MI->getDebugLoc();
15628 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15630 unsigned NumArgs = MI->getNumOperands();
15631 for (unsigned i = 1; i < NumArgs; ++i) {
15632 MachineOperand &Op = MI->getOperand(i);
15633 if (!(Op.isReg() && Op.isImplicit()))
15634 MIB.addOperand(Op);
15636 if (MI->hasOneMemOperand())
15637 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15639 BuildMI(*BB, MI, dl,
15640 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15641 .addReg(X86::XMM0);
15643 MI->eraseFromParent();
15647 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15648 // defs in an instruction pattern
15649 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15650 const TargetInstrInfo *TII) {
15652 switch (MI->getOpcode()) {
15653 default: llvm_unreachable("illegal opcode!");
15654 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15655 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15656 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15657 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15658 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15659 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15660 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15661 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15664 DebugLoc dl = MI->getDebugLoc();
15665 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15667 unsigned NumArgs = MI->getNumOperands(); // remove the results
15668 for (unsigned i = 1; i < NumArgs; ++i) {
15669 MachineOperand &Op = MI->getOperand(i);
15670 if (!(Op.isReg() && Op.isImplicit()))
15671 MIB.addOperand(Op);
15673 if (MI->hasOneMemOperand())
15674 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15676 BuildMI(*BB, MI, dl,
15677 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15680 MI->eraseFromParent();
15684 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15685 const TargetInstrInfo *TII,
15686 const X86Subtarget* Subtarget) {
15687 DebugLoc dl = MI->getDebugLoc();
15689 // Address into RAX/EAX, other two args into ECX, EDX.
15690 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15691 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15692 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15693 for (int i = 0; i < X86::AddrNumOperands; ++i)
15694 MIB.addOperand(MI->getOperand(i));
15696 unsigned ValOps = X86::AddrNumOperands;
15697 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15698 .addReg(MI->getOperand(ValOps).getReg());
15699 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15700 .addReg(MI->getOperand(ValOps+1).getReg());
15702 // The instruction doesn't actually take any operands though.
15703 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15705 MI->eraseFromParent(); // The pseudo is gone now.
15709 MachineBasicBlock *
15710 X86TargetLowering::EmitVAARG64WithCustomInserter(
15712 MachineBasicBlock *MBB) const {
15713 // Emit va_arg instruction on X86-64.
15715 // Operands to this pseudo-instruction:
15716 // 0 ) Output : destination address (reg)
15717 // 1-5) Input : va_list address (addr, i64mem)
15718 // 6 ) ArgSize : Size (in bytes) of vararg type
15719 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15720 // 8 ) Align : Alignment of type
15721 // 9 ) EFLAGS (implicit-def)
15723 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15724 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15726 unsigned DestReg = MI->getOperand(0).getReg();
15727 MachineOperand &Base = MI->getOperand(1);
15728 MachineOperand &Scale = MI->getOperand(2);
15729 MachineOperand &Index = MI->getOperand(3);
15730 MachineOperand &Disp = MI->getOperand(4);
15731 MachineOperand &Segment = MI->getOperand(5);
15732 unsigned ArgSize = MI->getOperand(6).getImm();
15733 unsigned ArgMode = MI->getOperand(7).getImm();
15734 unsigned Align = MI->getOperand(8).getImm();
15736 // Memory Reference
15737 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15738 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15739 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15741 // Machine Information
15742 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15743 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15744 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15745 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15746 DebugLoc DL = MI->getDebugLoc();
15748 // struct va_list {
15751 // i64 overflow_area (address)
15752 // i64 reg_save_area (address)
15754 // sizeof(va_list) = 24
15755 // alignment(va_list) = 8
15757 unsigned TotalNumIntRegs = 6;
15758 unsigned TotalNumXMMRegs = 8;
15759 bool UseGPOffset = (ArgMode == 1);
15760 bool UseFPOffset = (ArgMode == 2);
15761 unsigned MaxOffset = TotalNumIntRegs * 8 +
15762 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15764 /* Align ArgSize to a multiple of 8 */
15765 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15766 bool NeedsAlign = (Align > 8);
15768 MachineBasicBlock *thisMBB = MBB;
15769 MachineBasicBlock *overflowMBB;
15770 MachineBasicBlock *offsetMBB;
15771 MachineBasicBlock *endMBB;
15773 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15774 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15775 unsigned OffsetReg = 0;
15777 if (!UseGPOffset && !UseFPOffset) {
15778 // If we only pull from the overflow region, we don't create a branch.
15779 // We don't need to alter control flow.
15780 OffsetDestReg = 0; // unused
15781 OverflowDestReg = DestReg;
15783 offsetMBB = nullptr;
15784 overflowMBB = thisMBB;
15787 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15788 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15789 // If not, pull from overflow_area. (branch to overflowMBB)
15794 // offsetMBB overflowMBB
15799 // Registers for the PHI in endMBB
15800 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15801 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15803 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15804 MachineFunction *MF = MBB->getParent();
15805 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15806 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15807 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15809 MachineFunction::iterator MBBIter = MBB;
15812 // Insert the new basic blocks
15813 MF->insert(MBBIter, offsetMBB);
15814 MF->insert(MBBIter, overflowMBB);
15815 MF->insert(MBBIter, endMBB);
15817 // Transfer the remainder of MBB and its successor edges to endMBB.
15818 endMBB->splice(endMBB->begin(), thisMBB,
15819 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15820 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15822 // Make offsetMBB and overflowMBB successors of thisMBB
15823 thisMBB->addSuccessor(offsetMBB);
15824 thisMBB->addSuccessor(overflowMBB);
15826 // endMBB is a successor of both offsetMBB and overflowMBB
15827 offsetMBB->addSuccessor(endMBB);
15828 overflowMBB->addSuccessor(endMBB);
15830 // Load the offset value into a register
15831 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15832 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15836 .addDisp(Disp, UseFPOffset ? 4 : 0)
15837 .addOperand(Segment)
15838 .setMemRefs(MMOBegin, MMOEnd);
15840 // Check if there is enough room left to pull this argument.
15841 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15843 .addImm(MaxOffset + 8 - ArgSizeA8);
15845 // Branch to "overflowMBB" if offset >= max
15846 // Fall through to "offsetMBB" otherwise
15847 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15848 .addMBB(overflowMBB);
15851 // In offsetMBB, emit code to use the reg_save_area.
15853 assert(OffsetReg != 0);
15855 // Read the reg_save_area address.
15856 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15857 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15862 .addOperand(Segment)
15863 .setMemRefs(MMOBegin, MMOEnd);
15865 // Zero-extend the offset
15866 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15867 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15870 .addImm(X86::sub_32bit);
15872 // Add the offset to the reg_save_area to get the final address.
15873 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15874 .addReg(OffsetReg64)
15875 .addReg(RegSaveReg);
15877 // Compute the offset for the next argument
15878 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15879 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15881 .addImm(UseFPOffset ? 16 : 8);
15883 // Store it back into the va_list.
15884 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15888 .addDisp(Disp, UseFPOffset ? 4 : 0)
15889 .addOperand(Segment)
15890 .addReg(NextOffsetReg)
15891 .setMemRefs(MMOBegin, MMOEnd);
15894 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15899 // Emit code to use overflow area
15902 // Load the overflow_area address into a register.
15903 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15904 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15909 .addOperand(Segment)
15910 .setMemRefs(MMOBegin, MMOEnd);
15912 // If we need to align it, do so. Otherwise, just copy the address
15913 // to OverflowDestReg.
15915 // Align the overflow address
15916 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15917 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15919 // aligned_addr = (addr + (align-1)) & ~(align-1)
15920 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15921 .addReg(OverflowAddrReg)
15924 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15926 .addImm(~(uint64_t)(Align-1));
15928 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15929 .addReg(OverflowAddrReg);
15932 // Compute the next overflow address after this argument.
15933 // (the overflow address should be kept 8-byte aligned)
15934 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15935 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15936 .addReg(OverflowDestReg)
15937 .addImm(ArgSizeA8);
15939 // Store the new overflow address.
15940 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15945 .addOperand(Segment)
15946 .addReg(NextAddrReg)
15947 .setMemRefs(MMOBegin, MMOEnd);
15949 // If we branched, emit the PHI to the front of endMBB.
15951 BuildMI(*endMBB, endMBB->begin(), DL,
15952 TII->get(X86::PHI), DestReg)
15953 .addReg(OffsetDestReg).addMBB(offsetMBB)
15954 .addReg(OverflowDestReg).addMBB(overflowMBB);
15957 // Erase the pseudo instruction
15958 MI->eraseFromParent();
15963 MachineBasicBlock *
15964 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15966 MachineBasicBlock *MBB) const {
15967 // Emit code to save XMM registers to the stack. The ABI says that the
15968 // number of registers to save is given in %al, so it's theoretically
15969 // possible to do an indirect jump trick to avoid saving all of them,
15970 // however this code takes a simpler approach and just executes all
15971 // of the stores if %al is non-zero. It's less code, and it's probably
15972 // easier on the hardware branch predictor, and stores aren't all that
15973 // expensive anyway.
15975 // Create the new basic blocks. One block contains all the XMM stores,
15976 // and one block is the final destination regardless of whether any
15977 // stores were performed.
15978 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15979 MachineFunction *F = MBB->getParent();
15980 MachineFunction::iterator MBBIter = MBB;
15982 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15983 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15984 F->insert(MBBIter, XMMSaveMBB);
15985 F->insert(MBBIter, EndMBB);
15987 // Transfer the remainder of MBB and its successor edges to EndMBB.
15988 EndMBB->splice(EndMBB->begin(), MBB,
15989 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15990 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15992 // The original block will now fall through to the XMM save block.
15993 MBB->addSuccessor(XMMSaveMBB);
15994 // The XMMSaveMBB will fall through to the end block.
15995 XMMSaveMBB->addSuccessor(EndMBB);
15997 // Now add the instructions.
15998 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15999 DebugLoc DL = MI->getDebugLoc();
16001 unsigned CountReg = MI->getOperand(0).getReg();
16002 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16003 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16005 if (!Subtarget->isTargetWin64()) {
16006 // If %al is 0, branch around the XMM save block.
16007 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16008 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16009 MBB->addSuccessor(EndMBB);
16012 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16013 // that was just emitted, but clearly shouldn't be "saved".
16014 assert((MI->getNumOperands() <= 3 ||
16015 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16016 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16017 && "Expected last argument to be EFLAGS");
16018 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16019 // In the XMM save block, save all the XMM argument registers.
16020 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16021 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16022 MachineMemOperand *MMO =
16023 F->getMachineMemOperand(
16024 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16025 MachineMemOperand::MOStore,
16026 /*Size=*/16, /*Align=*/16);
16027 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16028 .addFrameIndex(RegSaveFrameIndex)
16029 .addImm(/*Scale=*/1)
16030 .addReg(/*IndexReg=*/0)
16031 .addImm(/*Disp=*/Offset)
16032 .addReg(/*Segment=*/0)
16033 .addReg(MI->getOperand(i).getReg())
16034 .addMemOperand(MMO);
16037 MI->eraseFromParent(); // The pseudo instruction is gone now.
16042 // The EFLAGS operand of SelectItr might be missing a kill marker
16043 // because there were multiple uses of EFLAGS, and ISel didn't know
16044 // which to mark. Figure out whether SelectItr should have had a
16045 // kill marker, and set it if it should. Returns the correct kill
16047 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16048 MachineBasicBlock* BB,
16049 const TargetRegisterInfo* TRI) {
16050 // Scan forward through BB for a use/def of EFLAGS.
16051 MachineBasicBlock::iterator miI(std::next(SelectItr));
16052 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16053 const MachineInstr& mi = *miI;
16054 if (mi.readsRegister(X86::EFLAGS))
16056 if (mi.definesRegister(X86::EFLAGS))
16057 break; // Should have kill-flag - update below.
16060 // If we hit the end of the block, check whether EFLAGS is live into a
16062 if (miI == BB->end()) {
16063 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16064 sEnd = BB->succ_end();
16065 sItr != sEnd; ++sItr) {
16066 MachineBasicBlock* succ = *sItr;
16067 if (succ->isLiveIn(X86::EFLAGS))
16072 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16073 // out. SelectMI should have a kill flag on EFLAGS.
16074 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16078 MachineBasicBlock *
16079 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16080 MachineBasicBlock *BB) const {
16081 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16082 DebugLoc DL = MI->getDebugLoc();
16084 // To "insert" a SELECT_CC instruction, we actually have to insert the
16085 // diamond control-flow pattern. The incoming instruction knows the
16086 // destination vreg to set, the condition code register to branch on, the
16087 // true/false values to select between, and a branch opcode to use.
16088 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16089 MachineFunction::iterator It = BB;
16095 // cmpTY ccX, r1, r2
16097 // fallthrough --> copy0MBB
16098 MachineBasicBlock *thisMBB = BB;
16099 MachineFunction *F = BB->getParent();
16100 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16101 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16102 F->insert(It, copy0MBB);
16103 F->insert(It, sinkMBB);
16105 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16106 // live into the sink and copy blocks.
16107 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16108 if (!MI->killsRegister(X86::EFLAGS) &&
16109 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16110 copy0MBB->addLiveIn(X86::EFLAGS);
16111 sinkMBB->addLiveIn(X86::EFLAGS);
16114 // Transfer the remainder of BB and its successor edges to sinkMBB.
16115 sinkMBB->splice(sinkMBB->begin(), BB,
16116 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16117 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16119 // Add the true and fallthrough blocks as its successors.
16120 BB->addSuccessor(copy0MBB);
16121 BB->addSuccessor(sinkMBB);
16123 // Create the conditional branch instruction.
16125 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16126 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16129 // %FalseValue = ...
16130 // # fallthrough to sinkMBB
16131 copy0MBB->addSuccessor(sinkMBB);
16134 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16136 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16137 TII->get(X86::PHI), MI->getOperand(0).getReg())
16138 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16139 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16141 MI->eraseFromParent(); // The pseudo instruction is gone now.
16145 MachineBasicBlock *
16146 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16147 bool Is64Bit) const {
16148 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16149 DebugLoc DL = MI->getDebugLoc();
16150 MachineFunction *MF = BB->getParent();
16151 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16153 assert(MF->shouldSplitStack());
16155 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16156 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16159 // ... [Till the alloca]
16160 // If stacklet is not large enough, jump to mallocMBB
16163 // Allocate by subtracting from RSP
16164 // Jump to continueMBB
16167 // Allocate by call to runtime
16171 // [rest of original BB]
16174 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16175 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16176 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16178 MachineRegisterInfo &MRI = MF->getRegInfo();
16179 const TargetRegisterClass *AddrRegClass =
16180 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16182 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16183 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16184 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16185 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16186 sizeVReg = MI->getOperand(1).getReg(),
16187 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16189 MachineFunction::iterator MBBIter = BB;
16192 MF->insert(MBBIter, bumpMBB);
16193 MF->insert(MBBIter, mallocMBB);
16194 MF->insert(MBBIter, continueMBB);
16196 continueMBB->splice(continueMBB->begin(), BB,
16197 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16198 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16200 // Add code to the main basic block to check if the stack limit has been hit,
16201 // and if so, jump to mallocMBB otherwise to bumpMBB.
16202 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16203 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16204 .addReg(tmpSPVReg).addReg(sizeVReg);
16205 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16206 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16207 .addReg(SPLimitVReg);
16208 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16210 // bumpMBB simply decreases the stack pointer, since we know the current
16211 // stacklet has enough space.
16212 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16213 .addReg(SPLimitVReg);
16214 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16215 .addReg(SPLimitVReg);
16216 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16218 // Calls into a routine in libgcc to allocate more space from the heap.
16219 const uint32_t *RegMask =
16220 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16222 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16224 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16225 .addExternalSymbol("__morestack_allocate_stack_space")
16226 .addRegMask(RegMask)
16227 .addReg(X86::RDI, RegState::Implicit)
16228 .addReg(X86::RAX, RegState::ImplicitDefine);
16230 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16232 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16233 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16234 .addExternalSymbol("__morestack_allocate_stack_space")
16235 .addRegMask(RegMask)
16236 .addReg(X86::EAX, RegState::ImplicitDefine);
16240 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16243 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16244 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16245 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16247 // Set up the CFG correctly.
16248 BB->addSuccessor(bumpMBB);
16249 BB->addSuccessor(mallocMBB);
16250 mallocMBB->addSuccessor(continueMBB);
16251 bumpMBB->addSuccessor(continueMBB);
16253 // Take care of the PHI nodes.
16254 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16255 MI->getOperand(0).getReg())
16256 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16257 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16259 // Delete the original pseudo instruction.
16260 MI->eraseFromParent();
16263 return continueMBB;
16266 MachineBasicBlock *
16267 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16268 MachineBasicBlock *BB) const {
16269 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16270 DebugLoc DL = MI->getDebugLoc();
16272 assert(!Subtarget->isTargetMacho());
16274 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16275 // non-trivial part is impdef of ESP.
16277 if (Subtarget->isTargetWin64()) {
16278 if (Subtarget->isTargetCygMing()) {
16279 // ___chkstk(Mingw64):
16280 // Clobbers R10, R11, RAX and EFLAGS.
16282 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16283 .addExternalSymbol("___chkstk")
16284 .addReg(X86::RAX, RegState::Implicit)
16285 .addReg(X86::RSP, RegState::Implicit)
16286 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16287 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16288 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16290 // __chkstk(MSVCRT): does not update stack pointer.
16291 // Clobbers R10, R11 and EFLAGS.
16292 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16293 .addExternalSymbol("__chkstk")
16294 .addReg(X86::RAX, RegState::Implicit)
16295 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16296 // RAX has the offset to be subtracted from RSP.
16297 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16302 const char *StackProbeSymbol =
16303 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16305 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16306 .addExternalSymbol(StackProbeSymbol)
16307 .addReg(X86::EAX, RegState::Implicit)
16308 .addReg(X86::ESP, RegState::Implicit)
16309 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16310 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16311 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16314 MI->eraseFromParent(); // The pseudo instruction is gone now.
16318 MachineBasicBlock *
16319 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16320 MachineBasicBlock *BB) const {
16321 // This is pretty easy. We're taking the value that we received from
16322 // our load from the relocation, sticking it in either RDI (x86-64)
16323 // or EAX and doing an indirect call. The return value will then
16324 // be in the normal return register.
16325 const X86InstrInfo *TII
16326 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16327 DebugLoc DL = MI->getDebugLoc();
16328 MachineFunction *F = BB->getParent();
16330 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16331 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16333 // Get a register mask for the lowered call.
16334 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16335 // proper register mask.
16336 const uint32_t *RegMask =
16337 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16338 if (Subtarget->is64Bit()) {
16339 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16340 TII->get(X86::MOV64rm), X86::RDI)
16342 .addImm(0).addReg(0)
16343 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16344 MI->getOperand(3).getTargetFlags())
16346 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16347 addDirectMem(MIB, X86::RDI);
16348 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16349 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16350 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16351 TII->get(X86::MOV32rm), X86::EAX)
16353 .addImm(0).addReg(0)
16354 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16355 MI->getOperand(3).getTargetFlags())
16357 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16358 addDirectMem(MIB, X86::EAX);
16359 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16361 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16362 TII->get(X86::MOV32rm), X86::EAX)
16363 .addReg(TII->getGlobalBaseReg(F))
16364 .addImm(0).addReg(0)
16365 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16366 MI->getOperand(3).getTargetFlags())
16368 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16369 addDirectMem(MIB, X86::EAX);
16370 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16373 MI->eraseFromParent(); // The pseudo instruction is gone now.
16377 MachineBasicBlock *
16378 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16379 MachineBasicBlock *MBB) const {
16380 DebugLoc DL = MI->getDebugLoc();
16381 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16383 MachineFunction *MF = MBB->getParent();
16384 MachineRegisterInfo &MRI = MF->getRegInfo();
16386 const BasicBlock *BB = MBB->getBasicBlock();
16387 MachineFunction::iterator I = MBB;
16390 // Memory Reference
16391 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16392 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16395 unsigned MemOpndSlot = 0;
16397 unsigned CurOp = 0;
16399 DstReg = MI->getOperand(CurOp++).getReg();
16400 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16401 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16402 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16403 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16405 MemOpndSlot = CurOp;
16407 MVT PVT = getPointerTy();
16408 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16409 "Invalid Pointer Size!");
16411 // For v = setjmp(buf), we generate
16414 // buf[LabelOffset] = restoreMBB
16415 // SjLjSetup restoreMBB
16421 // v = phi(main, restore)
16426 MachineBasicBlock *thisMBB = MBB;
16427 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16428 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16429 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16430 MF->insert(I, mainMBB);
16431 MF->insert(I, sinkMBB);
16432 MF->push_back(restoreMBB);
16434 MachineInstrBuilder MIB;
16436 // Transfer the remainder of BB and its successor edges to sinkMBB.
16437 sinkMBB->splice(sinkMBB->begin(), MBB,
16438 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16439 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16442 unsigned PtrStoreOpc = 0;
16443 unsigned LabelReg = 0;
16444 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16445 Reloc::Model RM = getTargetMachine().getRelocationModel();
16446 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16447 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16449 // Prepare IP either in reg or imm.
16450 if (!UseImmLabel) {
16451 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16452 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16453 LabelReg = MRI.createVirtualRegister(PtrRC);
16454 if (Subtarget->is64Bit()) {
16455 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16459 .addMBB(restoreMBB)
16462 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16463 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16464 .addReg(XII->getGlobalBaseReg(MF))
16467 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16471 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16473 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16474 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16475 if (i == X86::AddrDisp)
16476 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16478 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16481 MIB.addReg(LabelReg);
16483 MIB.addMBB(restoreMBB);
16484 MIB.setMemRefs(MMOBegin, MMOEnd);
16486 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16487 .addMBB(restoreMBB);
16489 const X86RegisterInfo *RegInfo =
16490 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16491 MIB.addRegMask(RegInfo->getNoPreservedMask());
16492 thisMBB->addSuccessor(mainMBB);
16493 thisMBB->addSuccessor(restoreMBB);
16497 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16498 mainMBB->addSuccessor(sinkMBB);
16501 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16502 TII->get(X86::PHI), DstReg)
16503 .addReg(mainDstReg).addMBB(mainMBB)
16504 .addReg(restoreDstReg).addMBB(restoreMBB);
16507 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16508 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16509 restoreMBB->addSuccessor(sinkMBB);
16511 MI->eraseFromParent();
16515 MachineBasicBlock *
16516 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16517 MachineBasicBlock *MBB) const {
16518 DebugLoc DL = MI->getDebugLoc();
16519 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16521 MachineFunction *MF = MBB->getParent();
16522 MachineRegisterInfo &MRI = MF->getRegInfo();
16524 // Memory Reference
16525 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16526 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16528 MVT PVT = getPointerTy();
16529 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16530 "Invalid Pointer Size!");
16532 const TargetRegisterClass *RC =
16533 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16534 unsigned Tmp = MRI.createVirtualRegister(RC);
16535 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16536 const X86RegisterInfo *RegInfo =
16537 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16538 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16539 unsigned SP = RegInfo->getStackRegister();
16541 MachineInstrBuilder MIB;
16543 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16544 const int64_t SPOffset = 2 * PVT.getStoreSize();
16546 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16547 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16550 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16551 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16552 MIB.addOperand(MI->getOperand(i));
16553 MIB.setMemRefs(MMOBegin, MMOEnd);
16555 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16556 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16557 if (i == X86::AddrDisp)
16558 MIB.addDisp(MI->getOperand(i), LabelOffset);
16560 MIB.addOperand(MI->getOperand(i));
16562 MIB.setMemRefs(MMOBegin, MMOEnd);
16564 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16565 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16566 if (i == X86::AddrDisp)
16567 MIB.addDisp(MI->getOperand(i), SPOffset);
16569 MIB.addOperand(MI->getOperand(i));
16571 MIB.setMemRefs(MMOBegin, MMOEnd);
16573 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16575 MI->eraseFromParent();
16579 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16580 // accumulator loops. Writing back to the accumulator allows the coalescer
16581 // to remove extra copies in the loop.
16582 MachineBasicBlock *
16583 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16584 MachineBasicBlock *MBB) const {
16585 MachineOperand &AddendOp = MI->getOperand(3);
16587 // Bail out early if the addend isn't a register - we can't switch these.
16588 if (!AddendOp.isReg())
16591 MachineFunction &MF = *MBB->getParent();
16592 MachineRegisterInfo &MRI = MF.getRegInfo();
16594 // Check whether the addend is defined by a PHI:
16595 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16596 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16597 if (!AddendDef.isPHI())
16600 // Look for the following pattern:
16602 // %addend = phi [%entry, 0], [%loop, %result]
16604 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16608 // %addend = phi [%entry, 0], [%loop, %result]
16610 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16612 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16613 assert(AddendDef.getOperand(i).isReg());
16614 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16615 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16616 if (&PHISrcInst == MI) {
16617 // Found a matching instruction.
16618 unsigned NewFMAOpc = 0;
16619 switch (MI->getOpcode()) {
16620 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16621 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16622 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16623 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16624 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16625 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16626 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16627 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16628 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16629 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16630 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16631 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16632 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16633 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16634 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16635 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16636 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16637 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16638 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16639 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16640 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16641 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16642 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16643 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16644 default: llvm_unreachable("Unrecognized FMA variant.");
16647 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16648 MachineInstrBuilder MIB =
16649 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16650 .addOperand(MI->getOperand(0))
16651 .addOperand(MI->getOperand(3))
16652 .addOperand(MI->getOperand(2))
16653 .addOperand(MI->getOperand(1));
16654 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16655 MI->eraseFromParent();
16662 MachineBasicBlock *
16663 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16664 MachineBasicBlock *BB) const {
16665 switch (MI->getOpcode()) {
16666 default: llvm_unreachable("Unexpected instr type to insert");
16667 case X86::TAILJMPd64:
16668 case X86::TAILJMPr64:
16669 case X86::TAILJMPm64:
16670 llvm_unreachable("TAILJMP64 would not be touched here.");
16671 case X86::TCRETURNdi64:
16672 case X86::TCRETURNri64:
16673 case X86::TCRETURNmi64:
16675 case X86::WIN_ALLOCA:
16676 return EmitLoweredWinAlloca(MI, BB);
16677 case X86::SEG_ALLOCA_32:
16678 return EmitLoweredSegAlloca(MI, BB, false);
16679 case X86::SEG_ALLOCA_64:
16680 return EmitLoweredSegAlloca(MI, BB, true);
16681 case X86::TLSCall_32:
16682 case X86::TLSCall_64:
16683 return EmitLoweredTLSCall(MI, BB);
16684 case X86::CMOV_GR8:
16685 case X86::CMOV_FR32:
16686 case X86::CMOV_FR64:
16687 case X86::CMOV_V4F32:
16688 case X86::CMOV_V2F64:
16689 case X86::CMOV_V2I64:
16690 case X86::CMOV_V8F32:
16691 case X86::CMOV_V4F64:
16692 case X86::CMOV_V4I64:
16693 case X86::CMOV_V16F32:
16694 case X86::CMOV_V8F64:
16695 case X86::CMOV_V8I64:
16696 case X86::CMOV_GR16:
16697 case X86::CMOV_GR32:
16698 case X86::CMOV_RFP32:
16699 case X86::CMOV_RFP64:
16700 case X86::CMOV_RFP80:
16701 return EmitLoweredSelect(MI, BB);
16703 case X86::FP32_TO_INT16_IN_MEM:
16704 case X86::FP32_TO_INT32_IN_MEM:
16705 case X86::FP32_TO_INT64_IN_MEM:
16706 case X86::FP64_TO_INT16_IN_MEM:
16707 case X86::FP64_TO_INT32_IN_MEM:
16708 case X86::FP64_TO_INT64_IN_MEM:
16709 case X86::FP80_TO_INT16_IN_MEM:
16710 case X86::FP80_TO_INT32_IN_MEM:
16711 case X86::FP80_TO_INT64_IN_MEM: {
16712 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16713 DebugLoc DL = MI->getDebugLoc();
16715 // Change the floating point control register to use "round towards zero"
16716 // mode when truncating to an integer value.
16717 MachineFunction *F = BB->getParent();
16718 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16719 addFrameReference(BuildMI(*BB, MI, DL,
16720 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16722 // Load the old value of the high byte of the control word...
16724 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16725 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16728 // Set the high part to be round to zero...
16729 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16732 // Reload the modified control word now...
16733 addFrameReference(BuildMI(*BB, MI, DL,
16734 TII->get(X86::FLDCW16m)), CWFrameIdx);
16736 // Restore the memory image of control word to original value
16737 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16740 // Get the X86 opcode to use.
16742 switch (MI->getOpcode()) {
16743 default: llvm_unreachable("illegal opcode!");
16744 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16745 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16746 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16747 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16748 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16749 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16750 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16751 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16752 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16756 MachineOperand &Op = MI->getOperand(0);
16758 AM.BaseType = X86AddressMode::RegBase;
16759 AM.Base.Reg = Op.getReg();
16761 AM.BaseType = X86AddressMode::FrameIndexBase;
16762 AM.Base.FrameIndex = Op.getIndex();
16764 Op = MI->getOperand(1);
16766 AM.Scale = Op.getImm();
16767 Op = MI->getOperand(2);
16769 AM.IndexReg = Op.getImm();
16770 Op = MI->getOperand(3);
16771 if (Op.isGlobal()) {
16772 AM.GV = Op.getGlobal();
16774 AM.Disp = Op.getImm();
16776 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16777 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16779 // Reload the original control word now.
16780 addFrameReference(BuildMI(*BB, MI, DL,
16781 TII->get(X86::FLDCW16m)), CWFrameIdx);
16783 MI->eraseFromParent(); // The pseudo instruction is gone now.
16786 // String/text processing lowering.
16787 case X86::PCMPISTRM128REG:
16788 case X86::VPCMPISTRM128REG:
16789 case X86::PCMPISTRM128MEM:
16790 case X86::VPCMPISTRM128MEM:
16791 case X86::PCMPESTRM128REG:
16792 case X86::VPCMPESTRM128REG:
16793 case X86::PCMPESTRM128MEM:
16794 case X86::VPCMPESTRM128MEM:
16795 assert(Subtarget->hasSSE42() &&
16796 "Target must have SSE4.2 or AVX features enabled");
16797 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16799 // String/text processing lowering.
16800 case X86::PCMPISTRIREG:
16801 case X86::VPCMPISTRIREG:
16802 case X86::PCMPISTRIMEM:
16803 case X86::VPCMPISTRIMEM:
16804 case X86::PCMPESTRIREG:
16805 case X86::VPCMPESTRIREG:
16806 case X86::PCMPESTRIMEM:
16807 case X86::VPCMPESTRIMEM:
16808 assert(Subtarget->hasSSE42() &&
16809 "Target must have SSE4.2 or AVX features enabled");
16810 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16812 // Thread synchronization.
16814 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16818 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16820 // Atomic Lowering.
16821 case X86::ATOMAND8:
16822 case X86::ATOMAND16:
16823 case X86::ATOMAND32:
16824 case X86::ATOMAND64:
16827 case X86::ATOMOR16:
16828 case X86::ATOMOR32:
16829 case X86::ATOMOR64:
16831 case X86::ATOMXOR16:
16832 case X86::ATOMXOR8:
16833 case X86::ATOMXOR32:
16834 case X86::ATOMXOR64:
16836 case X86::ATOMNAND8:
16837 case X86::ATOMNAND16:
16838 case X86::ATOMNAND32:
16839 case X86::ATOMNAND64:
16841 case X86::ATOMMAX8:
16842 case X86::ATOMMAX16:
16843 case X86::ATOMMAX32:
16844 case X86::ATOMMAX64:
16846 case X86::ATOMMIN8:
16847 case X86::ATOMMIN16:
16848 case X86::ATOMMIN32:
16849 case X86::ATOMMIN64:
16851 case X86::ATOMUMAX8:
16852 case X86::ATOMUMAX16:
16853 case X86::ATOMUMAX32:
16854 case X86::ATOMUMAX64:
16856 case X86::ATOMUMIN8:
16857 case X86::ATOMUMIN16:
16858 case X86::ATOMUMIN32:
16859 case X86::ATOMUMIN64:
16860 return EmitAtomicLoadArith(MI, BB);
16862 // This group does 64-bit operations on a 32-bit host.
16863 case X86::ATOMAND6432:
16864 case X86::ATOMOR6432:
16865 case X86::ATOMXOR6432:
16866 case X86::ATOMNAND6432:
16867 case X86::ATOMADD6432:
16868 case X86::ATOMSUB6432:
16869 case X86::ATOMMAX6432:
16870 case X86::ATOMMIN6432:
16871 case X86::ATOMUMAX6432:
16872 case X86::ATOMUMIN6432:
16873 case X86::ATOMSWAP6432:
16874 return EmitAtomicLoadArith6432(MI, BB);
16876 case X86::VASTART_SAVE_XMM_REGS:
16877 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16879 case X86::VAARG_64:
16880 return EmitVAARG64WithCustomInserter(MI, BB);
16882 case X86::EH_SjLj_SetJmp32:
16883 case X86::EH_SjLj_SetJmp64:
16884 return emitEHSjLjSetJmp(MI, BB);
16886 case X86::EH_SjLj_LongJmp32:
16887 case X86::EH_SjLj_LongJmp64:
16888 return emitEHSjLjLongJmp(MI, BB);
16890 case TargetOpcode::STACKMAP:
16891 case TargetOpcode::PATCHPOINT:
16892 return emitPatchPoint(MI, BB);
16894 case X86::VFMADDPDr213r:
16895 case X86::VFMADDPSr213r:
16896 case X86::VFMADDSDr213r:
16897 case X86::VFMADDSSr213r:
16898 case X86::VFMSUBPDr213r:
16899 case X86::VFMSUBPSr213r:
16900 case X86::VFMSUBSDr213r:
16901 case X86::VFMSUBSSr213r:
16902 case X86::VFNMADDPDr213r:
16903 case X86::VFNMADDPSr213r:
16904 case X86::VFNMADDSDr213r:
16905 case X86::VFNMADDSSr213r:
16906 case X86::VFNMSUBPDr213r:
16907 case X86::VFNMSUBPSr213r:
16908 case X86::VFNMSUBSDr213r:
16909 case X86::VFNMSUBSSr213r:
16910 case X86::VFMADDPDr213rY:
16911 case X86::VFMADDPSr213rY:
16912 case X86::VFMSUBPDr213rY:
16913 case X86::VFMSUBPSr213rY:
16914 case X86::VFNMADDPDr213rY:
16915 case X86::VFNMADDPSr213rY:
16916 case X86::VFNMSUBPDr213rY:
16917 case X86::VFNMSUBPSr213rY:
16918 return emitFMA3Instr(MI, BB);
16922 //===----------------------------------------------------------------------===//
16923 // X86 Optimization Hooks
16924 //===----------------------------------------------------------------------===//
16926 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16929 const SelectionDAG &DAG,
16930 unsigned Depth) const {
16931 unsigned BitWidth = KnownZero.getBitWidth();
16932 unsigned Opc = Op.getOpcode();
16933 assert((Opc >= ISD::BUILTIN_OP_END ||
16934 Opc == ISD::INTRINSIC_WO_CHAIN ||
16935 Opc == ISD::INTRINSIC_W_CHAIN ||
16936 Opc == ISD::INTRINSIC_VOID) &&
16937 "Should use MaskedValueIsZero if you don't know whether Op"
16938 " is a target node!");
16940 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16954 // These nodes' second result is a boolean.
16955 if (Op.getResNo() == 0)
16958 case X86ISD::SETCC:
16959 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16961 case ISD::INTRINSIC_WO_CHAIN: {
16962 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16963 unsigned NumLoBits = 0;
16966 case Intrinsic::x86_sse_movmsk_ps:
16967 case Intrinsic::x86_avx_movmsk_ps_256:
16968 case Intrinsic::x86_sse2_movmsk_pd:
16969 case Intrinsic::x86_avx_movmsk_pd_256:
16970 case Intrinsic::x86_mmx_pmovmskb:
16971 case Intrinsic::x86_sse2_pmovmskb_128:
16972 case Intrinsic::x86_avx2_pmovmskb: {
16973 // High bits of movmskp{s|d}, pmovmskb are known zero.
16975 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16976 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16977 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16978 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16979 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16980 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16981 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16982 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16984 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16993 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16995 const SelectionDAG &,
16996 unsigned Depth) const {
16997 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16998 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16999 return Op.getValueType().getScalarType().getSizeInBits();
17005 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17006 /// node is a GlobalAddress + offset.
17007 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17008 const GlobalValue* &GA,
17009 int64_t &Offset) const {
17010 if (N->getOpcode() == X86ISD::Wrapper) {
17011 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17012 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17013 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17017 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17020 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17021 /// same as extracting the high 128-bit part of 256-bit vector and then
17022 /// inserting the result into the low part of a new 256-bit vector
17023 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17024 EVT VT = SVOp->getValueType(0);
17025 unsigned NumElems = VT.getVectorNumElements();
17027 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17028 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17029 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17030 SVOp->getMaskElt(j) >= 0)
17036 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17037 /// same as extracting the low 128-bit part of 256-bit vector and then
17038 /// inserting the result into the high part of a new 256-bit vector
17039 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17040 EVT VT = SVOp->getValueType(0);
17041 unsigned NumElems = VT.getVectorNumElements();
17043 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17044 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17045 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17046 SVOp->getMaskElt(j) >= 0)
17052 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17053 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17054 TargetLowering::DAGCombinerInfo &DCI,
17055 const X86Subtarget* Subtarget) {
17057 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17058 SDValue V1 = SVOp->getOperand(0);
17059 SDValue V2 = SVOp->getOperand(1);
17060 EVT VT = SVOp->getValueType(0);
17061 unsigned NumElems = VT.getVectorNumElements();
17063 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17064 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17068 // V UNDEF BUILD_VECTOR UNDEF
17070 // CONCAT_VECTOR CONCAT_VECTOR
17073 // RESULT: V + zero extended
17075 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17076 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17077 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17080 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17083 // To match the shuffle mask, the first half of the mask should
17084 // be exactly the first vector, and all the rest a splat with the
17085 // first element of the second one.
17086 for (unsigned i = 0; i != NumElems/2; ++i)
17087 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17088 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17091 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17092 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17093 if (Ld->hasNUsesOfValue(1, 0)) {
17094 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17095 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17097 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17099 Ld->getPointerInfo(),
17100 Ld->getAlignment(),
17101 false/*isVolatile*/, true/*ReadMem*/,
17102 false/*WriteMem*/);
17104 // Make sure the newly-created LOAD is in the same position as Ld in
17105 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17106 // and update uses of Ld's output chain to use the TokenFactor.
17107 if (Ld->hasAnyUseOfValue(1)) {
17108 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17109 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17110 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17111 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17112 SDValue(ResNode.getNode(), 1));
17115 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17119 // Emit a zeroed vector and insert the desired subvector on its
17121 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17122 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17123 return DCI.CombineTo(N, InsV);
17126 //===--------------------------------------------------------------------===//
17127 // Combine some shuffles into subvector extracts and inserts:
17130 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17131 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17132 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17133 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17134 return DCI.CombineTo(N, InsV);
17137 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17138 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17139 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17140 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17141 return DCI.CombineTo(N, InsV);
17147 /// PerformShuffleCombine - Performs several different shuffle combines.
17148 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17149 TargetLowering::DAGCombinerInfo &DCI,
17150 const X86Subtarget *Subtarget) {
17152 EVT VT = N->getValueType(0);
17154 // Don't create instructions with illegal types after legalize types has run.
17155 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17156 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17159 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17160 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17161 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17162 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17164 // Only handle 128 wide vector from here on.
17165 if (!VT.is128BitVector())
17168 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17169 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17170 // consecutive, non-overlapping, and in the right order.
17171 SmallVector<SDValue, 16> Elts;
17172 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17173 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17175 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17178 /// PerformTruncateCombine - Converts truncate operation to
17179 /// a sequence of vector shuffle operations.
17180 /// It is possible when we truncate 256-bit vector to 128-bit vector
17181 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17182 TargetLowering::DAGCombinerInfo &DCI,
17183 const X86Subtarget *Subtarget) {
17187 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17188 /// specific shuffle of a load can be folded into a single element load.
17189 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17190 /// shuffles have been customed lowered so we need to handle those here.
17191 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17192 TargetLowering::DAGCombinerInfo &DCI) {
17193 if (DCI.isBeforeLegalizeOps())
17196 SDValue InVec = N->getOperand(0);
17197 SDValue EltNo = N->getOperand(1);
17199 if (!isa<ConstantSDNode>(EltNo))
17202 EVT VT = InVec.getValueType();
17204 bool HasShuffleIntoBitcast = false;
17205 if (InVec.getOpcode() == ISD::BITCAST) {
17206 // Don't duplicate a load with other uses.
17207 if (!InVec.hasOneUse())
17209 EVT BCVT = InVec.getOperand(0).getValueType();
17210 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17212 InVec = InVec.getOperand(0);
17213 HasShuffleIntoBitcast = true;
17216 if (!isTargetShuffle(InVec.getOpcode()))
17219 // Don't duplicate a load with other uses.
17220 if (!InVec.hasOneUse())
17223 SmallVector<int, 16> ShuffleMask;
17225 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17229 // Select the input vector, guarding against out of range extract vector.
17230 unsigned NumElems = VT.getVectorNumElements();
17231 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17232 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17233 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17234 : InVec.getOperand(1);
17236 // If inputs to shuffle are the same for both ops, then allow 2 uses
17237 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17239 if (LdNode.getOpcode() == ISD::BITCAST) {
17240 // Don't duplicate a load with other uses.
17241 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17244 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17245 LdNode = LdNode.getOperand(0);
17248 if (!ISD::isNormalLoad(LdNode.getNode()))
17251 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17253 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17256 if (HasShuffleIntoBitcast) {
17257 // If there's a bitcast before the shuffle, check if the load type and
17258 // alignment is valid.
17259 unsigned Align = LN0->getAlignment();
17260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17261 unsigned NewAlign = TLI.getDataLayout()->
17262 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17264 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17268 // All checks match so transform back to vector_shuffle so that DAG combiner
17269 // can finish the job
17272 // Create shuffle node taking into account the case that its a unary shuffle
17273 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17274 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17275 InVec.getOperand(0), Shuffle,
17277 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17278 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17282 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17283 /// generation and convert it from being a bunch of shuffles and extracts
17284 /// to a simple store and scalar loads to extract the elements.
17285 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17286 TargetLowering::DAGCombinerInfo &DCI) {
17287 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17288 if (NewOp.getNode())
17291 SDValue InputVector = N->getOperand(0);
17293 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17294 // from mmx to v2i32 has a single usage.
17295 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17296 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17297 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17298 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17299 N->getValueType(0),
17300 InputVector.getNode()->getOperand(0));
17302 // Only operate on vectors of 4 elements, where the alternative shuffling
17303 // gets to be more expensive.
17304 if (InputVector.getValueType() != MVT::v4i32)
17307 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17308 // single use which is a sign-extend or zero-extend, and all elements are
17310 SmallVector<SDNode *, 4> Uses;
17311 unsigned ExtractedElements = 0;
17312 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17313 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17314 if (UI.getUse().getResNo() != InputVector.getResNo())
17317 SDNode *Extract = *UI;
17318 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17321 if (Extract->getValueType(0) != MVT::i32)
17323 if (!Extract->hasOneUse())
17325 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17326 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17328 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17331 // Record which element was extracted.
17332 ExtractedElements |=
17333 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17335 Uses.push_back(Extract);
17338 // If not all the elements were used, this may not be worthwhile.
17339 if (ExtractedElements != 15)
17342 // Ok, we've now decided to do the transformation.
17343 SDLoc dl(InputVector);
17345 // Store the value to a temporary stack slot.
17346 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17347 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17348 MachinePointerInfo(), false, false, 0);
17350 // Replace each use (extract) with a load of the appropriate element.
17351 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17352 UE = Uses.end(); UI != UE; ++UI) {
17353 SDNode *Extract = *UI;
17355 // cOMpute the element's address.
17356 SDValue Idx = Extract->getOperand(1);
17358 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17359 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17361 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17363 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17364 StackPtr, OffsetVal);
17366 // Load the scalar.
17367 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17368 ScalarAddr, MachinePointerInfo(),
17369 false, false, false, 0);
17371 // Replace the exact with the load.
17372 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17375 // The replacement was made in place; don't return anything.
17379 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17380 static std::pair<unsigned, bool>
17381 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17382 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17383 if (!VT.isVector())
17384 return std::make_pair(0, false);
17386 bool NeedSplit = false;
17387 switch (VT.getSimpleVT().SimpleTy) {
17388 default: return std::make_pair(0, false);
17392 if (!Subtarget->hasAVX2())
17394 if (!Subtarget->hasAVX())
17395 return std::make_pair(0, false);
17400 if (!Subtarget->hasSSE2())
17401 return std::make_pair(0, false);
17404 // SSE2 has only a small subset of the operations.
17405 bool hasUnsigned = Subtarget->hasSSE41() ||
17406 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17407 bool hasSigned = Subtarget->hasSSE41() ||
17408 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17410 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17413 // Check for x CC y ? x : y.
17414 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17415 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17420 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17423 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17426 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17429 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17431 // Check for x CC y ? y : x -- a min/max with reversed arms.
17432 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17433 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17438 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17441 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17444 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17447 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17451 return std::make_pair(Opc, NeedSplit);
17454 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17456 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17457 TargetLowering::DAGCombinerInfo &DCI,
17458 const X86Subtarget *Subtarget) {
17460 SDValue Cond = N->getOperand(0);
17461 // Get the LHS/RHS of the select.
17462 SDValue LHS = N->getOperand(1);
17463 SDValue RHS = N->getOperand(2);
17464 EVT VT = LHS.getValueType();
17465 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17467 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17468 // instructions match the semantics of the common C idiom x<y?x:y but not
17469 // x<=y?x:y, because of how they handle negative zero (which can be
17470 // ignored in unsafe-math mode).
17471 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17472 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17473 (Subtarget->hasSSE2() ||
17474 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17475 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17477 unsigned Opcode = 0;
17478 // Check for x CC y ? x : y.
17479 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17480 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17484 // Converting this to a min would handle NaNs incorrectly, and swapping
17485 // the operands would cause it to handle comparisons between positive
17486 // and negative zero incorrectly.
17487 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17488 if (!DAG.getTarget().Options.UnsafeFPMath &&
17489 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17491 std::swap(LHS, RHS);
17493 Opcode = X86ISD::FMIN;
17496 // Converting this to a min would handle comparisons between positive
17497 // and negative zero incorrectly.
17498 if (!DAG.getTarget().Options.UnsafeFPMath &&
17499 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17501 Opcode = X86ISD::FMIN;
17504 // Converting this to a min would handle both negative zeros and NaNs
17505 // incorrectly, but we can swap the operands to fix both.
17506 std::swap(LHS, RHS);
17510 Opcode = X86ISD::FMIN;
17514 // Converting this to a max would handle comparisons between positive
17515 // and negative zero incorrectly.
17516 if (!DAG.getTarget().Options.UnsafeFPMath &&
17517 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17519 Opcode = X86ISD::FMAX;
17522 // Converting this to a max would handle NaNs incorrectly, and swapping
17523 // the operands would cause it to handle comparisons between positive
17524 // and negative zero incorrectly.
17525 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17526 if (!DAG.getTarget().Options.UnsafeFPMath &&
17527 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17529 std::swap(LHS, RHS);
17531 Opcode = X86ISD::FMAX;
17534 // Converting this to a max would handle both negative zeros and NaNs
17535 // incorrectly, but we can swap the operands to fix both.
17536 std::swap(LHS, RHS);
17540 Opcode = X86ISD::FMAX;
17543 // Check for x CC y ? y : x -- a min/max with reversed arms.
17544 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17545 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17549 // Converting this to a min would handle comparisons between positive
17550 // and negative zero incorrectly, and swapping the operands would
17551 // cause it to handle NaNs incorrectly.
17552 if (!DAG.getTarget().Options.UnsafeFPMath &&
17553 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17554 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17556 std::swap(LHS, RHS);
17558 Opcode = X86ISD::FMIN;
17561 // Converting this to a min would handle NaNs incorrectly.
17562 if (!DAG.getTarget().Options.UnsafeFPMath &&
17563 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17565 Opcode = X86ISD::FMIN;
17568 // Converting this to a min would handle both negative zeros and NaNs
17569 // incorrectly, but we can swap the operands to fix both.
17570 std::swap(LHS, RHS);
17574 Opcode = X86ISD::FMIN;
17578 // Converting this to a max would handle NaNs incorrectly.
17579 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17581 Opcode = X86ISD::FMAX;
17584 // Converting this to a max would handle comparisons between positive
17585 // and negative zero incorrectly, and swapping the operands would
17586 // cause it to handle NaNs incorrectly.
17587 if (!DAG.getTarget().Options.UnsafeFPMath &&
17588 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17589 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17591 std::swap(LHS, RHS);
17593 Opcode = X86ISD::FMAX;
17596 // Converting this to a max would handle both negative zeros and NaNs
17597 // incorrectly, but we can swap the operands to fix both.
17598 std::swap(LHS, RHS);
17602 Opcode = X86ISD::FMAX;
17608 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17611 EVT CondVT = Cond.getValueType();
17612 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17613 CondVT.getVectorElementType() == MVT::i1) {
17614 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17615 // lowering on AVX-512. In this case we convert it to
17616 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17617 // The same situation for all 128 and 256-bit vectors of i8 and i16
17618 EVT OpVT = LHS.getValueType();
17619 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17620 (OpVT.getVectorElementType() == MVT::i8 ||
17621 OpVT.getVectorElementType() == MVT::i16)) {
17622 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17623 DCI.AddToWorklist(Cond.getNode());
17624 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17627 // If this is a select between two integer constants, try to do some
17629 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17630 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17631 // Don't do this for crazy integer types.
17632 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17633 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17634 // so that TrueC (the true value) is larger than FalseC.
17635 bool NeedsCondInvert = false;
17637 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17638 // Efficiently invertible.
17639 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17640 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17641 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17642 NeedsCondInvert = true;
17643 std::swap(TrueC, FalseC);
17646 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17647 if (FalseC->getAPIntValue() == 0 &&
17648 TrueC->getAPIntValue().isPowerOf2()) {
17649 if (NeedsCondInvert) // Invert the condition if needed.
17650 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17651 DAG.getConstant(1, Cond.getValueType()));
17653 // Zero extend the condition if needed.
17654 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17656 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17657 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17658 DAG.getConstant(ShAmt, MVT::i8));
17661 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17662 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17663 if (NeedsCondInvert) // Invert the condition if needed.
17664 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17665 DAG.getConstant(1, Cond.getValueType()));
17667 // Zero extend the condition if needed.
17668 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17669 FalseC->getValueType(0), Cond);
17670 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17671 SDValue(FalseC, 0));
17674 // Optimize cases that will turn into an LEA instruction. This requires
17675 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17676 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17677 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17678 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17680 bool isFastMultiplier = false;
17682 switch ((unsigned char)Diff) {
17684 case 1: // result = add base, cond
17685 case 2: // result = lea base( , cond*2)
17686 case 3: // result = lea base(cond, cond*2)
17687 case 4: // result = lea base( , cond*4)
17688 case 5: // result = lea base(cond, cond*4)
17689 case 8: // result = lea base( , cond*8)
17690 case 9: // result = lea base(cond, cond*8)
17691 isFastMultiplier = true;
17696 if (isFastMultiplier) {
17697 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17698 if (NeedsCondInvert) // Invert the condition if needed.
17699 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17700 DAG.getConstant(1, Cond.getValueType()));
17702 // Zero extend the condition if needed.
17703 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17705 // Scale the condition by the difference.
17707 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17708 DAG.getConstant(Diff, Cond.getValueType()));
17710 // Add the base if non-zero.
17711 if (FalseC->getAPIntValue() != 0)
17712 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17713 SDValue(FalseC, 0));
17720 // Canonicalize max and min:
17721 // (x > y) ? x : y -> (x >= y) ? x : y
17722 // (x < y) ? x : y -> (x <= y) ? x : y
17723 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17724 // the need for an extra compare
17725 // against zero. e.g.
17726 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17728 // testl %edi, %edi
17730 // cmovgl %edi, %eax
17734 // cmovsl %eax, %edi
17735 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17736 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17737 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17738 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17743 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17744 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17745 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17746 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17751 // Early exit check
17752 if (!TLI.isTypeLegal(VT))
17755 // Match VSELECTs into subs with unsigned saturation.
17756 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17757 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17758 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17759 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17760 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17762 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17763 // left side invert the predicate to simplify logic below.
17765 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17767 CC = ISD::getSetCCInverse(CC, true);
17768 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17772 if (Other.getNode() && Other->getNumOperands() == 2 &&
17773 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17774 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17775 SDValue CondRHS = Cond->getOperand(1);
17777 // Look for a general sub with unsigned saturation first.
17778 // x >= y ? x-y : 0 --> subus x, y
17779 // x > y ? x-y : 0 --> subus x, y
17780 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17781 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17782 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17784 // If the RHS is a constant we have to reverse the const canonicalization.
17785 // x > C-1 ? x+-C : 0 --> subus x, C
17786 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17787 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17788 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17789 if (CondRHS.getConstantOperandVal(0) == -A-1)
17790 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17791 DAG.getConstant(-A, VT));
17794 // Another special case: If C was a sign bit, the sub has been
17795 // canonicalized into a xor.
17796 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17797 // it's safe to decanonicalize the xor?
17798 // x s< 0 ? x^C : 0 --> subus x, C
17799 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17800 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17801 isSplatVector(OpRHS.getNode())) {
17802 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17804 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17809 // Try to match a min/max vector operation.
17810 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17811 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17812 unsigned Opc = ret.first;
17813 bool NeedSplit = ret.second;
17815 if (Opc && NeedSplit) {
17816 unsigned NumElems = VT.getVectorNumElements();
17817 // Extract the LHS vectors
17818 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17819 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17821 // Extract the RHS vectors
17822 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17823 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17825 // Create min/max for each subvector
17826 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17827 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17829 // Merge the result
17830 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17832 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17835 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17836 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17837 // Check if SETCC has already been promoted
17838 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17839 // Check that condition value type matches vselect operand type
17842 assert(Cond.getValueType().isVector() &&
17843 "vector select expects a vector selector!");
17845 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17846 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17848 if (!TValIsAllOnes && !FValIsAllZeros) {
17849 // Try invert the condition if true value is not all 1s and false value
17851 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17852 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17854 if (TValIsAllZeros || FValIsAllOnes) {
17855 SDValue CC = Cond.getOperand(2);
17856 ISD::CondCode NewCC =
17857 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17858 Cond.getOperand(0).getValueType().isInteger());
17859 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17860 std::swap(LHS, RHS);
17861 TValIsAllOnes = FValIsAllOnes;
17862 FValIsAllZeros = TValIsAllZeros;
17866 if (TValIsAllOnes || FValIsAllZeros) {
17869 if (TValIsAllOnes && FValIsAllZeros)
17871 else if (TValIsAllOnes)
17872 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17873 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17874 else if (FValIsAllZeros)
17875 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17876 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17878 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17882 // Try to fold this VSELECT into a MOVSS/MOVSD
17883 if (N->getOpcode() == ISD::VSELECT &&
17884 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17885 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17886 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17887 bool CanFold = false;
17888 unsigned NumElems = Cond.getNumOperands();
17892 if (isZero(Cond.getOperand(0))) {
17895 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17896 // fold (vselect <0,-1> -> (movsd A, B)
17897 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17898 CanFold = isAllOnes(Cond.getOperand(i));
17899 } else if (isAllOnes(Cond.getOperand(0))) {
17903 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17904 // fold (vselect <-1,0> -> (movsd B, A)
17905 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17906 CanFold = isZero(Cond.getOperand(i));
17910 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17911 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17912 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17915 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17916 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17917 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17918 // (v2i64 (bitcast B)))))
17920 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17921 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17922 // (v2f64 (bitcast B)))))
17924 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17925 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17926 // (v2i64 (bitcast A)))))
17928 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17929 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17930 // (v2f64 (bitcast A)))))
17932 CanFold = (isZero(Cond.getOperand(0)) &&
17933 isZero(Cond.getOperand(1)) &&
17934 isAllOnes(Cond.getOperand(2)) &&
17935 isAllOnes(Cond.getOperand(3)));
17937 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17938 isAllOnes(Cond.getOperand(1)) &&
17939 isZero(Cond.getOperand(2)) &&
17940 isZero(Cond.getOperand(3))) {
17942 std::swap(LHS, RHS);
17946 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17947 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17948 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17949 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17951 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17957 // If we know that this node is legal then we know that it is going to be
17958 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17959 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17960 // to simplify previous instructions.
17961 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17962 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17963 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17965 // Don't optimize vector selects that map to mask-registers.
17969 // Check all uses of that condition operand to check whether it will be
17970 // consumed by non-BLEND instructions, which may depend on all bits are set
17972 for (SDNode::use_iterator I = Cond->use_begin(),
17973 E = Cond->use_end(); I != E; ++I)
17974 if (I->getOpcode() != ISD::VSELECT)
17975 // TODO: Add other opcodes eventually lowered into BLEND.
17978 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17979 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17981 APInt KnownZero, KnownOne;
17982 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17983 DCI.isBeforeLegalizeOps());
17984 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17985 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17986 DCI.CommitTargetLoweringOpt(TLO);
17992 // Check whether a boolean test is testing a boolean value generated by
17993 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17996 // Simplify the following patterns:
17997 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17998 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17999 // to (Op EFLAGS Cond)
18001 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18002 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18003 // to (Op EFLAGS !Cond)
18005 // where Op could be BRCOND or CMOV.
18007 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18008 // Quit if not CMP and SUB with its value result used.
18009 if (Cmp.getOpcode() != X86ISD::CMP &&
18010 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18013 // Quit if not used as a boolean value.
18014 if (CC != X86::COND_E && CC != X86::COND_NE)
18017 // Check CMP operands. One of them should be 0 or 1 and the other should be
18018 // an SetCC or extended from it.
18019 SDValue Op1 = Cmp.getOperand(0);
18020 SDValue Op2 = Cmp.getOperand(1);
18023 const ConstantSDNode* C = nullptr;
18024 bool needOppositeCond = (CC == X86::COND_E);
18025 bool checkAgainstTrue = false; // Is it a comparison against 1?
18027 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18029 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18031 else // Quit if all operands are not constants.
18034 if (C->getZExtValue() == 1) {
18035 needOppositeCond = !needOppositeCond;
18036 checkAgainstTrue = true;
18037 } else if (C->getZExtValue() != 0)
18038 // Quit if the constant is neither 0 or 1.
18041 bool truncatedToBoolWithAnd = false;
18042 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18043 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18044 SetCC.getOpcode() == ISD::TRUNCATE ||
18045 SetCC.getOpcode() == ISD::AND) {
18046 if (SetCC.getOpcode() == ISD::AND) {
18048 ConstantSDNode *CS;
18049 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18050 CS->getZExtValue() == 1)
18052 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18053 CS->getZExtValue() == 1)
18057 SetCC = SetCC.getOperand(OpIdx);
18058 truncatedToBoolWithAnd = true;
18060 SetCC = SetCC.getOperand(0);
18063 switch (SetCC.getOpcode()) {
18064 case X86ISD::SETCC_CARRY:
18065 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18066 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18067 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18068 // truncated to i1 using 'and'.
18069 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18071 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18072 "Invalid use of SETCC_CARRY!");
18074 case X86ISD::SETCC:
18075 // Set the condition code or opposite one if necessary.
18076 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18077 if (needOppositeCond)
18078 CC = X86::GetOppositeBranchCondition(CC);
18079 return SetCC.getOperand(1);
18080 case X86ISD::CMOV: {
18081 // Check whether false/true value has canonical one, i.e. 0 or 1.
18082 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18083 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18084 // Quit if true value is not a constant.
18087 // Quit if false value is not a constant.
18089 SDValue Op = SetCC.getOperand(0);
18090 // Skip 'zext' or 'trunc' node.
18091 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18092 Op.getOpcode() == ISD::TRUNCATE)
18093 Op = Op.getOperand(0);
18094 // A special case for rdrand/rdseed, where 0 is set if false cond is
18096 if ((Op.getOpcode() != X86ISD::RDRAND &&
18097 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18100 // Quit if false value is not the constant 0 or 1.
18101 bool FValIsFalse = true;
18102 if (FVal && FVal->getZExtValue() != 0) {
18103 if (FVal->getZExtValue() != 1)
18105 // If FVal is 1, opposite cond is needed.
18106 needOppositeCond = !needOppositeCond;
18107 FValIsFalse = false;
18109 // Quit if TVal is not the constant opposite of FVal.
18110 if (FValIsFalse && TVal->getZExtValue() != 1)
18112 if (!FValIsFalse && TVal->getZExtValue() != 0)
18114 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18115 if (needOppositeCond)
18116 CC = X86::GetOppositeBranchCondition(CC);
18117 return SetCC.getOperand(3);
18124 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18125 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18126 TargetLowering::DAGCombinerInfo &DCI,
18127 const X86Subtarget *Subtarget) {
18130 // If the flag operand isn't dead, don't touch this CMOV.
18131 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18134 SDValue FalseOp = N->getOperand(0);
18135 SDValue TrueOp = N->getOperand(1);
18136 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18137 SDValue Cond = N->getOperand(3);
18139 if (CC == X86::COND_E || CC == X86::COND_NE) {
18140 switch (Cond.getOpcode()) {
18144 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18145 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18146 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18152 Flags = checkBoolTestSetCCCombine(Cond, CC);
18153 if (Flags.getNode() &&
18154 // Extra check as FCMOV only supports a subset of X86 cond.
18155 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18156 SDValue Ops[] = { FalseOp, TrueOp,
18157 DAG.getConstant(CC, MVT::i8), Flags };
18158 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18161 // If this is a select between two integer constants, try to do some
18162 // optimizations. Note that the operands are ordered the opposite of SELECT
18164 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18165 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18166 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18167 // larger than FalseC (the false value).
18168 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18169 CC = X86::GetOppositeBranchCondition(CC);
18170 std::swap(TrueC, FalseC);
18171 std::swap(TrueOp, FalseOp);
18174 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18175 // This is efficient for any integer data type (including i8/i16) and
18177 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18178 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18179 DAG.getConstant(CC, MVT::i8), Cond);
18181 // Zero extend the condition if needed.
18182 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18184 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18185 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18186 DAG.getConstant(ShAmt, MVT::i8));
18187 if (N->getNumValues() == 2) // Dead flag value?
18188 return DCI.CombineTo(N, Cond, SDValue());
18192 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18193 // for any integer data type, including i8/i16.
18194 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18195 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18196 DAG.getConstant(CC, MVT::i8), Cond);
18198 // Zero extend the condition if needed.
18199 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18200 FalseC->getValueType(0), Cond);
18201 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18202 SDValue(FalseC, 0));
18204 if (N->getNumValues() == 2) // Dead flag value?
18205 return DCI.CombineTo(N, Cond, SDValue());
18209 // Optimize cases that will turn into an LEA instruction. This requires
18210 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18211 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18212 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18213 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18215 bool isFastMultiplier = false;
18217 switch ((unsigned char)Diff) {
18219 case 1: // result = add base, cond
18220 case 2: // result = lea base( , cond*2)
18221 case 3: // result = lea base(cond, cond*2)
18222 case 4: // result = lea base( , cond*4)
18223 case 5: // result = lea base(cond, cond*4)
18224 case 8: // result = lea base( , cond*8)
18225 case 9: // result = lea base(cond, cond*8)
18226 isFastMultiplier = true;
18231 if (isFastMultiplier) {
18232 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18233 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18234 DAG.getConstant(CC, MVT::i8), Cond);
18235 // Zero extend the condition if needed.
18236 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18238 // Scale the condition by the difference.
18240 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18241 DAG.getConstant(Diff, Cond.getValueType()));
18243 // Add the base if non-zero.
18244 if (FalseC->getAPIntValue() != 0)
18245 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18246 SDValue(FalseC, 0));
18247 if (N->getNumValues() == 2) // Dead flag value?
18248 return DCI.CombineTo(N, Cond, SDValue());
18255 // Handle these cases:
18256 // (select (x != c), e, c) -> select (x != c), e, x),
18257 // (select (x == c), c, e) -> select (x == c), x, e)
18258 // where the c is an integer constant, and the "select" is the combination
18259 // of CMOV and CMP.
18261 // The rationale for this change is that the conditional-move from a constant
18262 // needs two instructions, however, conditional-move from a register needs
18263 // only one instruction.
18265 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18266 // some instruction-combining opportunities. This opt needs to be
18267 // postponed as late as possible.
18269 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18270 // the DCI.xxxx conditions are provided to postpone the optimization as
18271 // late as possible.
18273 ConstantSDNode *CmpAgainst = nullptr;
18274 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18275 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18276 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18278 if (CC == X86::COND_NE &&
18279 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18280 CC = X86::GetOppositeBranchCondition(CC);
18281 std::swap(TrueOp, FalseOp);
18284 if (CC == X86::COND_E &&
18285 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18286 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18287 DAG.getConstant(CC, MVT::i8), Cond };
18288 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18296 /// PerformMulCombine - Optimize a single multiply with constant into two
18297 /// in order to implement it with two cheaper instructions, e.g.
18298 /// LEA + SHL, LEA + LEA.
18299 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18300 TargetLowering::DAGCombinerInfo &DCI) {
18301 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18304 EVT VT = N->getValueType(0);
18305 if (VT != MVT::i64)
18308 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18311 uint64_t MulAmt = C->getZExtValue();
18312 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18315 uint64_t MulAmt1 = 0;
18316 uint64_t MulAmt2 = 0;
18317 if ((MulAmt % 9) == 0) {
18319 MulAmt2 = MulAmt / 9;
18320 } else if ((MulAmt % 5) == 0) {
18322 MulAmt2 = MulAmt / 5;
18323 } else if ((MulAmt % 3) == 0) {
18325 MulAmt2 = MulAmt / 3;
18328 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18331 if (isPowerOf2_64(MulAmt2) &&
18332 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18333 // If second multiplifer is pow2, issue it first. We want the multiply by
18334 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18336 std::swap(MulAmt1, MulAmt2);
18339 if (isPowerOf2_64(MulAmt1))
18340 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18341 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18343 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18344 DAG.getConstant(MulAmt1, VT));
18346 if (isPowerOf2_64(MulAmt2))
18347 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18348 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18350 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18351 DAG.getConstant(MulAmt2, VT));
18353 // Do not add new nodes to DAG combiner worklist.
18354 DCI.CombineTo(N, NewMul, false);
18359 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18360 SDValue N0 = N->getOperand(0);
18361 SDValue N1 = N->getOperand(1);
18362 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18363 EVT VT = N0.getValueType();
18365 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18366 // since the result of setcc_c is all zero's or all ones.
18367 if (VT.isInteger() && !VT.isVector() &&
18368 N1C && N0.getOpcode() == ISD::AND &&
18369 N0.getOperand(1).getOpcode() == ISD::Constant) {
18370 SDValue N00 = N0.getOperand(0);
18371 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18372 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18373 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18374 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18375 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18376 APInt ShAmt = N1C->getAPIntValue();
18377 Mask = Mask.shl(ShAmt);
18379 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18380 N00, DAG.getConstant(Mask, VT));
18384 // Hardware support for vector shifts is sparse which makes us scalarize the
18385 // vector operations in many cases. Also, on sandybridge ADD is faster than
18387 // (shl V, 1) -> add V,V
18388 if (isSplatVector(N1.getNode())) {
18389 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18390 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18391 // We shift all of the values by one. In many cases we do not have
18392 // hardware support for this operation. This is better expressed as an ADD
18394 if (N1C && (1 == N1C->getZExtValue())) {
18395 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18402 /// \brief Returns a vector of 0s if the node in input is a vector logical
18403 /// shift by a constant amount which is known to be bigger than or equal
18404 /// to the vector element size in bits.
18405 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18406 const X86Subtarget *Subtarget) {
18407 EVT VT = N->getValueType(0);
18409 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18410 (!Subtarget->hasInt256() ||
18411 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18414 SDValue Amt = N->getOperand(1);
18416 if (isSplatVector(Amt.getNode())) {
18417 SDValue SclrAmt = Amt->getOperand(0);
18418 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18419 APInt ShiftAmt = C->getAPIntValue();
18420 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18422 // SSE2/AVX2 logical shifts always return a vector of 0s
18423 // if the shift amount is bigger than or equal to
18424 // the element size. The constant shift amount will be
18425 // encoded as a 8-bit immediate.
18426 if (ShiftAmt.trunc(8).uge(MaxAmount))
18427 return getZeroVector(VT, Subtarget, DAG, DL);
18434 /// PerformShiftCombine - Combine shifts.
18435 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18436 TargetLowering::DAGCombinerInfo &DCI,
18437 const X86Subtarget *Subtarget) {
18438 if (N->getOpcode() == ISD::SHL) {
18439 SDValue V = PerformSHLCombine(N, DAG);
18440 if (V.getNode()) return V;
18443 if (N->getOpcode() != ISD::SRA) {
18444 // Try to fold this logical shift into a zero vector.
18445 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18446 if (V.getNode()) return V;
18452 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18453 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18454 // and friends. Likewise for OR -> CMPNEQSS.
18455 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18456 TargetLowering::DAGCombinerInfo &DCI,
18457 const X86Subtarget *Subtarget) {
18460 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18461 // we're requiring SSE2 for both.
18462 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18463 SDValue N0 = N->getOperand(0);
18464 SDValue N1 = N->getOperand(1);
18465 SDValue CMP0 = N0->getOperand(1);
18466 SDValue CMP1 = N1->getOperand(1);
18469 // The SETCCs should both refer to the same CMP.
18470 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18473 SDValue CMP00 = CMP0->getOperand(0);
18474 SDValue CMP01 = CMP0->getOperand(1);
18475 EVT VT = CMP00.getValueType();
18477 if (VT == MVT::f32 || VT == MVT::f64) {
18478 bool ExpectingFlags = false;
18479 // Check for any users that want flags:
18480 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18481 !ExpectingFlags && UI != UE; ++UI)
18482 switch (UI->getOpcode()) {
18487 ExpectingFlags = true;
18489 case ISD::CopyToReg:
18490 case ISD::SIGN_EXTEND:
18491 case ISD::ZERO_EXTEND:
18492 case ISD::ANY_EXTEND:
18496 if (!ExpectingFlags) {
18497 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18498 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18500 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18501 X86::CondCode tmp = cc0;
18506 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18507 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18508 // FIXME: need symbolic constants for these magic numbers.
18509 // See X86ATTInstPrinter.cpp:printSSECC().
18510 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18511 if (Subtarget->hasAVX512()) {
18512 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18513 CMP01, DAG.getConstant(x86cc, MVT::i8));
18514 if (N->getValueType(0) != MVT::i1)
18515 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18519 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18520 CMP00.getValueType(), CMP00, CMP01,
18521 DAG.getConstant(x86cc, MVT::i8));
18523 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18524 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18526 if (is64BitFP && !Subtarget->is64Bit()) {
18527 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18528 // 64-bit integer, since that's not a legal type. Since
18529 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18530 // bits, but can do this little dance to extract the lowest 32 bits
18531 // and work with those going forward.
18532 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18534 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18536 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18537 Vector32, DAG.getIntPtrConstant(0));
18541 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18542 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18543 DAG.getConstant(1, IntVT));
18544 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18545 return OneBitOfTruth;
18553 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18554 /// so it can be folded inside ANDNP.
18555 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18556 EVT VT = N->getValueType(0);
18558 // Match direct AllOnes for 128 and 256-bit vectors
18559 if (ISD::isBuildVectorAllOnes(N))
18562 // Look through a bit convert.
18563 if (N->getOpcode() == ISD::BITCAST)
18564 N = N->getOperand(0).getNode();
18566 // Sometimes the operand may come from a insert_subvector building a 256-bit
18568 if (VT.is256BitVector() &&
18569 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18570 SDValue V1 = N->getOperand(0);
18571 SDValue V2 = N->getOperand(1);
18573 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18574 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18575 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18576 ISD::isBuildVectorAllOnes(V2.getNode()))
18583 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18584 // register. In most cases we actually compare or select YMM-sized registers
18585 // and mixing the two types creates horrible code. This method optimizes
18586 // some of the transition sequences.
18587 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18588 TargetLowering::DAGCombinerInfo &DCI,
18589 const X86Subtarget *Subtarget) {
18590 EVT VT = N->getValueType(0);
18591 if (!VT.is256BitVector())
18594 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18595 N->getOpcode() == ISD::ZERO_EXTEND ||
18596 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18598 SDValue Narrow = N->getOperand(0);
18599 EVT NarrowVT = Narrow->getValueType(0);
18600 if (!NarrowVT.is128BitVector())
18603 if (Narrow->getOpcode() != ISD::XOR &&
18604 Narrow->getOpcode() != ISD::AND &&
18605 Narrow->getOpcode() != ISD::OR)
18608 SDValue N0 = Narrow->getOperand(0);
18609 SDValue N1 = Narrow->getOperand(1);
18612 // The Left side has to be a trunc.
18613 if (N0.getOpcode() != ISD::TRUNCATE)
18616 // The type of the truncated inputs.
18617 EVT WideVT = N0->getOperand(0)->getValueType(0);
18621 // The right side has to be a 'trunc' or a constant vector.
18622 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18623 bool RHSConst = (isSplatVector(N1.getNode()) &&
18624 isa<ConstantSDNode>(N1->getOperand(0)));
18625 if (!RHSTrunc && !RHSConst)
18628 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18630 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18633 // Set N0 and N1 to hold the inputs to the new wide operation.
18634 N0 = N0->getOperand(0);
18636 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18637 N1->getOperand(0));
18638 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18639 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18640 } else if (RHSTrunc) {
18641 N1 = N1->getOperand(0);
18644 // Generate the wide operation.
18645 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18646 unsigned Opcode = N->getOpcode();
18648 case ISD::ANY_EXTEND:
18650 case ISD::ZERO_EXTEND: {
18651 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18652 APInt Mask = APInt::getAllOnesValue(InBits);
18653 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18654 return DAG.getNode(ISD::AND, DL, VT,
18655 Op, DAG.getConstant(Mask, VT));
18657 case ISD::SIGN_EXTEND:
18658 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18659 Op, DAG.getValueType(NarrowVT));
18661 llvm_unreachable("Unexpected opcode");
18665 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18666 TargetLowering::DAGCombinerInfo &DCI,
18667 const X86Subtarget *Subtarget) {
18668 EVT VT = N->getValueType(0);
18669 if (DCI.isBeforeLegalizeOps())
18672 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18676 // Create BEXTR instructions
18677 // BEXTR is ((X >> imm) & (2**size-1))
18678 if (VT == MVT::i32 || VT == MVT::i64) {
18679 SDValue N0 = N->getOperand(0);
18680 SDValue N1 = N->getOperand(1);
18683 // Check for BEXTR.
18684 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18685 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18686 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18687 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18688 if (MaskNode && ShiftNode) {
18689 uint64_t Mask = MaskNode->getZExtValue();
18690 uint64_t Shift = ShiftNode->getZExtValue();
18691 if (isMask_64(Mask)) {
18692 uint64_t MaskSize = CountPopulation_64(Mask);
18693 if (Shift + MaskSize <= VT.getSizeInBits())
18694 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18695 DAG.getConstant(Shift | (MaskSize << 8), VT));
18703 // Want to form ANDNP nodes:
18704 // 1) In the hopes of then easily combining them with OR and AND nodes
18705 // to form PBLEND/PSIGN.
18706 // 2) To match ANDN packed intrinsics
18707 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18710 SDValue N0 = N->getOperand(0);
18711 SDValue N1 = N->getOperand(1);
18714 // Check LHS for vnot
18715 if (N0.getOpcode() == ISD::XOR &&
18716 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18717 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18718 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18720 // Check RHS for vnot
18721 if (N1.getOpcode() == ISD::XOR &&
18722 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18723 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18724 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18729 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18730 TargetLowering::DAGCombinerInfo &DCI,
18731 const X86Subtarget *Subtarget) {
18732 if (DCI.isBeforeLegalizeOps())
18735 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18739 SDValue N0 = N->getOperand(0);
18740 SDValue N1 = N->getOperand(1);
18741 EVT VT = N->getValueType(0);
18743 // look for psign/blend
18744 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18745 if (!Subtarget->hasSSSE3() ||
18746 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18749 // Canonicalize pandn to RHS
18750 if (N0.getOpcode() == X86ISD::ANDNP)
18752 // or (and (m, y), (pandn m, x))
18753 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18754 SDValue Mask = N1.getOperand(0);
18755 SDValue X = N1.getOperand(1);
18757 if (N0.getOperand(0) == Mask)
18758 Y = N0.getOperand(1);
18759 if (N0.getOperand(1) == Mask)
18760 Y = N0.getOperand(0);
18762 // Check to see if the mask appeared in both the AND and ANDNP and
18766 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18767 // Look through mask bitcast.
18768 if (Mask.getOpcode() == ISD::BITCAST)
18769 Mask = Mask.getOperand(0);
18770 if (X.getOpcode() == ISD::BITCAST)
18771 X = X.getOperand(0);
18772 if (Y.getOpcode() == ISD::BITCAST)
18773 Y = Y.getOperand(0);
18775 EVT MaskVT = Mask.getValueType();
18777 // Validate that the Mask operand is a vector sra node.
18778 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18779 // there is no psrai.b
18780 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18781 unsigned SraAmt = ~0;
18782 if (Mask.getOpcode() == ISD::SRA) {
18783 SDValue Amt = Mask.getOperand(1);
18784 if (isSplatVector(Amt.getNode())) {
18785 SDValue SclrAmt = Amt->getOperand(0);
18786 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18787 SraAmt = C->getZExtValue();
18789 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18790 SDValue SraC = Mask.getOperand(1);
18791 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18793 if ((SraAmt + 1) != EltBits)
18798 // Now we know we at least have a plendvb with the mask val. See if
18799 // we can form a psignb/w/d.
18800 // psign = x.type == y.type == mask.type && y = sub(0, x);
18801 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18802 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18803 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18804 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18805 "Unsupported VT for PSIGN");
18806 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18807 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18809 // PBLENDVB only available on SSE 4.1
18810 if (!Subtarget->hasSSE41())
18813 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18815 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18816 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18817 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18818 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18819 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18823 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18826 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18827 MachineFunction &MF = DAG.getMachineFunction();
18828 bool OptForSize = MF.getFunction()->getAttributes().
18829 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18831 // SHLD/SHRD instructions have lower register pressure, but on some
18832 // platforms they have higher latency than the equivalent
18833 // series of shifts/or that would otherwise be generated.
18834 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18835 // have higher latencies and we are not optimizing for size.
18836 if (!OptForSize && Subtarget->isSHLDSlow())
18839 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18841 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18843 if (!N0.hasOneUse() || !N1.hasOneUse())
18846 SDValue ShAmt0 = N0.getOperand(1);
18847 if (ShAmt0.getValueType() != MVT::i8)
18849 SDValue ShAmt1 = N1.getOperand(1);
18850 if (ShAmt1.getValueType() != MVT::i8)
18852 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18853 ShAmt0 = ShAmt0.getOperand(0);
18854 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18855 ShAmt1 = ShAmt1.getOperand(0);
18858 unsigned Opc = X86ISD::SHLD;
18859 SDValue Op0 = N0.getOperand(0);
18860 SDValue Op1 = N1.getOperand(0);
18861 if (ShAmt0.getOpcode() == ISD::SUB) {
18862 Opc = X86ISD::SHRD;
18863 std::swap(Op0, Op1);
18864 std::swap(ShAmt0, ShAmt1);
18867 unsigned Bits = VT.getSizeInBits();
18868 if (ShAmt1.getOpcode() == ISD::SUB) {
18869 SDValue Sum = ShAmt1.getOperand(0);
18870 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18871 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18872 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18873 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18874 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18875 return DAG.getNode(Opc, DL, VT,
18877 DAG.getNode(ISD::TRUNCATE, DL,
18880 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18881 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18883 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18884 return DAG.getNode(Opc, DL, VT,
18885 N0.getOperand(0), N1.getOperand(0),
18886 DAG.getNode(ISD::TRUNCATE, DL,
18893 // Generate NEG and CMOV for integer abs.
18894 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18895 EVT VT = N->getValueType(0);
18897 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18898 // 8-bit integer abs to NEG and CMOV.
18899 if (VT.isInteger() && VT.getSizeInBits() == 8)
18902 SDValue N0 = N->getOperand(0);
18903 SDValue N1 = N->getOperand(1);
18906 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18907 // and change it to SUB and CMOV.
18908 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18909 N0.getOpcode() == ISD::ADD &&
18910 N0.getOperand(1) == N1 &&
18911 N1.getOpcode() == ISD::SRA &&
18912 N1.getOperand(0) == N0.getOperand(0))
18913 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18914 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18915 // Generate SUB & CMOV.
18916 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18917 DAG.getConstant(0, VT), N0.getOperand(0));
18919 SDValue Ops[] = { N0.getOperand(0), Neg,
18920 DAG.getConstant(X86::COND_GE, MVT::i8),
18921 SDValue(Neg.getNode(), 1) };
18922 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18927 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18928 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18929 TargetLowering::DAGCombinerInfo &DCI,
18930 const X86Subtarget *Subtarget) {
18931 if (DCI.isBeforeLegalizeOps())
18934 if (Subtarget->hasCMov()) {
18935 SDValue RV = performIntegerAbsCombine(N, DAG);
18943 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18944 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18945 TargetLowering::DAGCombinerInfo &DCI,
18946 const X86Subtarget *Subtarget) {
18947 LoadSDNode *Ld = cast<LoadSDNode>(N);
18948 EVT RegVT = Ld->getValueType(0);
18949 EVT MemVT = Ld->getMemoryVT();
18951 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18952 unsigned RegSz = RegVT.getSizeInBits();
18954 // On Sandybridge unaligned 256bit loads are inefficient.
18955 ISD::LoadExtType Ext = Ld->getExtensionType();
18956 unsigned Alignment = Ld->getAlignment();
18957 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18958 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18959 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18960 unsigned NumElems = RegVT.getVectorNumElements();
18964 SDValue Ptr = Ld->getBasePtr();
18965 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18967 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18969 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18970 Ld->getPointerInfo(), Ld->isVolatile(),
18971 Ld->isNonTemporal(), Ld->isInvariant(),
18973 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18974 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18975 Ld->getPointerInfo(), Ld->isVolatile(),
18976 Ld->isNonTemporal(), Ld->isInvariant(),
18977 std::min(16U, Alignment));
18978 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18980 Load2.getValue(1));
18982 SDValue NewVec = DAG.getUNDEF(RegVT);
18983 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18984 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18985 return DCI.CombineTo(N, NewVec, TF, true);
18988 // If this is a vector EXT Load then attempt to optimize it using a
18989 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18990 // expansion is still better than scalar code.
18991 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18992 // emit a shuffle and a arithmetic shift.
18993 // TODO: It is possible to support ZExt by zeroing the undef values
18994 // during the shuffle phase or after the shuffle.
18995 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18996 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18997 assert(MemVT != RegVT && "Cannot extend to the same type");
18998 assert(MemVT.isVector() && "Must load a vector from memory");
19000 unsigned NumElems = RegVT.getVectorNumElements();
19001 unsigned MemSz = MemVT.getSizeInBits();
19002 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19004 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19007 // All sizes must be a power of two.
19008 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19011 // Attempt to load the original value using scalar loads.
19012 // Find the largest scalar type that divides the total loaded size.
19013 MVT SclrLoadTy = MVT::i8;
19014 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19015 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19016 MVT Tp = (MVT::SimpleValueType)tp;
19017 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19022 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19023 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19025 SclrLoadTy = MVT::f64;
19027 // Calculate the number of scalar loads that we need to perform
19028 // in order to load our vector from memory.
19029 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19030 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19033 unsigned loadRegZize = RegSz;
19034 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19037 // Represent our vector as a sequence of elements which are the
19038 // largest scalar that we can load.
19039 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19040 loadRegZize/SclrLoadTy.getSizeInBits());
19042 // Represent the data using the same element type that is stored in
19043 // memory. In practice, we ''widen'' MemVT.
19045 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19046 loadRegZize/MemVT.getScalarType().getSizeInBits());
19048 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19049 "Invalid vector type");
19051 // We can't shuffle using an illegal type.
19052 if (!TLI.isTypeLegal(WideVecVT))
19055 SmallVector<SDValue, 8> Chains;
19056 SDValue Ptr = Ld->getBasePtr();
19057 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19058 TLI.getPointerTy());
19059 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19061 for (unsigned i = 0; i < NumLoads; ++i) {
19062 // Perform a single load.
19063 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19064 Ptr, Ld->getPointerInfo(),
19065 Ld->isVolatile(), Ld->isNonTemporal(),
19066 Ld->isInvariant(), Ld->getAlignment());
19067 Chains.push_back(ScalarLoad.getValue(1));
19068 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19069 // another round of DAGCombining.
19071 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19073 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19074 ScalarLoad, DAG.getIntPtrConstant(i));
19076 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19079 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19081 // Bitcast the loaded value to a vector of the original element type, in
19082 // the size of the target vector type.
19083 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19084 unsigned SizeRatio = RegSz/MemSz;
19086 if (Ext == ISD::SEXTLOAD) {
19087 // If we have SSE4.1 we can directly emit a VSEXT node.
19088 if (Subtarget->hasSSE41()) {
19089 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19090 return DCI.CombineTo(N, Sext, TF, true);
19093 // Otherwise we'll shuffle the small elements in the high bits of the
19094 // larger type and perform an arithmetic shift. If the shift is not legal
19095 // it's better to scalarize.
19096 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19099 // Redistribute the loaded elements into the different locations.
19100 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19101 for (unsigned i = 0; i != NumElems; ++i)
19102 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19104 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19105 DAG.getUNDEF(WideVecVT),
19108 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19110 // Build the arithmetic shift.
19111 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19112 MemVT.getVectorElementType().getSizeInBits();
19113 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19114 DAG.getConstant(Amt, RegVT));
19116 return DCI.CombineTo(N, Shuff, TF, true);
19119 // Redistribute the loaded elements into the different locations.
19120 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19121 for (unsigned i = 0; i != NumElems; ++i)
19122 ShuffleVec[i*SizeRatio] = i;
19124 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19125 DAG.getUNDEF(WideVecVT),
19128 // Bitcast to the requested type.
19129 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19130 // Replace the original load with the new sequence
19131 // and return the new chain.
19132 return DCI.CombineTo(N, Shuff, TF, true);
19138 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19139 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19140 const X86Subtarget *Subtarget) {
19141 StoreSDNode *St = cast<StoreSDNode>(N);
19142 EVT VT = St->getValue().getValueType();
19143 EVT StVT = St->getMemoryVT();
19145 SDValue StoredVal = St->getOperand(1);
19146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19148 // If we are saving a concatenation of two XMM registers, perform two stores.
19149 // On Sandy Bridge, 256-bit memory operations are executed by two
19150 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19151 // memory operation.
19152 unsigned Alignment = St->getAlignment();
19153 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19154 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19155 StVT == VT && !IsAligned) {
19156 unsigned NumElems = VT.getVectorNumElements();
19160 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19161 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19163 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19164 SDValue Ptr0 = St->getBasePtr();
19165 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19167 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19168 St->getPointerInfo(), St->isVolatile(),
19169 St->isNonTemporal(), Alignment);
19170 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19171 St->getPointerInfo(), St->isVolatile(),
19172 St->isNonTemporal(),
19173 std::min(16U, Alignment));
19174 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19177 // Optimize trunc store (of multiple scalars) to shuffle and store.
19178 // First, pack all of the elements in one place. Next, store to memory
19179 // in fewer chunks.
19180 if (St->isTruncatingStore() && VT.isVector()) {
19181 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19182 unsigned NumElems = VT.getVectorNumElements();
19183 assert(StVT != VT && "Cannot truncate to the same type");
19184 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19185 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19187 // From, To sizes and ElemCount must be pow of two
19188 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19189 // We are going to use the original vector elt for storing.
19190 // Accumulated smaller vector elements must be a multiple of the store size.
19191 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19193 unsigned SizeRatio = FromSz / ToSz;
19195 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19197 // Create a type on which we perform the shuffle
19198 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19199 StVT.getScalarType(), NumElems*SizeRatio);
19201 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19203 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19204 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19205 for (unsigned i = 0; i != NumElems; ++i)
19206 ShuffleVec[i] = i * SizeRatio;
19208 // Can't shuffle using an illegal type.
19209 if (!TLI.isTypeLegal(WideVecVT))
19212 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19213 DAG.getUNDEF(WideVecVT),
19215 // At this point all of the data is stored at the bottom of the
19216 // register. We now need to save it to mem.
19218 // Find the largest store unit
19219 MVT StoreType = MVT::i8;
19220 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19221 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19222 MVT Tp = (MVT::SimpleValueType)tp;
19223 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19227 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19228 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19229 (64 <= NumElems * ToSz))
19230 StoreType = MVT::f64;
19232 // Bitcast the original vector into a vector of store-size units
19233 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19234 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19235 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19236 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19237 SmallVector<SDValue, 8> Chains;
19238 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19239 TLI.getPointerTy());
19240 SDValue Ptr = St->getBasePtr();
19242 // Perform one or more big stores into memory.
19243 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19244 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19245 StoreType, ShuffWide,
19246 DAG.getIntPtrConstant(i));
19247 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19248 St->getPointerInfo(), St->isVolatile(),
19249 St->isNonTemporal(), St->getAlignment());
19250 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19251 Chains.push_back(Ch);
19254 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19257 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19258 // the FP state in cases where an emms may be missing.
19259 // A preferable solution to the general problem is to figure out the right
19260 // places to insert EMMS. This qualifies as a quick hack.
19262 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19263 if (VT.getSizeInBits() != 64)
19266 const Function *F = DAG.getMachineFunction().getFunction();
19267 bool NoImplicitFloatOps = F->getAttributes().
19268 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19269 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19270 && Subtarget->hasSSE2();
19271 if ((VT.isVector() ||
19272 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19273 isa<LoadSDNode>(St->getValue()) &&
19274 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19275 St->getChain().hasOneUse() && !St->isVolatile()) {
19276 SDNode* LdVal = St->getValue().getNode();
19277 LoadSDNode *Ld = nullptr;
19278 int TokenFactorIndex = -1;
19279 SmallVector<SDValue, 8> Ops;
19280 SDNode* ChainVal = St->getChain().getNode();
19281 // Must be a store of a load. We currently handle two cases: the load
19282 // is a direct child, and it's under an intervening TokenFactor. It is
19283 // possible to dig deeper under nested TokenFactors.
19284 if (ChainVal == LdVal)
19285 Ld = cast<LoadSDNode>(St->getChain());
19286 else if (St->getValue().hasOneUse() &&
19287 ChainVal->getOpcode() == ISD::TokenFactor) {
19288 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19289 if (ChainVal->getOperand(i).getNode() == LdVal) {
19290 TokenFactorIndex = i;
19291 Ld = cast<LoadSDNode>(St->getValue());
19293 Ops.push_back(ChainVal->getOperand(i));
19297 if (!Ld || !ISD::isNormalLoad(Ld))
19300 // If this is not the MMX case, i.e. we are just turning i64 load/store
19301 // into f64 load/store, avoid the transformation if there are multiple
19302 // uses of the loaded value.
19303 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19308 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19309 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19311 if (Subtarget->is64Bit() || F64IsLegal) {
19312 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19313 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19314 Ld->getPointerInfo(), Ld->isVolatile(),
19315 Ld->isNonTemporal(), Ld->isInvariant(),
19316 Ld->getAlignment());
19317 SDValue NewChain = NewLd.getValue(1);
19318 if (TokenFactorIndex != -1) {
19319 Ops.push_back(NewChain);
19320 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19322 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19323 St->getPointerInfo(),
19324 St->isVolatile(), St->isNonTemporal(),
19325 St->getAlignment());
19328 // Otherwise, lower to two pairs of 32-bit loads / stores.
19329 SDValue LoAddr = Ld->getBasePtr();
19330 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19331 DAG.getConstant(4, MVT::i32));
19333 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19334 Ld->getPointerInfo(),
19335 Ld->isVolatile(), Ld->isNonTemporal(),
19336 Ld->isInvariant(), Ld->getAlignment());
19337 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19338 Ld->getPointerInfo().getWithOffset(4),
19339 Ld->isVolatile(), Ld->isNonTemporal(),
19341 MinAlign(Ld->getAlignment(), 4));
19343 SDValue NewChain = LoLd.getValue(1);
19344 if (TokenFactorIndex != -1) {
19345 Ops.push_back(LoLd);
19346 Ops.push_back(HiLd);
19347 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19350 LoAddr = St->getBasePtr();
19351 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19352 DAG.getConstant(4, MVT::i32));
19354 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19355 St->getPointerInfo(),
19356 St->isVolatile(), St->isNonTemporal(),
19357 St->getAlignment());
19358 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19359 St->getPointerInfo().getWithOffset(4),
19361 St->isNonTemporal(),
19362 MinAlign(St->getAlignment(), 4));
19363 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19368 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19369 /// and return the operands for the horizontal operation in LHS and RHS. A
19370 /// horizontal operation performs the binary operation on successive elements
19371 /// of its first operand, then on successive elements of its second operand,
19372 /// returning the resulting values in a vector. For example, if
19373 /// A = < float a0, float a1, float a2, float a3 >
19375 /// B = < float b0, float b1, float b2, float b3 >
19376 /// then the result of doing a horizontal operation on A and B is
19377 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19378 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19379 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19380 /// set to A, RHS to B, and the routine returns 'true'.
19381 /// Note that the binary operation should have the property that if one of the
19382 /// operands is UNDEF then the result is UNDEF.
19383 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19384 // Look for the following pattern: if
19385 // A = < float a0, float a1, float a2, float a3 >
19386 // B = < float b0, float b1, float b2, float b3 >
19388 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19389 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19390 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19391 // which is A horizontal-op B.
19393 // At least one of the operands should be a vector shuffle.
19394 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19395 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19398 MVT VT = LHS.getSimpleValueType();
19400 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19401 "Unsupported vector type for horizontal add/sub");
19403 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19404 // operate independently on 128-bit lanes.
19405 unsigned NumElts = VT.getVectorNumElements();
19406 unsigned NumLanes = VT.getSizeInBits()/128;
19407 unsigned NumLaneElts = NumElts / NumLanes;
19408 assert((NumLaneElts % 2 == 0) &&
19409 "Vector type should have an even number of elements in each lane");
19410 unsigned HalfLaneElts = NumLaneElts/2;
19412 // View LHS in the form
19413 // LHS = VECTOR_SHUFFLE A, B, LMask
19414 // If LHS is not a shuffle then pretend it is the shuffle
19415 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19416 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19419 SmallVector<int, 16> LMask(NumElts);
19420 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19421 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19422 A = LHS.getOperand(0);
19423 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19424 B = LHS.getOperand(1);
19425 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19426 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19428 if (LHS.getOpcode() != ISD::UNDEF)
19430 for (unsigned i = 0; i != NumElts; ++i)
19434 // Likewise, view RHS in the form
19435 // RHS = VECTOR_SHUFFLE C, D, RMask
19437 SmallVector<int, 16> RMask(NumElts);
19438 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19439 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19440 C = RHS.getOperand(0);
19441 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19442 D = RHS.getOperand(1);
19443 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19444 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19446 if (RHS.getOpcode() != ISD::UNDEF)
19448 for (unsigned i = 0; i != NumElts; ++i)
19452 // Check that the shuffles are both shuffling the same vectors.
19453 if (!(A == C && B == D) && !(A == D && B == C))
19456 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19457 if (!A.getNode() && !B.getNode())
19460 // If A and B occur in reverse order in RHS, then "swap" them (which means
19461 // rewriting the mask).
19463 CommuteVectorShuffleMask(RMask, NumElts);
19465 // At this point LHS and RHS are equivalent to
19466 // LHS = VECTOR_SHUFFLE A, B, LMask
19467 // RHS = VECTOR_SHUFFLE A, B, RMask
19468 // Check that the masks correspond to performing a horizontal operation.
19469 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19470 for (unsigned i = 0; i != NumLaneElts; ++i) {
19471 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19473 // Ignore any UNDEF components.
19474 if (LIdx < 0 || RIdx < 0 ||
19475 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19476 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19479 // Check that successive elements are being operated on. If not, this is
19480 // not a horizontal operation.
19481 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19482 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19483 if (!(LIdx == Index && RIdx == Index + 1) &&
19484 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19489 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19490 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19494 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19495 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19496 const X86Subtarget *Subtarget) {
19497 EVT VT = N->getValueType(0);
19498 SDValue LHS = N->getOperand(0);
19499 SDValue RHS = N->getOperand(1);
19501 // Try to synthesize horizontal adds from adds of shuffles.
19502 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19503 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19504 isHorizontalBinOp(LHS, RHS, true))
19505 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19509 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19510 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19511 const X86Subtarget *Subtarget) {
19512 EVT VT = N->getValueType(0);
19513 SDValue LHS = N->getOperand(0);
19514 SDValue RHS = N->getOperand(1);
19516 // Try to synthesize horizontal subs from subs of shuffles.
19517 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19518 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19519 isHorizontalBinOp(LHS, RHS, false))
19520 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19524 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19525 /// X86ISD::FXOR nodes.
19526 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19527 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19528 // F[X]OR(0.0, x) -> x
19529 // F[X]OR(x, 0.0) -> x
19530 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19531 if (C->getValueAPF().isPosZero())
19532 return N->getOperand(1);
19533 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19534 if (C->getValueAPF().isPosZero())
19535 return N->getOperand(0);
19539 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19540 /// X86ISD::FMAX nodes.
19541 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19542 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19544 // Only perform optimizations if UnsafeMath is used.
19545 if (!DAG.getTarget().Options.UnsafeFPMath)
19548 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19549 // into FMINC and FMAXC, which are Commutative operations.
19550 unsigned NewOp = 0;
19551 switch (N->getOpcode()) {
19552 default: llvm_unreachable("unknown opcode");
19553 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19554 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19557 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19558 N->getOperand(0), N->getOperand(1));
19561 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19562 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19563 // FAND(0.0, x) -> 0.0
19564 // FAND(x, 0.0) -> 0.0
19565 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19566 if (C->getValueAPF().isPosZero())
19567 return N->getOperand(0);
19568 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19569 if (C->getValueAPF().isPosZero())
19570 return N->getOperand(1);
19574 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19575 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19576 // FANDN(x, 0.0) -> 0.0
19577 // FANDN(0.0, x) -> x
19578 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19579 if (C->getValueAPF().isPosZero())
19580 return N->getOperand(1);
19581 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19582 if (C->getValueAPF().isPosZero())
19583 return N->getOperand(1);
19587 static SDValue PerformBTCombine(SDNode *N,
19589 TargetLowering::DAGCombinerInfo &DCI) {
19590 // BT ignores high bits in the bit index operand.
19591 SDValue Op1 = N->getOperand(1);
19592 if (Op1.hasOneUse()) {
19593 unsigned BitWidth = Op1.getValueSizeInBits();
19594 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19595 APInt KnownZero, KnownOne;
19596 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19597 !DCI.isBeforeLegalizeOps());
19598 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19599 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19600 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19601 DCI.CommitTargetLoweringOpt(TLO);
19606 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19607 SDValue Op = N->getOperand(0);
19608 if (Op.getOpcode() == ISD::BITCAST)
19609 Op = Op.getOperand(0);
19610 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19611 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19612 VT.getVectorElementType().getSizeInBits() ==
19613 OpVT.getVectorElementType().getSizeInBits()) {
19614 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19619 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19620 const X86Subtarget *Subtarget) {
19621 EVT VT = N->getValueType(0);
19622 if (!VT.isVector())
19625 SDValue N0 = N->getOperand(0);
19626 SDValue N1 = N->getOperand(1);
19627 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19630 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19631 // both SSE and AVX2 since there is no sign-extended shift right
19632 // operation on a vector with 64-bit elements.
19633 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19634 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19635 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19636 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19637 SDValue N00 = N0.getOperand(0);
19639 // EXTLOAD has a better solution on AVX2,
19640 // it may be replaced with X86ISD::VSEXT node.
19641 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19642 if (!ISD::isNormalLoad(N00.getNode()))
19645 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19646 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19648 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19654 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19655 TargetLowering::DAGCombinerInfo &DCI,
19656 const X86Subtarget *Subtarget) {
19657 if (!DCI.isBeforeLegalizeOps())
19660 if (!Subtarget->hasFp256())
19663 EVT VT = N->getValueType(0);
19664 if (VT.isVector() && VT.getSizeInBits() == 256) {
19665 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19673 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19674 const X86Subtarget* Subtarget) {
19676 EVT VT = N->getValueType(0);
19678 // Let legalize expand this if it isn't a legal type yet.
19679 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19682 EVT ScalarVT = VT.getScalarType();
19683 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19684 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19687 SDValue A = N->getOperand(0);
19688 SDValue B = N->getOperand(1);
19689 SDValue C = N->getOperand(2);
19691 bool NegA = (A.getOpcode() == ISD::FNEG);
19692 bool NegB = (B.getOpcode() == ISD::FNEG);
19693 bool NegC = (C.getOpcode() == ISD::FNEG);
19695 // Negative multiplication when NegA xor NegB
19696 bool NegMul = (NegA != NegB);
19698 A = A.getOperand(0);
19700 B = B.getOperand(0);
19702 C = C.getOperand(0);
19706 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19708 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19710 return DAG.getNode(Opcode, dl, VT, A, B, C);
19713 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19714 TargetLowering::DAGCombinerInfo &DCI,
19715 const X86Subtarget *Subtarget) {
19716 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19717 // (and (i32 x86isd::setcc_carry), 1)
19718 // This eliminates the zext. This transformation is necessary because
19719 // ISD::SETCC is always legalized to i8.
19721 SDValue N0 = N->getOperand(0);
19722 EVT VT = N->getValueType(0);
19724 if (N0.getOpcode() == ISD::AND &&
19726 N0.getOperand(0).hasOneUse()) {
19727 SDValue N00 = N0.getOperand(0);
19728 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19729 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19730 if (!C || C->getZExtValue() != 1)
19732 return DAG.getNode(ISD::AND, dl, VT,
19733 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19734 N00.getOperand(0), N00.getOperand(1)),
19735 DAG.getConstant(1, VT));
19739 if (N0.getOpcode() == ISD::TRUNCATE &&
19741 N0.getOperand(0).hasOneUse()) {
19742 SDValue N00 = N0.getOperand(0);
19743 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19744 return DAG.getNode(ISD::AND, dl, VT,
19745 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19746 N00.getOperand(0), N00.getOperand(1)),
19747 DAG.getConstant(1, VT));
19750 if (VT.is256BitVector()) {
19751 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19759 // Optimize x == -y --> x+y == 0
19760 // x != -y --> x+y != 0
19761 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19762 const X86Subtarget* Subtarget) {
19763 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19764 SDValue LHS = N->getOperand(0);
19765 SDValue RHS = N->getOperand(1);
19766 EVT VT = N->getValueType(0);
19769 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19770 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19771 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19772 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19773 LHS.getValueType(), RHS, LHS.getOperand(1));
19774 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19775 addV, DAG.getConstant(0, addV.getValueType()), CC);
19777 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19778 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19779 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19780 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19781 RHS.getValueType(), LHS, RHS.getOperand(1));
19782 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19783 addV, DAG.getConstant(0, addV.getValueType()), CC);
19786 if (VT.getScalarType() == MVT::i1) {
19787 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19788 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19789 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19790 if (!IsSEXT0 && !IsVZero0)
19792 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19793 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19794 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19796 if (!IsSEXT1 && !IsVZero1)
19799 if (IsSEXT0 && IsVZero1) {
19800 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19801 if (CC == ISD::SETEQ)
19802 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19803 return LHS.getOperand(0);
19805 if (IsSEXT1 && IsVZero0) {
19806 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19807 if (CC == ISD::SETEQ)
19808 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19809 return RHS.getOperand(0);
19816 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19817 // as "sbb reg,reg", since it can be extended without zext and produces
19818 // an all-ones bit which is more useful than 0/1 in some cases.
19819 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19822 return DAG.getNode(ISD::AND, DL, VT,
19823 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19824 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19825 DAG.getConstant(1, VT));
19826 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19827 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19828 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19829 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19832 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19833 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19834 TargetLowering::DAGCombinerInfo &DCI,
19835 const X86Subtarget *Subtarget) {
19837 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19838 SDValue EFLAGS = N->getOperand(1);
19840 if (CC == X86::COND_A) {
19841 // Try to convert COND_A into COND_B in an attempt to facilitate
19842 // materializing "setb reg".
19844 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19845 // cannot take an immediate as its first operand.
19847 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19848 EFLAGS.getValueType().isInteger() &&
19849 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19850 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19851 EFLAGS.getNode()->getVTList(),
19852 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19853 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19854 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19858 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19859 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19861 if (CC == X86::COND_B)
19862 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19866 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19867 if (Flags.getNode()) {
19868 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19869 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19875 // Optimize branch condition evaluation.
19877 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19878 TargetLowering::DAGCombinerInfo &DCI,
19879 const X86Subtarget *Subtarget) {
19881 SDValue Chain = N->getOperand(0);
19882 SDValue Dest = N->getOperand(1);
19883 SDValue EFLAGS = N->getOperand(3);
19884 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19888 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19889 if (Flags.getNode()) {
19890 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19891 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19898 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19899 const X86TargetLowering *XTLI) {
19900 SDValue Op0 = N->getOperand(0);
19901 EVT InVT = Op0->getValueType(0);
19903 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19904 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19906 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19907 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19908 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19911 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19912 // a 32-bit target where SSE doesn't support i64->FP operations.
19913 if (Op0.getOpcode() == ISD::LOAD) {
19914 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19915 EVT VT = Ld->getValueType(0);
19916 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19917 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19918 !XTLI->getSubtarget()->is64Bit() &&
19920 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19921 Ld->getChain(), Op0, DAG);
19922 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19929 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19930 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19931 X86TargetLowering::DAGCombinerInfo &DCI) {
19932 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19933 // the result is either zero or one (depending on the input carry bit).
19934 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19935 if (X86::isZeroNode(N->getOperand(0)) &&
19936 X86::isZeroNode(N->getOperand(1)) &&
19937 // We don't have a good way to replace an EFLAGS use, so only do this when
19939 SDValue(N, 1).use_empty()) {
19941 EVT VT = N->getValueType(0);
19942 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19943 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19944 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19945 DAG.getConstant(X86::COND_B,MVT::i8),
19947 DAG.getConstant(1, VT));
19948 return DCI.CombineTo(N, Res1, CarryOut);
19954 // fold (add Y, (sete X, 0)) -> adc 0, Y
19955 // (add Y, (setne X, 0)) -> sbb -1, Y
19956 // (sub (sete X, 0), Y) -> sbb 0, Y
19957 // (sub (setne X, 0), Y) -> adc -1, Y
19958 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19961 // Look through ZExts.
19962 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19963 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19966 SDValue SetCC = Ext.getOperand(0);
19967 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19970 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19971 if (CC != X86::COND_E && CC != X86::COND_NE)
19974 SDValue Cmp = SetCC.getOperand(1);
19975 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19976 !X86::isZeroNode(Cmp.getOperand(1)) ||
19977 !Cmp.getOperand(0).getValueType().isInteger())
19980 SDValue CmpOp0 = Cmp.getOperand(0);
19981 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19982 DAG.getConstant(1, CmpOp0.getValueType()));
19984 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19985 if (CC == X86::COND_NE)
19986 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19987 DL, OtherVal.getValueType(), OtherVal,
19988 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19989 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19990 DL, OtherVal.getValueType(), OtherVal,
19991 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19994 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19995 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19996 const X86Subtarget *Subtarget) {
19997 EVT VT = N->getValueType(0);
19998 SDValue Op0 = N->getOperand(0);
19999 SDValue Op1 = N->getOperand(1);
20001 // Try to synthesize horizontal adds from adds of shuffles.
20002 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20003 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20004 isHorizontalBinOp(Op0, Op1, true))
20005 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20007 return OptimizeConditionalInDecrement(N, DAG);
20010 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20011 const X86Subtarget *Subtarget) {
20012 SDValue Op0 = N->getOperand(0);
20013 SDValue Op1 = N->getOperand(1);
20015 // X86 can't encode an immediate LHS of a sub. See if we can push the
20016 // negation into a preceding instruction.
20017 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20018 // If the RHS of the sub is a XOR with one use and a constant, invert the
20019 // immediate. Then add one to the LHS of the sub so we can turn
20020 // X-Y -> X+~Y+1, saving one register.
20021 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20022 isa<ConstantSDNode>(Op1.getOperand(1))) {
20023 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20024 EVT VT = Op0.getValueType();
20025 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20027 DAG.getConstant(~XorC, VT));
20028 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20029 DAG.getConstant(C->getAPIntValue()+1, VT));
20033 // Try to synthesize horizontal adds from adds of shuffles.
20034 EVT VT = N->getValueType(0);
20035 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20036 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20037 isHorizontalBinOp(Op0, Op1, true))
20038 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20040 return OptimizeConditionalInDecrement(N, DAG);
20043 /// performVZEXTCombine - Performs build vector combines
20044 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20045 TargetLowering::DAGCombinerInfo &DCI,
20046 const X86Subtarget *Subtarget) {
20047 // (vzext (bitcast (vzext (x)) -> (vzext x)
20048 SDValue In = N->getOperand(0);
20049 while (In.getOpcode() == ISD::BITCAST)
20050 In = In.getOperand(0);
20052 if (In.getOpcode() != X86ISD::VZEXT)
20055 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20059 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20060 DAGCombinerInfo &DCI) const {
20061 SelectionDAG &DAG = DCI.DAG;
20062 switch (N->getOpcode()) {
20064 case ISD::EXTRACT_VECTOR_ELT:
20065 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20067 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20068 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20069 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20070 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20071 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20072 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20075 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20076 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20077 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20078 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20079 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20080 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20081 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20082 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20083 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20085 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20087 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20088 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20089 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20090 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20091 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20092 case ISD::ANY_EXTEND:
20093 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20094 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20095 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20096 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20097 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20098 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20099 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20100 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20101 case X86ISD::SHUFP: // Handle all target specific shuffles
20102 case X86ISD::PALIGNR:
20103 case X86ISD::UNPCKH:
20104 case X86ISD::UNPCKL:
20105 case X86ISD::MOVHLPS:
20106 case X86ISD::MOVLHPS:
20107 case X86ISD::PSHUFD:
20108 case X86ISD::PSHUFHW:
20109 case X86ISD::PSHUFLW:
20110 case X86ISD::MOVSS:
20111 case X86ISD::MOVSD:
20112 case X86ISD::VPERMILP:
20113 case X86ISD::VPERM2X128:
20114 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20115 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20121 /// isTypeDesirableForOp - Return true if the target has native support for
20122 /// the specified value type and it is 'desirable' to use the type for the
20123 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20124 /// instruction encodings are longer and some i16 instructions are slow.
20125 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20126 if (!isTypeLegal(VT))
20128 if (VT != MVT::i16)
20135 case ISD::SIGN_EXTEND:
20136 case ISD::ZERO_EXTEND:
20137 case ISD::ANY_EXTEND:
20150 /// IsDesirableToPromoteOp - This method query the target whether it is
20151 /// beneficial for dag combiner to promote the specified node. If true, it
20152 /// should return the desired promotion type by reference.
20153 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20154 EVT VT = Op.getValueType();
20155 if (VT != MVT::i16)
20158 bool Promote = false;
20159 bool Commute = false;
20160 switch (Op.getOpcode()) {
20163 LoadSDNode *LD = cast<LoadSDNode>(Op);
20164 // If the non-extending load has a single use and it's not live out, then it
20165 // might be folded.
20166 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20167 Op.hasOneUse()*/) {
20168 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20169 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20170 // The only case where we'd want to promote LOAD (rather then it being
20171 // promoted as an operand is when it's only use is liveout.
20172 if (UI->getOpcode() != ISD::CopyToReg)
20179 case ISD::SIGN_EXTEND:
20180 case ISD::ZERO_EXTEND:
20181 case ISD::ANY_EXTEND:
20186 SDValue N0 = Op.getOperand(0);
20187 // Look out for (store (shl (load), x)).
20188 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20201 SDValue N0 = Op.getOperand(0);
20202 SDValue N1 = Op.getOperand(1);
20203 if (!Commute && MayFoldLoad(N1))
20205 // Avoid disabling potential load folding opportunities.
20206 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20208 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20218 //===----------------------------------------------------------------------===//
20219 // X86 Inline Assembly Support
20220 //===----------------------------------------------------------------------===//
20223 // Helper to match a string separated by whitespace.
20224 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20225 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20227 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20228 StringRef piece(*args[i]);
20229 if (!s.startswith(piece)) // Check if the piece matches.
20232 s = s.substr(piece.size());
20233 StringRef::size_type pos = s.find_first_not_of(" \t");
20234 if (pos == 0) // We matched a prefix.
20242 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20245 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20247 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20248 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20249 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20250 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20252 if (AsmPieces.size() == 3)
20254 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20261 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20262 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20264 std::string AsmStr = IA->getAsmString();
20266 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20267 if (!Ty || Ty->getBitWidth() % 16 != 0)
20270 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20271 SmallVector<StringRef, 4> AsmPieces;
20272 SplitString(AsmStr, AsmPieces, ";\n");
20274 switch (AsmPieces.size()) {
20275 default: return false;
20277 // FIXME: this should verify that we are targeting a 486 or better. If not,
20278 // we will turn this bswap into something that will be lowered to logical
20279 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20280 // lower so don't worry about this.
20282 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20283 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20284 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20285 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20286 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20287 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20288 // No need to check constraints, nothing other than the equivalent of
20289 // "=r,0" would be valid here.
20290 return IntrinsicLowering::LowerToByteSwap(CI);
20293 // rorw $$8, ${0:w} --> llvm.bswap.i16
20294 if (CI->getType()->isIntegerTy(16) &&
20295 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20296 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20297 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20299 const std::string &ConstraintsStr = IA->getConstraintString();
20300 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20301 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20302 if (clobbersFlagRegisters(AsmPieces))
20303 return IntrinsicLowering::LowerToByteSwap(CI);
20307 if (CI->getType()->isIntegerTy(32) &&
20308 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20309 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20310 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20311 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20313 const std::string &ConstraintsStr = IA->getConstraintString();
20314 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20315 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20316 if (clobbersFlagRegisters(AsmPieces))
20317 return IntrinsicLowering::LowerToByteSwap(CI);
20320 if (CI->getType()->isIntegerTy(64)) {
20321 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20322 if (Constraints.size() >= 2 &&
20323 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20324 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20325 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20326 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20327 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20328 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20329 return IntrinsicLowering::LowerToByteSwap(CI);
20337 /// getConstraintType - Given a constraint letter, return the type of
20338 /// constraint it is for this target.
20339 X86TargetLowering::ConstraintType
20340 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20341 if (Constraint.size() == 1) {
20342 switch (Constraint[0]) {
20353 return C_RegisterClass;
20377 return TargetLowering::getConstraintType(Constraint);
20380 /// Examine constraint type and operand type and determine a weight value.
20381 /// This object must already have been set up with the operand type
20382 /// and the current alternative constraint selected.
20383 TargetLowering::ConstraintWeight
20384 X86TargetLowering::getSingleConstraintMatchWeight(
20385 AsmOperandInfo &info, const char *constraint) const {
20386 ConstraintWeight weight = CW_Invalid;
20387 Value *CallOperandVal = info.CallOperandVal;
20388 // If we don't have a value, we can't do a match,
20389 // but allow it at the lowest weight.
20390 if (!CallOperandVal)
20392 Type *type = CallOperandVal->getType();
20393 // Look at the constraint type.
20394 switch (*constraint) {
20396 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20407 if (CallOperandVal->getType()->isIntegerTy())
20408 weight = CW_SpecificReg;
20413 if (type->isFloatingPointTy())
20414 weight = CW_SpecificReg;
20417 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20418 weight = CW_SpecificReg;
20422 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20423 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20424 weight = CW_Register;
20427 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20428 if (C->getZExtValue() <= 31)
20429 weight = CW_Constant;
20433 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20434 if (C->getZExtValue() <= 63)
20435 weight = CW_Constant;
20439 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20440 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20441 weight = CW_Constant;
20445 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20446 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20447 weight = CW_Constant;
20451 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20452 if (C->getZExtValue() <= 3)
20453 weight = CW_Constant;
20457 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20458 if (C->getZExtValue() <= 0xff)
20459 weight = CW_Constant;
20464 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20465 weight = CW_Constant;
20469 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20470 if ((C->getSExtValue() >= -0x80000000LL) &&
20471 (C->getSExtValue() <= 0x7fffffffLL))
20472 weight = CW_Constant;
20476 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20477 if (C->getZExtValue() <= 0xffffffff)
20478 weight = CW_Constant;
20485 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20486 /// with another that has more specific requirements based on the type of the
20487 /// corresponding operand.
20488 const char *X86TargetLowering::
20489 LowerXConstraint(EVT ConstraintVT) const {
20490 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20491 // 'f' like normal targets.
20492 if (ConstraintVT.isFloatingPoint()) {
20493 if (Subtarget->hasSSE2())
20495 if (Subtarget->hasSSE1())
20499 return TargetLowering::LowerXConstraint(ConstraintVT);
20502 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20503 /// vector. If it is invalid, don't add anything to Ops.
20504 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20505 std::string &Constraint,
20506 std::vector<SDValue>&Ops,
20507 SelectionDAG &DAG) const {
20510 // Only support length 1 constraints for now.
20511 if (Constraint.length() > 1) return;
20513 char ConstraintLetter = Constraint[0];
20514 switch (ConstraintLetter) {
20517 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20518 if (C->getZExtValue() <= 31) {
20519 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20526 if (C->getZExtValue() <= 63) {
20527 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20533 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20534 if (isInt<8>(C->getSExtValue())) {
20535 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20541 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20542 if (C->getZExtValue() <= 255) {
20543 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20549 // 32-bit signed value
20550 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20551 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20552 C->getSExtValue())) {
20553 // Widen to 64 bits here to get it sign extended.
20554 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20557 // FIXME gcc accepts some relocatable values here too, but only in certain
20558 // memory models; it's complicated.
20563 // 32-bit unsigned value
20564 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20565 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20566 C->getZExtValue())) {
20567 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20571 // FIXME gcc accepts some relocatable values here too, but only in certain
20572 // memory models; it's complicated.
20576 // Literal immediates are always ok.
20577 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20578 // Widen to 64 bits here to get it sign extended.
20579 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20583 // In any sort of PIC mode addresses need to be computed at runtime by
20584 // adding in a register or some sort of table lookup. These can't
20585 // be used as immediates.
20586 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20589 // If we are in non-pic codegen mode, we allow the address of a global (with
20590 // an optional displacement) to be used with 'i'.
20591 GlobalAddressSDNode *GA = nullptr;
20592 int64_t Offset = 0;
20594 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20596 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20597 Offset += GA->getOffset();
20599 } else if (Op.getOpcode() == ISD::ADD) {
20600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20601 Offset += C->getZExtValue();
20602 Op = Op.getOperand(0);
20605 } else if (Op.getOpcode() == ISD::SUB) {
20606 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20607 Offset += -C->getZExtValue();
20608 Op = Op.getOperand(0);
20613 // Otherwise, this isn't something we can handle, reject it.
20617 const GlobalValue *GV = GA->getGlobal();
20618 // If we require an extra load to get this address, as in PIC mode, we
20619 // can't accept it.
20620 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20621 getTargetMachine())))
20624 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20625 GA->getValueType(0), Offset);
20630 if (Result.getNode()) {
20631 Ops.push_back(Result);
20634 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20637 std::pair<unsigned, const TargetRegisterClass*>
20638 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20640 // First, see if this is a constraint that directly corresponds to an LLVM
20642 if (Constraint.size() == 1) {
20643 // GCC Constraint Letters
20644 switch (Constraint[0]) {
20646 // TODO: Slight differences here in allocation order and leaving
20647 // RIP in the class. Do they matter any more here than they do
20648 // in the normal allocation?
20649 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20650 if (Subtarget->is64Bit()) {
20651 if (VT == MVT::i32 || VT == MVT::f32)
20652 return std::make_pair(0U, &X86::GR32RegClass);
20653 if (VT == MVT::i16)
20654 return std::make_pair(0U, &X86::GR16RegClass);
20655 if (VT == MVT::i8 || VT == MVT::i1)
20656 return std::make_pair(0U, &X86::GR8RegClass);
20657 if (VT == MVT::i64 || VT == MVT::f64)
20658 return std::make_pair(0U, &X86::GR64RegClass);
20661 // 32-bit fallthrough
20662 case 'Q': // Q_REGS
20663 if (VT == MVT::i32 || VT == MVT::f32)
20664 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20665 if (VT == MVT::i16)
20666 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20667 if (VT == MVT::i8 || VT == MVT::i1)
20668 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20669 if (VT == MVT::i64)
20670 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20672 case 'r': // GENERAL_REGS
20673 case 'l': // INDEX_REGS
20674 if (VT == MVT::i8 || VT == MVT::i1)
20675 return std::make_pair(0U, &X86::GR8RegClass);
20676 if (VT == MVT::i16)
20677 return std::make_pair(0U, &X86::GR16RegClass);
20678 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20679 return std::make_pair(0U, &X86::GR32RegClass);
20680 return std::make_pair(0U, &X86::GR64RegClass);
20681 case 'R': // LEGACY_REGS
20682 if (VT == MVT::i8 || VT == MVT::i1)
20683 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20684 if (VT == MVT::i16)
20685 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20686 if (VT == MVT::i32 || !Subtarget->is64Bit())
20687 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20688 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20689 case 'f': // FP Stack registers.
20690 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20691 // value to the correct fpstack register class.
20692 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20693 return std::make_pair(0U, &X86::RFP32RegClass);
20694 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20695 return std::make_pair(0U, &X86::RFP64RegClass);
20696 return std::make_pair(0U, &X86::RFP80RegClass);
20697 case 'y': // MMX_REGS if MMX allowed.
20698 if (!Subtarget->hasMMX()) break;
20699 return std::make_pair(0U, &X86::VR64RegClass);
20700 case 'Y': // SSE_REGS if SSE2 allowed
20701 if (!Subtarget->hasSSE2()) break;
20703 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20704 if (!Subtarget->hasSSE1()) break;
20706 switch (VT.SimpleTy) {
20708 // Scalar SSE types.
20711 return std::make_pair(0U, &X86::FR32RegClass);
20714 return std::make_pair(0U, &X86::FR64RegClass);
20722 return std::make_pair(0U, &X86::VR128RegClass);
20730 return std::make_pair(0U, &X86::VR256RegClass);
20735 return std::make_pair(0U, &X86::VR512RegClass);
20741 // Use the default implementation in TargetLowering to convert the register
20742 // constraint into a member of a register class.
20743 std::pair<unsigned, const TargetRegisterClass*> Res;
20744 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20746 // Not found as a standard register?
20748 // Map st(0) -> st(7) -> ST0
20749 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20750 tolower(Constraint[1]) == 's' &&
20751 tolower(Constraint[2]) == 't' &&
20752 Constraint[3] == '(' &&
20753 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20754 Constraint[5] == ')' &&
20755 Constraint[6] == '}') {
20757 Res.first = X86::ST0+Constraint[4]-'0';
20758 Res.second = &X86::RFP80RegClass;
20762 // GCC allows "st(0)" to be called just plain "st".
20763 if (StringRef("{st}").equals_lower(Constraint)) {
20764 Res.first = X86::ST0;
20765 Res.second = &X86::RFP80RegClass;
20770 if (StringRef("{flags}").equals_lower(Constraint)) {
20771 Res.first = X86::EFLAGS;
20772 Res.second = &X86::CCRRegClass;
20776 // 'A' means EAX + EDX.
20777 if (Constraint == "A") {
20778 Res.first = X86::EAX;
20779 Res.second = &X86::GR32_ADRegClass;
20785 // Otherwise, check to see if this is a register class of the wrong value
20786 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20787 // turn into {ax},{dx}.
20788 if (Res.second->hasType(VT))
20789 return Res; // Correct type already, nothing to do.
20791 // All of the single-register GCC register classes map their values onto
20792 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20793 // really want an 8-bit or 32-bit register, map to the appropriate register
20794 // class and return the appropriate register.
20795 if (Res.second == &X86::GR16RegClass) {
20796 if (VT == MVT::i8 || VT == MVT::i1) {
20797 unsigned DestReg = 0;
20798 switch (Res.first) {
20800 case X86::AX: DestReg = X86::AL; break;
20801 case X86::DX: DestReg = X86::DL; break;
20802 case X86::CX: DestReg = X86::CL; break;
20803 case X86::BX: DestReg = X86::BL; break;
20806 Res.first = DestReg;
20807 Res.second = &X86::GR8RegClass;
20809 } else if (VT == MVT::i32 || VT == MVT::f32) {
20810 unsigned DestReg = 0;
20811 switch (Res.first) {
20813 case X86::AX: DestReg = X86::EAX; break;
20814 case X86::DX: DestReg = X86::EDX; break;
20815 case X86::CX: DestReg = X86::ECX; break;
20816 case X86::BX: DestReg = X86::EBX; break;
20817 case X86::SI: DestReg = X86::ESI; break;
20818 case X86::DI: DestReg = X86::EDI; break;
20819 case X86::BP: DestReg = X86::EBP; break;
20820 case X86::SP: DestReg = X86::ESP; break;
20823 Res.first = DestReg;
20824 Res.second = &X86::GR32RegClass;
20826 } else if (VT == MVT::i64 || VT == MVT::f64) {
20827 unsigned DestReg = 0;
20828 switch (Res.first) {
20830 case X86::AX: DestReg = X86::RAX; break;
20831 case X86::DX: DestReg = X86::RDX; break;
20832 case X86::CX: DestReg = X86::RCX; break;
20833 case X86::BX: DestReg = X86::RBX; break;
20834 case X86::SI: DestReg = X86::RSI; break;
20835 case X86::DI: DestReg = X86::RDI; break;
20836 case X86::BP: DestReg = X86::RBP; break;
20837 case X86::SP: DestReg = X86::RSP; break;
20840 Res.first = DestReg;
20841 Res.second = &X86::GR64RegClass;
20844 } else if (Res.second == &X86::FR32RegClass ||
20845 Res.second == &X86::FR64RegClass ||
20846 Res.second == &X86::VR128RegClass ||
20847 Res.second == &X86::VR256RegClass ||
20848 Res.second == &X86::FR32XRegClass ||
20849 Res.second == &X86::FR64XRegClass ||
20850 Res.second == &X86::VR128XRegClass ||
20851 Res.second == &X86::VR256XRegClass ||
20852 Res.second == &X86::VR512RegClass) {
20853 // Handle references to XMM physical registers that got mapped into the
20854 // wrong class. This can happen with constraints like {xmm0} where the
20855 // target independent register mapper will just pick the first match it can
20856 // find, ignoring the required type.
20858 if (VT == MVT::f32 || VT == MVT::i32)
20859 Res.second = &X86::FR32RegClass;
20860 else if (VT == MVT::f64 || VT == MVT::i64)
20861 Res.second = &X86::FR64RegClass;
20862 else if (X86::VR128RegClass.hasType(VT))
20863 Res.second = &X86::VR128RegClass;
20864 else if (X86::VR256RegClass.hasType(VT))
20865 Res.second = &X86::VR256RegClass;
20866 else if (X86::VR512RegClass.hasType(VT))
20867 Res.second = &X86::VR512RegClass;
20873 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20875 // Scaling factors are not free at all.
20876 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20877 // will take 2 allocations in the out of order engine instead of 1
20878 // for plain addressing mode, i.e. inst (reg1).
20880 // vaddps (%rsi,%drx), %ymm0, %ymm1
20881 // Requires two allocations (one for the load, one for the computation)
20883 // vaddps (%rsi), %ymm0, %ymm1
20884 // Requires just 1 allocation, i.e., freeing allocations for other operations
20885 // and having less micro operations to execute.
20887 // For some X86 architectures, this is even worse because for instance for
20888 // stores, the complex addressing mode forces the instruction to use the
20889 // "load" ports instead of the dedicated "store" port.
20890 // E.g., on Haswell:
20891 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
20892 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
20893 if (isLegalAddressingMode(AM, Ty))
20894 // Scale represents reg2 * scale, thus account for 1
20895 // as soon as we use a second register.
20896 return AM.Scale != 0;