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 if (Subtarget->isTargetWin64()) {
1524 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1525 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1526 setOperationAction(ISD::SREM, MVT::i128, Custom);
1527 setOperationAction(ISD::UREM, MVT::i128, Custom);
1528 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1529 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1532 // We have target-specific dag combine patterns for the following nodes:
1533 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1534 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1535 setTargetDAGCombine(ISD::VSELECT);
1536 setTargetDAGCombine(ISD::SELECT);
1537 setTargetDAGCombine(ISD::SHL);
1538 setTargetDAGCombine(ISD::SRA);
1539 setTargetDAGCombine(ISD::SRL);
1540 setTargetDAGCombine(ISD::OR);
1541 setTargetDAGCombine(ISD::AND);
1542 setTargetDAGCombine(ISD::ADD);
1543 setTargetDAGCombine(ISD::FADD);
1544 setTargetDAGCombine(ISD::FSUB);
1545 setTargetDAGCombine(ISD::FMA);
1546 setTargetDAGCombine(ISD::SUB);
1547 setTargetDAGCombine(ISD::LOAD);
1548 setTargetDAGCombine(ISD::STORE);
1549 setTargetDAGCombine(ISD::ZERO_EXTEND);
1550 setTargetDAGCombine(ISD::ANY_EXTEND);
1551 setTargetDAGCombine(ISD::SIGN_EXTEND);
1552 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1553 setTargetDAGCombine(ISD::TRUNCATE);
1554 setTargetDAGCombine(ISD::SINT_TO_FP);
1555 setTargetDAGCombine(ISD::SETCC);
1556 if (Subtarget->is64Bit())
1557 setTargetDAGCombine(ISD::MUL);
1558 setTargetDAGCombine(ISD::XOR);
1560 computeRegisterProperties();
1562 // On Darwin, -Os means optimize for size without hurting performance,
1563 // do not reduce the limit.
1564 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1565 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1566 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1567 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1568 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1569 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1570 setPrefLoopAlignment(4); // 2^4 bytes.
1572 // Predictable cmov don't hurt on atom because it's in-order.
1573 PredictableSelectIsExpensive = !Subtarget->isAtom();
1575 setPrefFunctionAlignment(4); // 2^4 bytes.
1578 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1580 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1582 if (Subtarget->hasAVX512())
1583 switch(VT.getVectorNumElements()) {
1584 case 8: return MVT::v8i1;
1585 case 16: return MVT::v16i1;
1588 return VT.changeVectorElementTypeToInteger();
1591 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1592 /// the desired ByVal argument alignment.
1593 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1596 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1597 if (VTy->getBitWidth() == 128)
1599 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1600 unsigned EltAlign = 0;
1601 getMaxByValAlign(ATy->getElementType(), EltAlign);
1602 if (EltAlign > MaxAlign)
1603 MaxAlign = EltAlign;
1604 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1605 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1606 unsigned EltAlign = 0;
1607 getMaxByValAlign(STy->getElementType(i), EltAlign);
1608 if (EltAlign > MaxAlign)
1609 MaxAlign = EltAlign;
1616 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1617 /// function arguments in the caller parameter area. For X86, aggregates
1618 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1619 /// are at 4-byte boundaries.
1620 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1621 if (Subtarget->is64Bit()) {
1622 // Max of 8 and alignment of type.
1623 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1630 if (Subtarget->hasSSE1())
1631 getMaxByValAlign(Ty, Align);
1635 /// getOptimalMemOpType - Returns the target specific optimal type for load
1636 /// and store operations as a result of memset, memcpy, and memmove
1637 /// lowering. If DstAlign is zero that means it's safe to destination
1638 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1639 /// means there isn't a need to check it against alignment requirement,
1640 /// probably because the source does not need to be loaded. If 'IsMemset' is
1641 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1642 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1643 /// source is constant so it does not need to be loaded.
1644 /// It returns EVT::Other if the type should be determined using generic
1645 /// target-independent logic.
1647 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1648 unsigned DstAlign, unsigned SrcAlign,
1649 bool IsMemset, bool ZeroMemset,
1651 MachineFunction &MF) const {
1652 const Function *F = MF.getFunction();
1653 if ((!IsMemset || ZeroMemset) &&
1654 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1655 Attribute::NoImplicitFloat)) {
1657 (Subtarget->isUnalignedMemAccessFast() ||
1658 ((DstAlign == 0 || DstAlign >= 16) &&
1659 (SrcAlign == 0 || SrcAlign >= 16)))) {
1661 if (Subtarget->hasInt256())
1663 if (Subtarget->hasFp256())
1666 if (Subtarget->hasSSE2())
1668 if (Subtarget->hasSSE1())
1670 } else if (!MemcpyStrSrc && Size >= 8 &&
1671 !Subtarget->is64Bit() &&
1672 Subtarget->hasSSE2()) {
1673 // Do not use f64 to lower memcpy if source is string constant. It's
1674 // better to use i32 to avoid the loads.
1678 if (Subtarget->is64Bit() && Size >= 8)
1683 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1685 return X86ScalarSSEf32;
1686 else if (VT == MVT::f64)
1687 return X86ScalarSSEf64;
1692 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1696 *Fast = Subtarget->isUnalignedMemAccessFast();
1700 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1701 /// current function. The returned value is a member of the
1702 /// MachineJumpTableInfo::JTEntryKind enum.
1703 unsigned X86TargetLowering::getJumpTableEncoding() const {
1704 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1706 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1707 Subtarget->isPICStyleGOT())
1708 return MachineJumpTableInfo::EK_Custom32;
1710 // Otherwise, use the normal jump table encoding heuristics.
1711 return TargetLowering::getJumpTableEncoding();
1715 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1716 const MachineBasicBlock *MBB,
1717 unsigned uid,MCContext &Ctx) const{
1718 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1719 Subtarget->isPICStyleGOT());
1720 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1722 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1723 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1726 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1728 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1729 SelectionDAG &DAG) const {
1730 if (!Subtarget->is64Bit())
1731 // This doesn't have SDLoc associated with it, but is not really the
1732 // same as a Register.
1733 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1737 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1738 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1740 const MCExpr *X86TargetLowering::
1741 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1742 MCContext &Ctx) const {
1743 // X86-64 uses RIP relative addressing based on the jump table label.
1744 if (Subtarget->isPICStyleRIPRel())
1745 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1747 // Otherwise, the reference is relative to the PIC base.
1748 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1751 // FIXME: Why this routine is here? Move to RegInfo!
1752 std::pair<const TargetRegisterClass*, uint8_t>
1753 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1754 const TargetRegisterClass *RRC = nullptr;
1756 switch (VT.SimpleTy) {
1758 return TargetLowering::findRepresentativeClass(VT);
1759 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1760 RRC = Subtarget->is64Bit() ?
1761 (const TargetRegisterClass*)&X86::GR64RegClass :
1762 (const TargetRegisterClass*)&X86::GR32RegClass;
1765 RRC = &X86::VR64RegClass;
1767 case MVT::f32: case MVT::f64:
1768 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1769 case MVT::v4f32: case MVT::v2f64:
1770 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1772 RRC = &X86::VR128RegClass;
1775 return std::make_pair(RRC, Cost);
1778 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1779 unsigned &Offset) const {
1780 if (!Subtarget->isTargetLinux())
1783 if (Subtarget->is64Bit()) {
1784 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1786 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1798 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1799 unsigned DestAS) const {
1800 assert(SrcAS != DestAS && "Expected different address spaces!");
1802 return SrcAS < 256 && DestAS < 256;
1805 //===----------------------------------------------------------------------===//
1806 // Return Value Calling Convention Implementation
1807 //===----------------------------------------------------------------------===//
1809 #include "X86GenCallingConv.inc"
1812 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1813 MachineFunction &MF, bool isVarArg,
1814 const SmallVectorImpl<ISD::OutputArg> &Outs,
1815 LLVMContext &Context) const {
1816 SmallVector<CCValAssign, 16> RVLocs;
1817 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1819 return CCInfo.CheckReturn(Outs, RetCC_X86);
1822 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1823 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1828 X86TargetLowering::LowerReturn(SDValue Chain,
1829 CallingConv::ID CallConv, bool isVarArg,
1830 const SmallVectorImpl<ISD::OutputArg> &Outs,
1831 const SmallVectorImpl<SDValue> &OutVals,
1832 SDLoc dl, SelectionDAG &DAG) const {
1833 MachineFunction &MF = DAG.getMachineFunction();
1834 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1836 SmallVector<CCValAssign, 16> RVLocs;
1837 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1838 RVLocs, *DAG.getContext());
1839 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1842 SmallVector<SDValue, 6> RetOps;
1843 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1844 // Operand #1 = Bytes To Pop
1845 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1848 // Copy the result values into the output registers.
1849 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1850 CCValAssign &VA = RVLocs[i];
1851 assert(VA.isRegLoc() && "Can only return in registers!");
1852 SDValue ValToCopy = OutVals[i];
1853 EVT ValVT = ValToCopy.getValueType();
1855 // Promote values to the appropriate types
1856 if (VA.getLocInfo() == CCValAssign::SExt)
1857 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1858 else if (VA.getLocInfo() == CCValAssign::ZExt)
1859 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1860 else if (VA.getLocInfo() == CCValAssign::AExt)
1861 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1862 else if (VA.getLocInfo() == CCValAssign::BCvt)
1863 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1865 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1866 "Unexpected FP-extend for return value.");
1868 // If this is x86-64, and we disabled SSE, we can't return FP values,
1869 // or SSE or MMX vectors.
1870 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1871 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1872 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1873 report_fatal_error("SSE register return with SSE disabled");
1875 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1876 // llvm-gcc has never done it right and no one has noticed, so this
1877 // should be OK for now.
1878 if (ValVT == MVT::f64 &&
1879 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1880 report_fatal_error("SSE2 register return with SSE2 disabled");
1882 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1883 // the RET instruction and handled by the FP Stackifier.
1884 if (VA.getLocReg() == X86::ST0 ||
1885 VA.getLocReg() == X86::ST1) {
1886 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1887 // change the value to the FP stack register class.
1888 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1889 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1890 RetOps.push_back(ValToCopy);
1891 // Don't emit a copytoreg.
1895 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1896 // which is returned in RAX / RDX.
1897 if (Subtarget->is64Bit()) {
1898 if (ValVT == MVT::x86mmx) {
1899 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1900 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1901 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1903 // If we don't have SSE2 available, convert to v4f32 so the generated
1904 // register is legal.
1905 if (!Subtarget->hasSSE2())
1906 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1911 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1912 Flag = Chain.getValue(1);
1913 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1916 // The x86-64 ABIs require that for returning structs by value we copy
1917 // the sret argument into %rax/%eax (depending on ABI) for the return.
1918 // Win32 requires us to put the sret argument to %eax as well.
1919 // We saved the argument into a virtual register in the entry block,
1920 // so now we copy the value out and into %rax/%eax.
1921 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1922 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1923 MachineFunction &MF = DAG.getMachineFunction();
1924 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1925 unsigned Reg = FuncInfo->getSRetReturnReg();
1927 "SRetReturnReg should have been set in LowerFormalArguments().");
1928 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1931 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1932 X86::RAX : X86::EAX;
1933 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1934 Flag = Chain.getValue(1);
1936 // RAX/EAX now acts like a return value.
1937 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1940 RetOps[0] = Chain; // Update chain.
1942 // Add the flag if we have it.
1944 RetOps.push_back(Flag);
1946 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1949 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1950 if (N->getNumValues() != 1)
1952 if (!N->hasNUsesOfValue(1, 0))
1955 SDValue TCChain = Chain;
1956 SDNode *Copy = *N->use_begin();
1957 if (Copy->getOpcode() == ISD::CopyToReg) {
1958 // If the copy has a glue operand, we conservatively assume it isn't safe to
1959 // perform a tail call.
1960 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1962 TCChain = Copy->getOperand(0);
1963 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1966 bool HasRet = false;
1967 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1969 if (UI->getOpcode() != X86ISD::RET_FLAG)
1982 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1983 ISD::NodeType ExtendKind) const {
1985 // TODO: Is this also valid on 32-bit?
1986 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1987 ReturnMVT = MVT::i8;
1989 ReturnMVT = MVT::i32;
1991 MVT MinVT = getRegisterType(ReturnMVT);
1992 return VT.bitsLT(MinVT) ? MinVT : VT;
1995 /// LowerCallResult - Lower the result values of a call into the
1996 /// appropriate copies out of appropriate physical registers.
1999 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2000 CallingConv::ID CallConv, bool isVarArg,
2001 const SmallVectorImpl<ISD::InputArg> &Ins,
2002 SDLoc dl, SelectionDAG &DAG,
2003 SmallVectorImpl<SDValue> &InVals) const {
2005 // Assign locations to each value returned by this call.
2006 SmallVector<CCValAssign, 16> RVLocs;
2007 bool Is64Bit = Subtarget->is64Bit();
2008 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2009 getTargetMachine(), RVLocs, *DAG.getContext());
2010 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2012 // Copy all of the result registers out of their specified physreg.
2013 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2014 CCValAssign &VA = RVLocs[i];
2015 EVT CopyVT = VA.getValVT();
2017 // If this is x86-64, and we disabled SSE, we can't return FP values
2018 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2019 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2020 report_fatal_error("SSE register return with SSE disabled");
2025 // If this is a call to a function that returns an fp value on the floating
2026 // point stack, we must guarantee the value is popped from the stack, so
2027 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2028 // if the return value is not used. We use the FpPOP_RETVAL instruction
2030 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2031 // If we prefer to use the value in xmm registers, copy it out as f80 and
2032 // use a truncate to move it from fp stack reg to xmm reg.
2033 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2034 SDValue Ops[] = { Chain, InFlag };
2035 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2036 MVT::Other, MVT::Glue, Ops), 1);
2037 Val = Chain.getValue(0);
2039 // Round the f80 to the right size, which also moves it to the appropriate
2041 if (CopyVT != VA.getValVT())
2042 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2043 // This truncation won't change the value.
2044 DAG.getIntPtrConstant(1));
2046 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2047 CopyVT, InFlag).getValue(1);
2048 Val = Chain.getValue(0);
2050 InFlag = Chain.getValue(2);
2051 InVals.push_back(Val);
2057 //===----------------------------------------------------------------------===//
2058 // C & StdCall & Fast Calling Convention implementation
2059 //===----------------------------------------------------------------------===//
2060 // StdCall calling convention seems to be standard for many Windows' API
2061 // routines and around. It differs from C calling convention just a little:
2062 // callee should clean up the stack, not caller. Symbols should be also
2063 // decorated in some fancy way :) It doesn't support any vector arguments.
2064 // For info on fast calling convention see Fast Calling Convention (tail call)
2065 // implementation LowerX86_32FastCCCallTo.
2067 /// CallIsStructReturn - Determines whether a call uses struct return
2069 enum StructReturnType {
2074 static StructReturnType
2075 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2077 return NotStructReturn;
2079 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2080 if (!Flags.isSRet())
2081 return NotStructReturn;
2082 if (Flags.isInReg())
2083 return RegStructReturn;
2084 return StackStructReturn;
2087 /// ArgsAreStructReturn - Determines whether a function uses struct
2088 /// return semantics.
2089 static StructReturnType
2090 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2092 return NotStructReturn;
2094 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2095 if (!Flags.isSRet())
2096 return NotStructReturn;
2097 if (Flags.isInReg())
2098 return RegStructReturn;
2099 return StackStructReturn;
2102 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2103 /// by "Src" to address "Dst" with size and alignment information specified by
2104 /// the specific parameter attribute. The copy will be passed as a byval
2105 /// function parameter.
2107 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2108 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2110 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2112 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2113 /*isVolatile*/false, /*AlwaysInline=*/true,
2114 MachinePointerInfo(), MachinePointerInfo());
2117 /// IsTailCallConvention - Return true if the calling convention is one that
2118 /// supports tail call optimization.
2119 static bool IsTailCallConvention(CallingConv::ID CC) {
2120 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2121 CC == CallingConv::HiPE);
2124 /// \brief Return true if the calling convention is a C calling convention.
2125 static bool IsCCallConvention(CallingConv::ID CC) {
2126 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2127 CC == CallingConv::X86_64_SysV);
2130 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2131 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2135 CallingConv::ID CalleeCC = CS.getCallingConv();
2136 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2142 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2143 /// a tailcall target by changing its ABI.
2144 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2145 bool GuaranteedTailCallOpt) {
2146 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2150 X86TargetLowering::LowerMemArgument(SDValue Chain,
2151 CallingConv::ID CallConv,
2152 const SmallVectorImpl<ISD::InputArg> &Ins,
2153 SDLoc dl, SelectionDAG &DAG,
2154 const CCValAssign &VA,
2155 MachineFrameInfo *MFI,
2157 // Create the nodes corresponding to a load from this parameter slot.
2158 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2159 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2160 getTargetMachine().Options.GuaranteedTailCallOpt);
2161 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2164 // If value is passed by pointer we have address passed instead of the value
2166 if (VA.getLocInfo() == CCValAssign::Indirect)
2167 ValVT = VA.getLocVT();
2169 ValVT = VA.getValVT();
2171 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2172 // changed with more analysis.
2173 // In case of tail call optimization mark all arguments mutable. Since they
2174 // could be overwritten by lowering of arguments in case of a tail call.
2175 if (Flags.isByVal()) {
2176 unsigned Bytes = Flags.getByValSize();
2177 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2178 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2179 return DAG.getFrameIndex(FI, getPointerTy());
2181 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2182 VA.getLocMemOffset(), isImmutable);
2183 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2184 return DAG.getLoad(ValVT, dl, Chain, FIN,
2185 MachinePointerInfo::getFixedStack(FI),
2186 false, false, false, 0);
2191 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2192 CallingConv::ID CallConv,
2194 const SmallVectorImpl<ISD::InputArg> &Ins,
2197 SmallVectorImpl<SDValue> &InVals)
2199 MachineFunction &MF = DAG.getMachineFunction();
2200 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2202 const Function* Fn = MF.getFunction();
2203 if (Fn->hasExternalLinkage() &&
2204 Subtarget->isTargetCygMing() &&
2205 Fn->getName() == "main")
2206 FuncInfo->setForceFramePointer(true);
2208 MachineFrameInfo *MFI = MF.getFrameInfo();
2209 bool Is64Bit = Subtarget->is64Bit();
2210 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2212 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2213 "Var args not supported with calling convention fastcc, ghc or hipe");
2215 // Assign locations to all of the incoming arguments.
2216 SmallVector<CCValAssign, 16> ArgLocs;
2217 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2218 ArgLocs, *DAG.getContext());
2220 // Allocate shadow area for Win64
2222 CCInfo.AllocateStack(32, 8);
2224 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2226 unsigned LastVal = ~0U;
2228 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2229 CCValAssign &VA = ArgLocs[i];
2230 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2232 assert(VA.getValNo() != LastVal &&
2233 "Don't support value assigned to multiple locs yet");
2235 LastVal = VA.getValNo();
2237 if (VA.isRegLoc()) {
2238 EVT RegVT = VA.getLocVT();
2239 const TargetRegisterClass *RC;
2240 if (RegVT == MVT::i32)
2241 RC = &X86::GR32RegClass;
2242 else if (Is64Bit && RegVT == MVT::i64)
2243 RC = &X86::GR64RegClass;
2244 else if (RegVT == MVT::f32)
2245 RC = &X86::FR32RegClass;
2246 else if (RegVT == MVT::f64)
2247 RC = &X86::FR64RegClass;
2248 else if (RegVT.is512BitVector())
2249 RC = &X86::VR512RegClass;
2250 else if (RegVT.is256BitVector())
2251 RC = &X86::VR256RegClass;
2252 else if (RegVT.is128BitVector())
2253 RC = &X86::VR128RegClass;
2254 else if (RegVT == MVT::x86mmx)
2255 RC = &X86::VR64RegClass;
2256 else if (RegVT == MVT::i1)
2257 RC = &X86::VK1RegClass;
2258 else if (RegVT == MVT::v8i1)
2259 RC = &X86::VK8RegClass;
2260 else if (RegVT == MVT::v16i1)
2261 RC = &X86::VK16RegClass;
2263 llvm_unreachable("Unknown argument type!");
2265 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2266 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2268 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2269 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2271 if (VA.getLocInfo() == CCValAssign::SExt)
2272 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2273 DAG.getValueType(VA.getValVT()));
2274 else if (VA.getLocInfo() == CCValAssign::ZExt)
2275 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2276 DAG.getValueType(VA.getValVT()));
2277 else if (VA.getLocInfo() == CCValAssign::BCvt)
2278 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2280 if (VA.isExtInLoc()) {
2281 // Handle MMX values passed in XMM regs.
2282 if (RegVT.isVector())
2283 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2285 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2288 assert(VA.isMemLoc());
2289 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2292 // If value is passed via pointer - do a load.
2293 if (VA.getLocInfo() == CCValAssign::Indirect)
2294 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2295 MachinePointerInfo(), false, false, false, 0);
2297 InVals.push_back(ArgValue);
2300 // The x86-64 ABIs require that for returning structs by value we copy
2301 // the sret argument into %rax/%eax (depending on ABI) for the return.
2302 // Win32 requires us to put the sret argument to %eax as well.
2303 // Save the argument into a virtual register so that we can access it
2304 // from the return points.
2305 if (MF.getFunction()->hasStructRetAttr() &&
2306 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2307 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2308 unsigned Reg = FuncInfo->getSRetReturnReg();
2310 MVT PtrTy = getPointerTy();
2311 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2312 FuncInfo->setSRetReturnReg(Reg);
2314 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2315 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2318 unsigned StackSize = CCInfo.getNextStackOffset();
2319 // Align stack specially for tail calls.
2320 if (FuncIsMadeTailCallSafe(CallConv,
2321 MF.getTarget().Options.GuaranteedTailCallOpt))
2322 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2324 // If the function takes variable number of arguments, make a frame index for
2325 // the start of the first vararg value... for expansion of llvm.va_start.
2327 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2328 CallConv != CallingConv::X86_ThisCall)) {
2329 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2332 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2334 // FIXME: We should really autogenerate these arrays
2335 static const MCPhysReg GPR64ArgRegsWin64[] = {
2336 X86::RCX, X86::RDX, X86::R8, X86::R9
2338 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2339 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2341 static const MCPhysReg XMMArgRegs64Bit[] = {
2342 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2343 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2345 const MCPhysReg *GPR64ArgRegs;
2346 unsigned NumXMMRegs = 0;
2349 // The XMM registers which might contain var arg parameters are shadowed
2350 // in their paired GPR. So we only need to save the GPR to their home
2352 TotalNumIntRegs = 4;
2353 GPR64ArgRegs = GPR64ArgRegsWin64;
2355 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2356 GPR64ArgRegs = GPR64ArgRegs64Bit;
2358 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2361 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2364 bool NoImplicitFloatOps = Fn->getAttributes().
2365 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2366 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2367 "SSE register cannot be used when SSE is disabled!");
2368 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2369 NoImplicitFloatOps) &&
2370 "SSE register cannot be used when SSE is disabled!");
2371 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2372 !Subtarget->hasSSE1())
2373 // Kernel mode asks for SSE to be disabled, so don't push them
2375 TotalNumXMMRegs = 0;
2378 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2379 // Get to the caller-allocated home save location. Add 8 to account
2380 // for the return address.
2381 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2382 FuncInfo->setRegSaveFrameIndex(
2383 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2384 // Fixup to set vararg frame on shadow area (4 x i64).
2386 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2388 // For X86-64, if there are vararg parameters that are passed via
2389 // registers, then we must store them to their spots on the stack so
2390 // they may be loaded by deferencing the result of va_next.
2391 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2392 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2393 FuncInfo->setRegSaveFrameIndex(
2394 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2398 // Store the integer parameter registers.
2399 SmallVector<SDValue, 8> MemOps;
2400 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2402 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2403 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2404 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2405 DAG.getIntPtrConstant(Offset));
2406 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2407 &X86::GR64RegClass);
2408 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2410 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2411 MachinePointerInfo::getFixedStack(
2412 FuncInfo->getRegSaveFrameIndex(), Offset),
2414 MemOps.push_back(Store);
2418 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2419 // Now store the XMM (fp + vector) parameter registers.
2420 SmallVector<SDValue, 11> SaveXMMOps;
2421 SaveXMMOps.push_back(Chain);
2423 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2424 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2425 SaveXMMOps.push_back(ALVal);
2427 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2428 FuncInfo->getRegSaveFrameIndex()));
2429 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2430 FuncInfo->getVarArgsFPOffset()));
2432 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2433 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2434 &X86::VR128RegClass);
2435 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2436 SaveXMMOps.push_back(Val);
2438 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2439 MVT::Other, SaveXMMOps));
2442 if (!MemOps.empty())
2443 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2447 // Some CCs need callee pop.
2448 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2449 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2450 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2452 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2453 // If this is an sret function, the return should pop the hidden pointer.
2454 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2455 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2456 argsAreStructReturn(Ins) == StackStructReturn)
2457 FuncInfo->setBytesToPopOnReturn(4);
2461 // RegSaveFrameIndex is X86-64 only.
2462 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2463 if (CallConv == CallingConv::X86_FastCall ||
2464 CallConv == CallingConv::X86_ThisCall)
2465 // fastcc functions can't have varargs.
2466 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2469 FuncInfo->setArgumentStackSize(StackSize);
2475 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2476 SDValue StackPtr, SDValue Arg,
2477 SDLoc dl, SelectionDAG &DAG,
2478 const CCValAssign &VA,
2479 ISD::ArgFlagsTy Flags) const {
2480 unsigned LocMemOffset = VA.getLocMemOffset();
2481 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2482 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2483 if (Flags.isByVal())
2484 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2486 return DAG.getStore(Chain, dl, Arg, PtrOff,
2487 MachinePointerInfo::getStack(LocMemOffset),
2491 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2492 /// optimization is performed and it is required.
2494 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2495 SDValue &OutRetAddr, SDValue Chain,
2496 bool IsTailCall, bool Is64Bit,
2497 int FPDiff, SDLoc dl) const {
2498 // Adjust the Return address stack slot.
2499 EVT VT = getPointerTy();
2500 OutRetAddr = getReturnAddressFrameIndex(DAG);
2502 // Load the "old" Return address.
2503 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2504 false, false, false, 0);
2505 return SDValue(OutRetAddr.getNode(), 1);
2508 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2509 /// optimization is performed and it is required (FPDiff!=0).
2510 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2511 SDValue Chain, SDValue RetAddrFrIdx,
2512 EVT PtrVT, unsigned SlotSize,
2513 int FPDiff, SDLoc dl) {
2514 // Store the return address to the appropriate stack slot.
2515 if (!FPDiff) return Chain;
2516 // Calculate the new stack slot for the return address.
2517 int NewReturnAddrFI =
2518 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2520 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2521 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2522 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2528 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2529 SmallVectorImpl<SDValue> &InVals) const {
2530 SelectionDAG &DAG = CLI.DAG;
2532 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2533 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2534 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2535 SDValue Chain = CLI.Chain;
2536 SDValue Callee = CLI.Callee;
2537 CallingConv::ID CallConv = CLI.CallConv;
2538 bool &isTailCall = CLI.IsTailCall;
2539 bool isVarArg = CLI.IsVarArg;
2541 MachineFunction &MF = DAG.getMachineFunction();
2542 bool Is64Bit = Subtarget->is64Bit();
2543 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2544 StructReturnType SR = callIsStructReturn(Outs);
2545 bool IsSibcall = false;
2547 if (MF.getTarget().Options.DisableTailCalls)
2550 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2552 // Force this to be a tail call. The verifier rules are enough to ensure
2553 // that we can lower this successfully without moving the return address
2556 } else if (isTailCall) {
2557 // Check if it's really possible to do a tail call.
2558 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2559 isVarArg, SR != NotStructReturn,
2560 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2561 Outs, OutVals, Ins, DAG);
2563 // Sibcalls are automatically detected tailcalls which do not require
2565 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2572 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2573 "Var args not supported with calling convention fastcc, ghc or hipe");
2575 // Analyze operands of the call, assigning locations to each operand.
2576 SmallVector<CCValAssign, 16> ArgLocs;
2577 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2578 ArgLocs, *DAG.getContext());
2580 // Allocate shadow area for Win64
2582 CCInfo.AllocateStack(32, 8);
2584 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2586 // Get a count of how many bytes are to be pushed on the stack.
2587 unsigned NumBytes = CCInfo.getNextStackOffset();
2589 // This is a sibcall. The memory operands are available in caller's
2590 // own caller's stack.
2592 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2593 IsTailCallConvention(CallConv))
2594 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2597 if (isTailCall && !IsSibcall && !IsMustTail) {
2598 // Lower arguments at fp - stackoffset + fpdiff.
2599 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2600 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2602 FPDiff = NumBytesCallerPushed - NumBytes;
2604 // Set the delta of movement of the returnaddr stackslot.
2605 // But only set if delta is greater than previous delta.
2606 if (FPDiff < X86Info->getTCReturnAddrDelta())
2607 X86Info->setTCReturnAddrDelta(FPDiff);
2610 unsigned NumBytesToPush = NumBytes;
2611 unsigned NumBytesToPop = NumBytes;
2613 // If we have an inalloca argument, all stack space has already been allocated
2614 // for us and be right at the top of the stack. We don't support multiple
2615 // arguments passed in memory when using inalloca.
2616 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2618 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2619 "an inalloca argument must be the only memory argument");
2623 Chain = DAG.getCALLSEQ_START(
2624 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2626 SDValue RetAddrFrIdx;
2627 // Load return address for tail calls.
2628 if (isTailCall && FPDiff)
2629 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2630 Is64Bit, FPDiff, dl);
2632 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2633 SmallVector<SDValue, 8> MemOpChains;
2636 // Walk the register/memloc assignments, inserting copies/loads. In the case
2637 // of tail call optimization arguments are handle later.
2638 const X86RegisterInfo *RegInfo =
2639 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2640 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2641 // Skip inalloca arguments, they have already been written.
2642 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2643 if (Flags.isInAlloca())
2646 CCValAssign &VA = ArgLocs[i];
2647 EVT RegVT = VA.getLocVT();
2648 SDValue Arg = OutVals[i];
2649 bool isByVal = Flags.isByVal();
2651 // Promote the value if needed.
2652 switch (VA.getLocInfo()) {
2653 default: llvm_unreachable("Unknown loc info!");
2654 case CCValAssign::Full: break;
2655 case CCValAssign::SExt:
2656 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2658 case CCValAssign::ZExt:
2659 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2661 case CCValAssign::AExt:
2662 if (RegVT.is128BitVector()) {
2663 // Special case: passing MMX values in XMM registers.
2664 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2665 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2666 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2668 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2670 case CCValAssign::BCvt:
2671 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2673 case CCValAssign::Indirect: {
2674 // Store the argument.
2675 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2676 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2677 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2678 MachinePointerInfo::getFixedStack(FI),
2685 if (VA.isRegLoc()) {
2686 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2687 if (isVarArg && IsWin64) {
2688 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2689 // shadow reg if callee is a varargs function.
2690 unsigned ShadowReg = 0;
2691 switch (VA.getLocReg()) {
2692 case X86::XMM0: ShadowReg = X86::RCX; break;
2693 case X86::XMM1: ShadowReg = X86::RDX; break;
2694 case X86::XMM2: ShadowReg = X86::R8; break;
2695 case X86::XMM3: ShadowReg = X86::R9; break;
2698 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2700 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2701 assert(VA.isMemLoc());
2702 if (!StackPtr.getNode())
2703 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2705 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2706 dl, DAG, VA, Flags));
2710 if (!MemOpChains.empty())
2711 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2713 if (Subtarget->isPICStyleGOT()) {
2714 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2717 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2718 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2720 // If we are tail calling and generating PIC/GOT style code load the
2721 // address of the callee into ECX. The value in ecx is used as target of
2722 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2723 // for tail calls on PIC/GOT architectures. Normally we would just put the
2724 // address of GOT into ebx and then call target@PLT. But for tail calls
2725 // ebx would be restored (since ebx is callee saved) before jumping to the
2728 // Note: The actual moving to ECX is done further down.
2729 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2730 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2731 !G->getGlobal()->hasProtectedVisibility())
2732 Callee = LowerGlobalAddress(Callee, DAG);
2733 else if (isa<ExternalSymbolSDNode>(Callee))
2734 Callee = LowerExternalSymbol(Callee, DAG);
2738 if (Is64Bit && isVarArg && !IsWin64) {
2739 // From AMD64 ABI document:
2740 // For calls that may call functions that use varargs or stdargs
2741 // (prototype-less calls or calls to functions containing ellipsis (...) in
2742 // the declaration) %al is used as hidden argument to specify the number
2743 // of SSE registers used. The contents of %al do not need to match exactly
2744 // the number of registers, but must be an ubound on the number of SSE
2745 // registers used and is in the range 0 - 8 inclusive.
2747 // Count the number of XMM registers allocated.
2748 static const MCPhysReg XMMArgRegs[] = {
2749 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2750 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2752 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2753 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2754 && "SSE registers cannot be used when SSE is disabled");
2756 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2757 DAG.getConstant(NumXMMRegs, MVT::i8)));
2760 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2761 // don't need this because the eligibility check rejects calls that require
2762 // shuffling arguments passed in memory.
2763 if (!IsSibcall && isTailCall) {
2764 // Force all the incoming stack arguments to be loaded from the stack
2765 // before any new outgoing arguments are stored to the stack, because the
2766 // outgoing stack slots may alias the incoming argument stack slots, and
2767 // the alias isn't otherwise explicit. This is slightly more conservative
2768 // than necessary, because it means that each store effectively depends
2769 // on every argument instead of just those arguments it would clobber.
2770 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2772 SmallVector<SDValue, 8> MemOpChains2;
2775 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2776 CCValAssign &VA = ArgLocs[i];
2779 assert(VA.isMemLoc());
2780 SDValue Arg = OutVals[i];
2781 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2782 // Skip inalloca arguments. They don't require any work.
2783 if (Flags.isInAlloca())
2785 // Create frame index.
2786 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2787 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2788 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2789 FIN = DAG.getFrameIndex(FI, getPointerTy());
2791 if (Flags.isByVal()) {
2792 // Copy relative to framepointer.
2793 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2794 if (!StackPtr.getNode())
2795 StackPtr = DAG.getCopyFromReg(Chain, dl,
2796 RegInfo->getStackRegister(),
2798 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2800 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2804 // Store relative to framepointer.
2805 MemOpChains2.push_back(
2806 DAG.getStore(ArgChain, dl, Arg, FIN,
2807 MachinePointerInfo::getFixedStack(FI),
2812 if (!MemOpChains2.empty())
2813 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2815 // Store the return address to the appropriate stack slot.
2816 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2817 getPointerTy(), RegInfo->getSlotSize(),
2821 // Build a sequence of copy-to-reg nodes chained together with token chain
2822 // and flag operands which copy the outgoing args into registers.
2824 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2825 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2826 RegsToPass[i].second, InFlag);
2827 InFlag = Chain.getValue(1);
2830 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2831 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2832 // In the 64-bit large code model, we have to make all calls
2833 // through a register, since the call instruction's 32-bit
2834 // pc-relative offset may not be large enough to hold the whole
2836 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2837 // If the callee is a GlobalAddress node (quite common, every direct call
2838 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2841 // We should use extra load for direct calls to dllimported functions in
2843 const GlobalValue *GV = G->getGlobal();
2844 if (!GV->hasDLLImportStorageClass()) {
2845 unsigned char OpFlags = 0;
2846 bool ExtraLoad = false;
2847 unsigned WrapperKind = ISD::DELETED_NODE;
2849 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2850 // external symbols most go through the PLT in PIC mode. If the symbol
2851 // has hidden or protected visibility, or if it is static or local, then
2852 // we don't need to use the PLT - we can directly call it.
2853 if (Subtarget->isTargetELF() &&
2854 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2855 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2856 OpFlags = X86II::MO_PLT;
2857 } else if (Subtarget->isPICStyleStubAny() &&
2858 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2859 (!Subtarget->getTargetTriple().isMacOSX() ||
2860 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2861 // PC-relative references to external symbols should go through $stub,
2862 // unless we're building with the leopard linker or later, which
2863 // automatically synthesizes these stubs.
2864 OpFlags = X86II::MO_DARWIN_STUB;
2865 } else if (Subtarget->isPICStyleRIPRel() &&
2866 isa<Function>(GV) &&
2867 cast<Function>(GV)->getAttributes().
2868 hasAttribute(AttributeSet::FunctionIndex,
2869 Attribute::NonLazyBind)) {
2870 // If the function is marked as non-lazy, generate an indirect call
2871 // which loads from the GOT directly. This avoids runtime overhead
2872 // at the cost of eager binding (and one extra byte of encoding).
2873 OpFlags = X86II::MO_GOTPCREL;
2874 WrapperKind = X86ISD::WrapperRIP;
2878 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2879 G->getOffset(), OpFlags);
2881 // Add a wrapper if needed.
2882 if (WrapperKind != ISD::DELETED_NODE)
2883 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2884 // Add extra indirection if needed.
2886 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2887 MachinePointerInfo::getGOT(),
2888 false, false, false, 0);
2890 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2891 unsigned char OpFlags = 0;
2893 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2894 // external symbols should go through the PLT.
2895 if (Subtarget->isTargetELF() &&
2896 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2897 OpFlags = X86II::MO_PLT;
2898 } else if (Subtarget->isPICStyleStubAny() &&
2899 (!Subtarget->getTargetTriple().isMacOSX() ||
2900 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2901 // PC-relative references to external symbols should go through $stub,
2902 // unless we're building with the leopard linker or later, which
2903 // automatically synthesizes these stubs.
2904 OpFlags = X86II::MO_DARWIN_STUB;
2907 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2911 // Returns a chain & a flag for retval copy to use.
2912 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2913 SmallVector<SDValue, 8> Ops;
2915 if (!IsSibcall && isTailCall) {
2916 Chain = DAG.getCALLSEQ_END(Chain,
2917 DAG.getIntPtrConstant(NumBytesToPop, true),
2918 DAG.getIntPtrConstant(0, true), InFlag, dl);
2919 InFlag = Chain.getValue(1);
2922 Ops.push_back(Chain);
2923 Ops.push_back(Callee);
2926 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2928 // Add argument registers to the end of the list so that they are known live
2930 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2931 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2932 RegsToPass[i].second.getValueType()));
2934 // Add a register mask operand representing the call-preserved registers.
2935 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2936 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2937 assert(Mask && "Missing call preserved mask for calling convention");
2938 Ops.push_back(DAG.getRegisterMask(Mask));
2940 if (InFlag.getNode())
2941 Ops.push_back(InFlag);
2945 //// If this is the first return lowered for this function, add the regs
2946 //// to the liveout set for the function.
2947 // This isn't right, although it's probably harmless on x86; liveouts
2948 // should be computed from returns not tail calls. Consider a void
2949 // function making a tail call to a function returning int.
2950 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2953 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2954 InFlag = Chain.getValue(1);
2956 // Create the CALLSEQ_END node.
2957 unsigned NumBytesForCalleeToPop;
2958 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2959 getTargetMachine().Options.GuaranteedTailCallOpt))
2960 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2961 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2962 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2963 SR == StackStructReturn)
2964 // If this is a call to a struct-return function, the callee
2965 // pops the hidden struct pointer, so we have to push it back.
2966 // This is common for Darwin/X86, Linux & Mingw32 targets.
2967 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2968 NumBytesForCalleeToPop = 4;
2970 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2972 // Returns a flag for retval copy to use.
2974 Chain = DAG.getCALLSEQ_END(Chain,
2975 DAG.getIntPtrConstant(NumBytesToPop, true),
2976 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2979 InFlag = Chain.getValue(1);
2982 // Handle result values, copying them out of physregs into vregs that we
2984 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2985 Ins, dl, DAG, InVals);
2988 //===----------------------------------------------------------------------===//
2989 // Fast Calling Convention (tail call) implementation
2990 //===----------------------------------------------------------------------===//
2992 // Like std call, callee cleans arguments, convention except that ECX is
2993 // reserved for storing the tail called function address. Only 2 registers are
2994 // free for argument passing (inreg). Tail call optimization is performed
2996 // * tailcallopt is enabled
2997 // * caller/callee are fastcc
2998 // On X86_64 architecture with GOT-style position independent code only local
2999 // (within module) calls are supported at the moment.
3000 // To keep the stack aligned according to platform abi the function
3001 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3002 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3003 // If a tail called function callee has more arguments than the caller the
3004 // caller needs to make sure that there is room to move the RETADDR to. This is
3005 // achieved by reserving an area the size of the argument delta right after the
3006 // original REtADDR, but before the saved framepointer or the spilled registers
3007 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3019 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3020 /// for a 16 byte align requirement.
3022 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3023 SelectionDAG& DAG) const {
3024 MachineFunction &MF = DAG.getMachineFunction();
3025 const TargetMachine &TM = MF.getTarget();
3026 const X86RegisterInfo *RegInfo =
3027 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3028 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3029 unsigned StackAlignment = TFI.getStackAlignment();
3030 uint64_t AlignMask = StackAlignment - 1;
3031 int64_t Offset = StackSize;
3032 unsigned SlotSize = RegInfo->getSlotSize();
3033 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3034 // Number smaller than 12 so just add the difference.
3035 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3037 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3038 Offset = ((~AlignMask) & Offset) + StackAlignment +
3039 (StackAlignment-SlotSize);
3044 /// MatchingStackOffset - Return true if the given stack call argument is
3045 /// already available in the same position (relatively) of the caller's
3046 /// incoming argument stack.
3048 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3049 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3050 const X86InstrInfo *TII) {
3051 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3053 if (Arg.getOpcode() == ISD::CopyFromReg) {
3054 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3055 if (!TargetRegisterInfo::isVirtualRegister(VR))
3057 MachineInstr *Def = MRI->getVRegDef(VR);
3060 if (!Flags.isByVal()) {
3061 if (!TII->isLoadFromStackSlot(Def, FI))
3064 unsigned Opcode = Def->getOpcode();
3065 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3066 Def->getOperand(1).isFI()) {
3067 FI = Def->getOperand(1).getIndex();
3068 Bytes = Flags.getByValSize();
3072 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3073 if (Flags.isByVal())
3074 // ByVal argument is passed in as a pointer but it's now being
3075 // dereferenced. e.g.
3076 // define @foo(%struct.X* %A) {
3077 // tail call @bar(%struct.X* byval %A)
3080 SDValue Ptr = Ld->getBasePtr();
3081 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3084 FI = FINode->getIndex();
3085 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3086 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3087 FI = FINode->getIndex();
3088 Bytes = Flags.getByValSize();
3092 assert(FI != INT_MAX);
3093 if (!MFI->isFixedObjectIndex(FI))
3095 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3098 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3099 /// for tail call optimization. Targets which want to do tail call
3100 /// optimization should implement this function.
3102 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3103 CallingConv::ID CalleeCC,
3105 bool isCalleeStructRet,
3106 bool isCallerStructRet,
3108 const SmallVectorImpl<ISD::OutputArg> &Outs,
3109 const SmallVectorImpl<SDValue> &OutVals,
3110 const SmallVectorImpl<ISD::InputArg> &Ins,
3111 SelectionDAG &DAG) const {
3112 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3115 // If -tailcallopt is specified, make fastcc functions tail-callable.
3116 const MachineFunction &MF = DAG.getMachineFunction();
3117 const Function *CallerF = MF.getFunction();
3119 // If the function return type is x86_fp80 and the callee return type is not,
3120 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3121 // perform a tailcall optimization here.
3122 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3125 CallingConv::ID CallerCC = CallerF->getCallingConv();
3126 bool CCMatch = CallerCC == CalleeCC;
3127 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3128 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3130 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3131 if (IsTailCallConvention(CalleeCC) && CCMatch)
3136 // Look for obvious safe cases to perform tail call optimization that do not
3137 // require ABI changes. This is what gcc calls sibcall.
3139 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3140 // emit a special epilogue.
3141 const X86RegisterInfo *RegInfo =
3142 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3143 if (RegInfo->needsStackRealignment(MF))
3146 // Also avoid sibcall optimization if either caller or callee uses struct
3147 // return semantics.
3148 if (isCalleeStructRet || isCallerStructRet)
3151 // An stdcall/thiscall caller is expected to clean up its arguments; the
3152 // callee isn't going to do that.
3153 // FIXME: this is more restrictive than needed. We could produce a tailcall
3154 // when the stack adjustment matches. For example, with a thiscall that takes
3155 // only one argument.
3156 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3157 CallerCC == CallingConv::X86_ThisCall))
3160 // Do not sibcall optimize vararg calls unless all arguments are passed via
3162 if (isVarArg && !Outs.empty()) {
3164 // Optimizing for varargs on Win64 is unlikely to be safe without
3165 // additional testing.
3166 if (IsCalleeWin64 || IsCallerWin64)
3169 SmallVector<CCValAssign, 16> ArgLocs;
3170 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3171 getTargetMachine(), ArgLocs, *DAG.getContext());
3173 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3174 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3175 if (!ArgLocs[i].isRegLoc())
3179 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3180 // stack. Therefore, if it's not used by the call it is not safe to optimize
3181 // this into a sibcall.
3182 bool Unused = false;
3183 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3190 SmallVector<CCValAssign, 16> RVLocs;
3191 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3192 getTargetMachine(), RVLocs, *DAG.getContext());
3193 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3194 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3195 CCValAssign &VA = RVLocs[i];
3196 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3201 // If the calling conventions do not match, then we'd better make sure the
3202 // results are returned in the same way as what the caller expects.
3204 SmallVector<CCValAssign, 16> RVLocs1;
3205 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3206 getTargetMachine(), RVLocs1, *DAG.getContext());
3207 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3209 SmallVector<CCValAssign, 16> RVLocs2;
3210 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3211 getTargetMachine(), RVLocs2, *DAG.getContext());
3212 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3214 if (RVLocs1.size() != RVLocs2.size())
3216 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3217 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3219 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3221 if (RVLocs1[i].isRegLoc()) {
3222 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3225 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3231 // If the callee takes no arguments then go on to check the results of the
3233 if (!Outs.empty()) {
3234 // Check if stack adjustment is needed. For now, do not do this if any
3235 // argument is passed on the stack.
3236 SmallVector<CCValAssign, 16> ArgLocs;
3237 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3238 getTargetMachine(), ArgLocs, *DAG.getContext());
3240 // Allocate shadow area for Win64
3242 CCInfo.AllocateStack(32, 8);
3244 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3245 if (CCInfo.getNextStackOffset()) {
3246 MachineFunction &MF = DAG.getMachineFunction();
3247 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3250 // Check if the arguments are already laid out in the right way as
3251 // the caller's fixed stack objects.
3252 MachineFrameInfo *MFI = MF.getFrameInfo();
3253 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3254 const X86InstrInfo *TII =
3255 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3256 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3257 CCValAssign &VA = ArgLocs[i];
3258 SDValue Arg = OutVals[i];
3259 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3260 if (VA.getLocInfo() == CCValAssign::Indirect)
3262 if (!VA.isRegLoc()) {
3263 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3270 // If the tailcall address may be in a register, then make sure it's
3271 // possible to register allocate for it. In 32-bit, the call address can
3272 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3273 // callee-saved registers are restored. These happen to be the same
3274 // registers used to pass 'inreg' arguments so watch out for those.
3275 if (!Subtarget->is64Bit() &&
3276 ((!isa<GlobalAddressSDNode>(Callee) &&
3277 !isa<ExternalSymbolSDNode>(Callee)) ||
3278 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3279 unsigned NumInRegs = 0;
3280 // In PIC we need an extra register to formulate the address computation
3282 unsigned MaxInRegs =
3283 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3285 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3286 CCValAssign &VA = ArgLocs[i];
3289 unsigned Reg = VA.getLocReg();
3292 case X86::EAX: case X86::EDX: case X86::ECX:
3293 if (++NumInRegs == MaxInRegs)
3305 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3306 const TargetLibraryInfo *libInfo) const {
3307 return X86::createFastISel(funcInfo, libInfo);
3310 //===----------------------------------------------------------------------===//
3311 // Other Lowering Hooks
3312 //===----------------------------------------------------------------------===//
3314 static bool MayFoldLoad(SDValue Op) {
3315 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3318 static bool MayFoldIntoStore(SDValue Op) {
3319 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3322 static bool isTargetShuffle(unsigned Opcode) {
3324 default: return false;
3325 case X86ISD::PSHUFD:
3326 case X86ISD::PSHUFHW:
3327 case X86ISD::PSHUFLW:
3329 case X86ISD::PALIGNR:
3330 case X86ISD::MOVLHPS:
3331 case X86ISD::MOVLHPD:
3332 case X86ISD::MOVHLPS:
3333 case X86ISD::MOVLPS:
3334 case X86ISD::MOVLPD:
3335 case X86ISD::MOVSHDUP:
3336 case X86ISD::MOVSLDUP:
3337 case X86ISD::MOVDDUP:
3340 case X86ISD::UNPCKL:
3341 case X86ISD::UNPCKH:
3342 case X86ISD::VPERMILP:
3343 case X86ISD::VPERM2X128:
3344 case X86ISD::VPERMI:
3349 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3350 SDValue V1, SelectionDAG &DAG) {
3352 default: llvm_unreachable("Unknown x86 shuffle node");
3353 case X86ISD::MOVSHDUP:
3354 case X86ISD::MOVSLDUP:
3355 case X86ISD::MOVDDUP:
3356 return DAG.getNode(Opc, dl, VT, V1);
3360 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3361 SDValue V1, unsigned TargetMask,
3362 SelectionDAG &DAG) {
3364 default: llvm_unreachable("Unknown x86 shuffle node");
3365 case X86ISD::PSHUFD:
3366 case X86ISD::PSHUFHW:
3367 case X86ISD::PSHUFLW:
3368 case X86ISD::VPERMILP:
3369 case X86ISD::VPERMI:
3370 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375 SDValue V1, SDValue V2, unsigned TargetMask,
3376 SelectionDAG &DAG) {
3378 default: llvm_unreachable("Unknown x86 shuffle node");
3379 case X86ISD::PALIGNR:
3381 case X86ISD::VPERM2X128:
3382 return DAG.getNode(Opc, dl, VT, V1, V2,
3383 DAG.getConstant(TargetMask, MVT::i8));
3387 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3388 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3390 default: llvm_unreachable("Unknown x86 shuffle node");
3391 case X86ISD::MOVLHPS:
3392 case X86ISD::MOVLHPD:
3393 case X86ISD::MOVHLPS:
3394 case X86ISD::MOVLPS:
3395 case X86ISD::MOVLPD:
3398 case X86ISD::UNPCKL:
3399 case X86ISD::UNPCKH:
3400 return DAG.getNode(Opc, dl, VT, V1, V2);
3404 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3405 MachineFunction &MF = DAG.getMachineFunction();
3406 const X86RegisterInfo *RegInfo =
3407 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3408 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3409 int ReturnAddrIndex = FuncInfo->getRAIndex();
3411 if (ReturnAddrIndex == 0) {
3412 // Set up a frame object for the return address.
3413 unsigned SlotSize = RegInfo->getSlotSize();
3414 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3417 FuncInfo->setRAIndex(ReturnAddrIndex);
3420 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3423 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3424 bool hasSymbolicDisplacement) {
3425 // Offset should fit into 32 bit immediate field.
3426 if (!isInt<32>(Offset))
3429 // If we don't have a symbolic displacement - we don't have any extra
3431 if (!hasSymbolicDisplacement)
3434 // FIXME: Some tweaks might be needed for medium code model.
3435 if (M != CodeModel::Small && M != CodeModel::Kernel)
3438 // For small code model we assume that latest object is 16MB before end of 31
3439 // bits boundary. We may also accept pretty large negative constants knowing
3440 // that all objects are in the positive half of address space.
3441 if (M == CodeModel::Small && Offset < 16*1024*1024)
3444 // For kernel code model we know that all object resist in the negative half
3445 // of 32bits address space. We may not accept negative offsets, since they may
3446 // be just off and we may accept pretty large positive ones.
3447 if (M == CodeModel::Kernel && Offset > 0)
3453 /// isCalleePop - Determines whether the callee is required to pop its
3454 /// own arguments. Callee pop is necessary to support tail calls.
3455 bool X86::isCalleePop(CallingConv::ID CallingConv,
3456 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3460 switch (CallingConv) {
3463 case CallingConv::X86_StdCall:
3465 case CallingConv::X86_FastCall:
3467 case CallingConv::X86_ThisCall:
3469 case CallingConv::Fast:
3471 case CallingConv::GHC:
3473 case CallingConv::HiPE:
3478 /// \brief Return true if the condition is an unsigned comparison operation.
3479 static bool isX86CCUnsigned(unsigned X86CC) {
3481 default: llvm_unreachable("Invalid integer condition!");
3482 case X86::COND_E: return true;
3483 case X86::COND_G: return false;
3484 case X86::COND_GE: return false;
3485 case X86::COND_L: return false;
3486 case X86::COND_LE: return false;
3487 case X86::COND_NE: return true;
3488 case X86::COND_B: return true;
3489 case X86::COND_A: return true;
3490 case X86::COND_BE: return true;
3491 case X86::COND_AE: return true;
3493 llvm_unreachable("covered switch fell through?!");
3496 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3497 /// specific condition code, returning the condition code and the LHS/RHS of the
3498 /// comparison to make.
3499 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3500 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3502 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3503 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3504 // X > -1 -> X == 0, jump !sign.
3505 RHS = DAG.getConstant(0, RHS.getValueType());
3506 return X86::COND_NS;
3508 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3509 // X < 0 -> X == 0, jump on sign.
3512 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3514 RHS = DAG.getConstant(0, RHS.getValueType());
3515 return X86::COND_LE;
3519 switch (SetCCOpcode) {
3520 default: llvm_unreachable("Invalid integer condition!");
3521 case ISD::SETEQ: return X86::COND_E;
3522 case ISD::SETGT: return X86::COND_G;
3523 case ISD::SETGE: return X86::COND_GE;
3524 case ISD::SETLT: return X86::COND_L;
3525 case ISD::SETLE: return X86::COND_LE;
3526 case ISD::SETNE: return X86::COND_NE;
3527 case ISD::SETULT: return X86::COND_B;
3528 case ISD::SETUGT: return X86::COND_A;
3529 case ISD::SETULE: return X86::COND_BE;
3530 case ISD::SETUGE: return X86::COND_AE;
3534 // First determine if it is required or is profitable to flip the operands.
3536 // If LHS is a foldable load, but RHS is not, flip the condition.
3537 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3538 !ISD::isNON_EXTLoad(RHS.getNode())) {
3539 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3540 std::swap(LHS, RHS);
3543 switch (SetCCOpcode) {
3549 std::swap(LHS, RHS);
3553 // On a floating point condition, the flags are set as follows:
3555 // 0 | 0 | 0 | X > Y
3556 // 0 | 0 | 1 | X < Y
3557 // 1 | 0 | 0 | X == Y
3558 // 1 | 1 | 1 | unordered
3559 switch (SetCCOpcode) {
3560 default: llvm_unreachable("Condcode should be pre-legalized away");
3562 case ISD::SETEQ: return X86::COND_E;
3563 case ISD::SETOLT: // flipped
3565 case ISD::SETGT: return X86::COND_A;
3566 case ISD::SETOLE: // flipped
3568 case ISD::SETGE: return X86::COND_AE;
3569 case ISD::SETUGT: // flipped
3571 case ISD::SETLT: return X86::COND_B;
3572 case ISD::SETUGE: // flipped
3574 case ISD::SETLE: return X86::COND_BE;
3576 case ISD::SETNE: return X86::COND_NE;
3577 case ISD::SETUO: return X86::COND_P;
3578 case ISD::SETO: return X86::COND_NP;
3580 case ISD::SETUNE: return X86::COND_INVALID;
3584 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3585 /// code. Current x86 isa includes the following FP cmov instructions:
3586 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3587 static bool hasFPCMov(unsigned X86CC) {
3603 /// isFPImmLegal - Returns true if the target can instruction select the
3604 /// specified FP immediate natively. If false, the legalizer will
3605 /// materialize the FP immediate as a load from a constant pool.
3606 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3607 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3608 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3614 /// \brief Returns true if it is beneficial to convert a load of a constant
3615 /// to just the constant itself.
3616 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3618 assert(Ty->isIntegerTy());
3620 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3621 if (BitSize == 0 || BitSize > 64)
3626 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3627 /// the specified range (L, H].
3628 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3629 return (Val < 0) || (Val >= Low && Val < Hi);
3632 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3633 /// specified value.
3634 static bool isUndefOrEqual(int Val, int CmpVal) {
3635 return (Val < 0 || Val == CmpVal);
3638 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3639 /// from position Pos and ending in Pos+Size, falls within the specified
3640 /// sequential range (L, L+Pos]. or is undef.
3641 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3642 unsigned Pos, unsigned Size, int Low) {
3643 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3644 if (!isUndefOrEqual(Mask[i], Low))
3649 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3650 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3651 /// the second operand.
3652 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3653 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3654 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3655 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3656 return (Mask[0] < 2 && Mask[1] < 2);
3660 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3661 /// is suitable for input to PSHUFHW.
3662 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3663 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3666 // Lower quadword copied in order or undef.
3667 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3670 // Upper quadword shuffled.
3671 for (unsigned i = 4; i != 8; ++i)
3672 if (!isUndefOrInRange(Mask[i], 4, 8))
3675 if (VT == MVT::v16i16) {
3676 // Lower quadword copied in order or undef.
3677 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3680 // Upper quadword shuffled.
3681 for (unsigned i = 12; i != 16; ++i)
3682 if (!isUndefOrInRange(Mask[i], 12, 16))
3689 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3690 /// is suitable for input to PSHUFLW.
3691 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3692 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3695 // Upper quadword copied in order.
3696 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3699 // Lower quadword shuffled.
3700 for (unsigned i = 0; i != 4; ++i)
3701 if (!isUndefOrInRange(Mask[i], 0, 4))
3704 if (VT == MVT::v16i16) {
3705 // Upper quadword copied in order.
3706 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3709 // Lower quadword shuffled.
3710 for (unsigned i = 8; i != 12; ++i)
3711 if (!isUndefOrInRange(Mask[i], 8, 12))
3718 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3719 /// is suitable for input to PALIGNR.
3720 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3721 const X86Subtarget *Subtarget) {
3722 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3723 (VT.is256BitVector() && !Subtarget->hasInt256()))
3726 unsigned NumElts = VT.getVectorNumElements();
3727 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3728 unsigned NumLaneElts = NumElts/NumLanes;
3730 // Do not handle 64-bit element shuffles with palignr.
3731 if (NumLaneElts == 2)
3734 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3736 for (i = 0; i != NumLaneElts; ++i) {
3741 // Lane is all undef, go to next lane
3742 if (i == NumLaneElts)
3745 int Start = Mask[i+l];
3747 // Make sure its in this lane in one of the sources
3748 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3749 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3752 // If not lane 0, then we must match lane 0
3753 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3756 // Correct second source to be contiguous with first source
3757 if (Start >= (int)NumElts)
3758 Start -= NumElts - NumLaneElts;
3760 // Make sure we're shifting in the right direction.
3761 if (Start <= (int)(i+l))
3766 // Check the rest of the elements to see if they are consecutive.
3767 for (++i; i != NumLaneElts; ++i) {
3768 int Idx = Mask[i+l];
3770 // Make sure its in this lane
3771 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3772 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3775 // If not lane 0, then we must match lane 0
3776 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3779 if (Idx >= (int)NumElts)
3780 Idx -= NumElts - NumLaneElts;
3782 if (!isUndefOrEqual(Idx, Start+i))
3791 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3792 /// the two vector operands have swapped position.
3793 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3794 unsigned NumElems) {
3795 for (unsigned i = 0; i != NumElems; ++i) {
3799 else if (idx < (int)NumElems)
3800 Mask[i] = idx + NumElems;
3802 Mask[i] = idx - NumElems;
3806 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3807 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3808 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3809 /// reverse of what x86 shuffles want.
3810 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3812 unsigned NumElems = VT.getVectorNumElements();
3813 unsigned NumLanes = VT.getSizeInBits()/128;
3814 unsigned NumLaneElems = NumElems/NumLanes;
3816 if (NumLaneElems != 2 && NumLaneElems != 4)
3819 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3820 bool symetricMaskRequired =
3821 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3823 // VSHUFPSY divides the resulting vector into 4 chunks.
3824 // The sources are also splitted into 4 chunks, and each destination
3825 // chunk must come from a different source chunk.
3827 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3828 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3830 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3831 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3833 // VSHUFPDY divides the resulting vector into 4 chunks.
3834 // The sources are also splitted into 4 chunks, and each destination
3835 // chunk must come from a different source chunk.
3837 // SRC1 => X3 X2 X1 X0
3838 // SRC2 => Y3 Y2 Y1 Y0
3840 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3842 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3843 unsigned HalfLaneElems = NumLaneElems/2;
3844 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3845 for (unsigned i = 0; i != NumLaneElems; ++i) {
3846 int Idx = Mask[i+l];
3847 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3848 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3850 // For VSHUFPSY, the mask of the second half must be the same as the
3851 // first but with the appropriate offsets. This works in the same way as
3852 // VPERMILPS works with masks.
3853 if (!symetricMaskRequired || Idx < 0)
3855 if (MaskVal[i] < 0) {
3856 MaskVal[i] = Idx - l;
3859 if ((signed)(Idx - l) != MaskVal[i])
3867 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3868 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3869 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3870 if (!VT.is128BitVector())
3873 unsigned NumElems = VT.getVectorNumElements();
3878 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3879 return isUndefOrEqual(Mask[0], 6) &&
3880 isUndefOrEqual(Mask[1], 7) &&
3881 isUndefOrEqual(Mask[2], 2) &&
3882 isUndefOrEqual(Mask[3], 3);
3885 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3886 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3888 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3889 if (!VT.is128BitVector())
3892 unsigned NumElems = VT.getVectorNumElements();
3897 return isUndefOrEqual(Mask[0], 2) &&
3898 isUndefOrEqual(Mask[1], 3) &&
3899 isUndefOrEqual(Mask[2], 2) &&
3900 isUndefOrEqual(Mask[3], 3);
3903 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3905 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3906 if (!VT.is128BitVector())
3909 unsigned NumElems = VT.getVectorNumElements();
3911 if (NumElems != 2 && NumElems != 4)
3914 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3915 if (!isUndefOrEqual(Mask[i], i + NumElems))
3918 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3919 if (!isUndefOrEqual(Mask[i], i))
3925 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3926 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3927 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3928 if (!VT.is128BitVector())
3931 unsigned NumElems = VT.getVectorNumElements();
3933 if (NumElems != 2 && NumElems != 4)
3936 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3937 if (!isUndefOrEqual(Mask[i], i))
3940 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3941 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3947 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3948 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3949 /// i. e: If all but one element come from the same vector.
3950 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3951 // TODO: Deal with AVX's VINSERTPS
3952 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3955 unsigned CorrectPosV1 = 0;
3956 unsigned CorrectPosV2 = 0;
3957 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3960 else if (Mask[i] == i + 4)
3963 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3964 // We have 3 elements from one vector, and one from another.
3971 // Some special combinations that can be optimized.
3974 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3975 SelectionDAG &DAG) {
3976 MVT VT = SVOp->getSimpleValueType(0);
3979 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3982 ArrayRef<int> Mask = SVOp->getMask();
3984 // These are the special masks that may be optimized.
3985 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3986 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3987 bool MatchEvenMask = true;
3988 bool MatchOddMask = true;
3989 for (int i=0; i<8; ++i) {
3990 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3991 MatchEvenMask = false;
3992 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3993 MatchOddMask = false;
3996 if (!MatchEvenMask && !MatchOddMask)
3999 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4001 SDValue Op0 = SVOp->getOperand(0);
4002 SDValue Op1 = SVOp->getOperand(1);
4004 if (MatchEvenMask) {
4005 // Shift the second operand right to 32 bits.
4006 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4007 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4009 // Shift the first operand left to 32 bits.
4010 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4011 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4013 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4014 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4017 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4018 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4019 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4020 bool HasInt256, bool V2IsSplat = false) {
4022 assert(VT.getSizeInBits() >= 128 &&
4023 "Unsupported vector type for unpckl");
4025 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4027 unsigned NumOf256BitLanes;
4028 unsigned NumElts = VT.getVectorNumElements();
4029 if (VT.is256BitVector()) {
4030 if (NumElts != 4 && NumElts != 8 &&
4031 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4034 NumOf256BitLanes = 1;
4035 } else if (VT.is512BitVector()) {
4036 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4037 "Unsupported vector type for unpckh");
4039 NumOf256BitLanes = 2;
4042 NumOf256BitLanes = 1;
4045 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4046 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4048 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4049 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4050 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4051 int BitI = Mask[l256*NumEltsInStride+l+i];
4052 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4053 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4055 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4057 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4065 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4066 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4067 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4068 bool HasInt256, bool V2IsSplat = false) {
4069 assert(VT.getSizeInBits() >= 128 &&
4070 "Unsupported vector type for unpckh");
4072 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4074 unsigned NumOf256BitLanes;
4075 unsigned NumElts = VT.getVectorNumElements();
4076 if (VT.is256BitVector()) {
4077 if (NumElts != 4 && NumElts != 8 &&
4078 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4081 NumOf256BitLanes = 1;
4082 } else if (VT.is512BitVector()) {
4083 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4084 "Unsupported vector type for unpckh");
4086 NumOf256BitLanes = 2;
4089 NumOf256BitLanes = 1;
4092 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4093 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4095 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4096 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4097 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4098 int BitI = Mask[l256*NumEltsInStride+l+i];
4099 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4100 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4102 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4104 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4112 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4113 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4115 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4116 unsigned NumElts = VT.getVectorNumElements();
4117 bool Is256BitVec = VT.is256BitVector();
4119 if (VT.is512BitVector())
4121 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4122 "Unsupported vector type for unpckh");
4124 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4125 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4128 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4129 // FIXME: Need a better way to get rid of this, there's no latency difference
4130 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4131 // the former later. We should also remove the "_undef" special mask.
4132 if (NumElts == 4 && Is256BitVec)
4135 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4136 // independently on 128-bit lanes.
4137 unsigned NumLanes = VT.getSizeInBits()/128;
4138 unsigned NumLaneElts = NumElts/NumLanes;
4140 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4141 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4142 int BitI = Mask[l+i];
4143 int BitI1 = Mask[l+i+1];
4145 if (!isUndefOrEqual(BitI, j))
4147 if (!isUndefOrEqual(BitI1, j))
4155 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4156 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4158 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4159 unsigned NumElts = VT.getVectorNumElements();
4161 if (VT.is512BitVector())
4164 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4165 "Unsupported vector type for unpckh");
4167 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4168 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4171 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4172 // independently on 128-bit lanes.
4173 unsigned NumLanes = VT.getSizeInBits()/128;
4174 unsigned NumLaneElts = NumElts/NumLanes;
4176 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4177 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4178 int BitI = Mask[l+i];
4179 int BitI1 = Mask[l+i+1];
4180 if (!isUndefOrEqual(BitI, j))
4182 if (!isUndefOrEqual(BitI1, j))
4189 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4190 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4191 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4192 if (!VT.is512BitVector())
4195 unsigned NumElts = VT.getVectorNumElements();
4196 unsigned HalfSize = NumElts/2;
4197 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4198 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4203 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4204 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4212 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4213 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4214 /// MOVSD, and MOVD, i.e. setting the lowest element.
4215 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4216 if (VT.getVectorElementType().getSizeInBits() < 32)
4218 if (!VT.is128BitVector())
4221 unsigned NumElts = VT.getVectorNumElements();
4223 if (!isUndefOrEqual(Mask[0], NumElts))
4226 for (unsigned i = 1; i != NumElts; ++i)
4227 if (!isUndefOrEqual(Mask[i], i))
4233 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4234 /// as permutations between 128-bit chunks or halves. As an example: this
4236 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4237 /// The first half comes from the second half of V1 and the second half from the
4238 /// the second half of V2.
4239 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4240 if (!HasFp256 || !VT.is256BitVector())
4243 // The shuffle result is divided into half A and half B. In total the two
4244 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4245 // B must come from C, D, E or F.
4246 unsigned HalfSize = VT.getVectorNumElements()/2;
4247 bool MatchA = false, MatchB = false;
4249 // Check if A comes from one of C, D, E, F.
4250 for (unsigned Half = 0; Half != 4; ++Half) {
4251 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4257 // Check if B comes from one of C, D, E, F.
4258 for (unsigned Half = 0; Half != 4; ++Half) {
4259 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4265 return MatchA && MatchB;
4268 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4269 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4270 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4271 MVT VT = SVOp->getSimpleValueType(0);
4273 unsigned HalfSize = VT.getVectorNumElements()/2;
4275 unsigned FstHalf = 0, SndHalf = 0;
4276 for (unsigned i = 0; i < HalfSize; ++i) {
4277 if (SVOp->getMaskElt(i) > 0) {
4278 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4282 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4283 if (SVOp->getMaskElt(i) > 0) {
4284 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4289 return (FstHalf | (SndHalf << 4));
4292 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4293 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4294 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4298 unsigned NumElts = VT.getVectorNumElements();
4300 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4301 for (unsigned i = 0; i != NumElts; ++i) {
4304 Imm8 |= Mask[i] << (i*2);
4309 unsigned LaneSize = 4;
4310 SmallVector<int, 4> MaskVal(LaneSize, -1);
4312 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4313 for (unsigned i = 0; i != LaneSize; ++i) {
4314 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4318 if (MaskVal[i] < 0) {
4319 MaskVal[i] = Mask[i+l] - l;
4320 Imm8 |= MaskVal[i] << (i*2);
4323 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4330 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4331 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4332 /// Note that VPERMIL mask matching is different depending whether theunderlying
4333 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4334 /// to the same elements of the low, but to the higher half of the source.
4335 /// In VPERMILPD the two lanes could be shuffled independently of each other
4336 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4337 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4338 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4339 if (VT.getSizeInBits() < 256 || EltSize < 32)
4341 bool symetricMaskRequired = (EltSize == 32);
4342 unsigned NumElts = VT.getVectorNumElements();
4344 unsigned NumLanes = VT.getSizeInBits()/128;
4345 unsigned LaneSize = NumElts/NumLanes;
4346 // 2 or 4 elements in one lane
4348 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4349 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4350 for (unsigned i = 0; i != LaneSize; ++i) {
4351 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4353 if (symetricMaskRequired) {
4354 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4355 ExpectedMaskVal[i] = Mask[i+l] - l;
4358 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4366 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4367 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4368 /// element of vector 2 and the other elements to come from vector 1 in order.
4369 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4370 bool V2IsSplat = false, bool V2IsUndef = false) {
4371 if (!VT.is128BitVector())
4374 unsigned NumOps = VT.getVectorNumElements();
4375 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4378 if (!isUndefOrEqual(Mask[0], 0))
4381 for (unsigned i = 1; i != NumOps; ++i)
4382 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4383 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4384 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4390 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4391 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4392 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4393 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4394 const X86Subtarget *Subtarget) {
4395 if (!Subtarget->hasSSE3())
4398 unsigned NumElems = VT.getVectorNumElements();
4400 if ((VT.is128BitVector() && NumElems != 4) ||
4401 (VT.is256BitVector() && NumElems != 8) ||
4402 (VT.is512BitVector() && NumElems != 16))
4405 // "i+1" is the value the indexed mask element must have
4406 for (unsigned i = 0; i != NumElems; i += 2)
4407 if (!isUndefOrEqual(Mask[i], i+1) ||
4408 !isUndefOrEqual(Mask[i+1], i+1))
4414 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4415 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4416 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4417 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4418 const X86Subtarget *Subtarget) {
4419 if (!Subtarget->hasSSE3())
4422 unsigned NumElems = VT.getVectorNumElements();
4424 if ((VT.is128BitVector() && NumElems != 4) ||
4425 (VT.is256BitVector() && NumElems != 8) ||
4426 (VT.is512BitVector() && NumElems != 16))
4429 // "i" is the value the indexed mask element must have
4430 for (unsigned i = 0; i != NumElems; i += 2)
4431 if (!isUndefOrEqual(Mask[i], i) ||
4432 !isUndefOrEqual(Mask[i+1], i))
4438 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4439 /// specifies a shuffle of elements that is suitable for input to 256-bit
4440 /// version of MOVDDUP.
4441 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4442 if (!HasFp256 || !VT.is256BitVector())
4445 unsigned NumElts = VT.getVectorNumElements();
4449 for (unsigned i = 0; i != NumElts/2; ++i)
4450 if (!isUndefOrEqual(Mask[i], 0))
4452 for (unsigned i = NumElts/2; i != NumElts; ++i)
4453 if (!isUndefOrEqual(Mask[i], NumElts/2))
4458 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4459 /// specifies a shuffle of elements that is suitable for input to 128-bit
4460 /// version of MOVDDUP.
4461 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4462 if (!VT.is128BitVector())
4465 unsigned e = VT.getVectorNumElements() / 2;
4466 for (unsigned i = 0; i != e; ++i)
4467 if (!isUndefOrEqual(Mask[i], i))
4469 for (unsigned i = 0; i != e; ++i)
4470 if (!isUndefOrEqual(Mask[e+i], i))
4475 /// isVEXTRACTIndex - Return true if the specified
4476 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4477 /// suitable for instruction that extract 128 or 256 bit vectors
4478 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4479 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4480 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4483 // The index should be aligned on a vecWidth-bit boundary.
4485 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4487 MVT VT = N->getSimpleValueType(0);
4488 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4489 bool Result = (Index * ElSize) % vecWidth == 0;
4494 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4495 /// operand specifies a subvector insert that is suitable for input to
4496 /// insertion of 128 or 256-bit subvectors
4497 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4498 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4499 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4501 // The index should be aligned on a vecWidth-bit boundary.
4503 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4505 MVT VT = N->getSimpleValueType(0);
4506 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4507 bool Result = (Index * ElSize) % vecWidth == 0;
4512 bool X86::isVINSERT128Index(SDNode *N) {
4513 return isVINSERTIndex(N, 128);
4516 bool X86::isVINSERT256Index(SDNode *N) {
4517 return isVINSERTIndex(N, 256);
4520 bool X86::isVEXTRACT128Index(SDNode *N) {
4521 return isVEXTRACTIndex(N, 128);
4524 bool X86::isVEXTRACT256Index(SDNode *N) {
4525 return isVEXTRACTIndex(N, 256);
4528 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4529 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4530 /// Handles 128-bit and 256-bit.
4531 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4532 MVT VT = N->getSimpleValueType(0);
4534 assert((VT.getSizeInBits() >= 128) &&
4535 "Unsupported vector type for PSHUF/SHUFP");
4537 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4538 // independently on 128-bit lanes.
4539 unsigned NumElts = VT.getVectorNumElements();
4540 unsigned NumLanes = VT.getSizeInBits()/128;
4541 unsigned NumLaneElts = NumElts/NumLanes;
4543 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4544 "Only supports 2, 4 or 8 elements per lane");
4546 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4548 for (unsigned i = 0; i != NumElts; ++i) {
4549 int Elt = N->getMaskElt(i);
4550 if (Elt < 0) continue;
4551 Elt &= NumLaneElts - 1;
4552 unsigned ShAmt = (i << Shift) % 8;
4553 Mask |= Elt << ShAmt;
4559 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4560 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4561 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4562 MVT VT = N->getSimpleValueType(0);
4564 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4565 "Unsupported vector type for PSHUFHW");
4567 unsigned NumElts = VT.getVectorNumElements();
4570 for (unsigned l = 0; l != NumElts; l += 8) {
4571 // 8 nodes per lane, but we only care about the last 4.
4572 for (unsigned i = 0; i < 4; ++i) {
4573 int Elt = N->getMaskElt(l+i+4);
4574 if (Elt < 0) continue;
4575 Elt &= 0x3; // only 2-bits.
4576 Mask |= Elt << (i * 2);
4583 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4584 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4585 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4586 MVT VT = N->getSimpleValueType(0);
4588 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4589 "Unsupported vector type for PSHUFHW");
4591 unsigned NumElts = VT.getVectorNumElements();
4594 for (unsigned l = 0; l != NumElts; l += 8) {
4595 // 8 nodes per lane, but we only care about the first 4.
4596 for (unsigned i = 0; i < 4; ++i) {
4597 int Elt = N->getMaskElt(l+i);
4598 if (Elt < 0) continue;
4599 Elt &= 0x3; // only 2-bits
4600 Mask |= Elt << (i * 2);
4607 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4608 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4609 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4610 MVT VT = SVOp->getSimpleValueType(0);
4611 unsigned EltSize = VT.is512BitVector() ? 1 :
4612 VT.getVectorElementType().getSizeInBits() >> 3;
4614 unsigned NumElts = VT.getVectorNumElements();
4615 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4616 unsigned NumLaneElts = NumElts/NumLanes;
4620 for (i = 0; i != NumElts; ++i) {
4621 Val = SVOp->getMaskElt(i);
4625 if (Val >= (int)NumElts)
4626 Val -= NumElts - NumLaneElts;
4628 assert(Val - i > 0 && "PALIGNR imm should be positive");
4629 return (Val - i) * EltSize;
4632 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4633 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4634 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4635 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4638 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4640 MVT VecVT = N->getOperand(0).getSimpleValueType();
4641 MVT ElVT = VecVT.getVectorElementType();
4643 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4644 return Index / NumElemsPerChunk;
4647 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4648 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4649 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4650 llvm_unreachable("Illegal insert subvector for VINSERT");
4653 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4655 MVT VecVT = N->getSimpleValueType(0);
4656 MVT ElVT = VecVT.getVectorElementType();
4658 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4659 return Index / NumElemsPerChunk;
4662 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4663 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4664 /// and VINSERTI128 instructions.
4665 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4666 return getExtractVEXTRACTImmediate(N, 128);
4669 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4670 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4671 /// and VINSERTI64x4 instructions.
4672 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4673 return getExtractVEXTRACTImmediate(N, 256);
4676 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4677 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4678 /// and VINSERTI128 instructions.
4679 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4680 return getInsertVINSERTImmediate(N, 128);
4683 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4684 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4685 /// and VINSERTI64x4 instructions.
4686 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4687 return getInsertVINSERTImmediate(N, 256);
4690 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4692 bool X86::isZeroNode(SDValue Elt) {
4693 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4694 return CN->isNullValue();
4695 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4696 return CFP->getValueAPF().isPosZero();
4700 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4701 /// their permute mask.
4702 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4703 SelectionDAG &DAG) {
4704 MVT VT = SVOp->getSimpleValueType(0);
4705 unsigned NumElems = VT.getVectorNumElements();
4706 SmallVector<int, 8> MaskVec;
4708 for (unsigned i = 0; i != NumElems; ++i) {
4709 int Idx = SVOp->getMaskElt(i);
4711 if (Idx < (int)NumElems)
4716 MaskVec.push_back(Idx);
4718 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4719 SVOp->getOperand(0), &MaskVec[0]);
4722 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4723 /// match movhlps. The lower half elements should come from upper half of
4724 /// V1 (and in order), and the upper half elements should come from the upper
4725 /// half of V2 (and in order).
4726 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4727 if (!VT.is128BitVector())
4729 if (VT.getVectorNumElements() != 4)
4731 for (unsigned i = 0, e = 2; i != e; ++i)
4732 if (!isUndefOrEqual(Mask[i], i+2))
4734 for (unsigned i = 2; i != 4; ++i)
4735 if (!isUndefOrEqual(Mask[i], i+4))
4740 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4741 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4743 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4744 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4746 N = N->getOperand(0).getNode();
4747 if (!ISD::isNON_EXTLoad(N))
4750 *LD = cast<LoadSDNode>(N);
4754 // Test whether the given value is a vector value which will be legalized
4756 static bool WillBeConstantPoolLoad(SDNode *N) {
4757 if (N->getOpcode() != ISD::BUILD_VECTOR)
4760 // Check for any non-constant elements.
4761 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4762 switch (N->getOperand(i).getNode()->getOpcode()) {
4764 case ISD::ConstantFP:
4771 // Vectors of all-zeros and all-ones are materialized with special
4772 // instructions rather than being loaded.
4773 return !ISD::isBuildVectorAllZeros(N) &&
4774 !ISD::isBuildVectorAllOnes(N);
4777 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4778 /// match movlp{s|d}. The lower half elements should come from lower half of
4779 /// V1 (and in order), and the upper half elements should come from the upper
4780 /// half of V2 (and in order). And since V1 will become the source of the
4781 /// MOVLP, it must be either a vector load or a scalar load to vector.
4782 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4783 ArrayRef<int> Mask, MVT VT) {
4784 if (!VT.is128BitVector())
4787 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4789 // Is V2 is a vector load, don't do this transformation. We will try to use
4790 // load folding shufps op.
4791 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4794 unsigned NumElems = VT.getVectorNumElements();
4796 if (NumElems != 2 && NumElems != 4)
4798 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4799 if (!isUndefOrEqual(Mask[i], i))
4801 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4802 if (!isUndefOrEqual(Mask[i], i+NumElems))
4807 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4809 static bool isSplatVector(SDNode *N) {
4810 if (N->getOpcode() != ISD::BUILD_VECTOR)
4813 SDValue SplatValue = N->getOperand(0);
4814 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4815 if (N->getOperand(i) != SplatValue)
4820 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4821 /// to an zero vector.
4822 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4823 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4824 SDValue V1 = N->getOperand(0);
4825 SDValue V2 = N->getOperand(1);
4826 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4827 for (unsigned i = 0; i != NumElems; ++i) {
4828 int Idx = N->getMaskElt(i);
4829 if (Idx >= (int)NumElems) {
4830 unsigned Opc = V2.getOpcode();
4831 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4833 if (Opc != ISD::BUILD_VECTOR ||
4834 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4836 } else if (Idx >= 0) {
4837 unsigned Opc = V1.getOpcode();
4838 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4840 if (Opc != ISD::BUILD_VECTOR ||
4841 !X86::isZeroNode(V1.getOperand(Idx)))
4848 /// getZeroVector - Returns a vector of specified type with all zero elements.
4850 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4851 SelectionDAG &DAG, SDLoc dl) {
4852 assert(VT.isVector() && "Expected a vector type");
4854 // Always build SSE zero vectors as <4 x i32> bitcasted
4855 // to their dest type. This ensures they get CSE'd.
4857 if (VT.is128BitVector()) { // SSE
4858 if (Subtarget->hasSSE2()) { // SSE2
4859 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4860 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4862 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4863 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4865 } else if (VT.is256BitVector()) { // AVX
4866 if (Subtarget->hasInt256()) { // AVX2
4867 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4868 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4869 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4871 // 256-bit logic and arithmetic instructions in AVX are all
4872 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4873 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4874 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4875 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4877 } else if (VT.is512BitVector()) { // AVX-512
4878 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4879 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4880 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4881 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4882 } else if (VT.getScalarType() == MVT::i1) {
4883 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4884 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4885 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4886 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4888 llvm_unreachable("Unexpected vector type");
4890 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4893 /// getOnesVector - Returns a vector of specified type with all bits set.
4894 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4895 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4896 /// Then bitcast to their original type, ensuring they get CSE'd.
4897 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4899 assert(VT.isVector() && "Expected a vector type");
4901 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4903 if (VT.is256BitVector()) {
4904 if (HasInt256) { // AVX2
4905 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4906 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4908 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4909 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4911 } else if (VT.is128BitVector()) {
4912 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4914 llvm_unreachable("Unexpected vector type");
4916 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4919 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4920 /// that point to V2 points to its first element.
4921 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4922 for (unsigned i = 0; i != NumElems; ++i) {
4923 if (Mask[i] > (int)NumElems) {
4929 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4930 /// operation of specified width.
4931 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4933 unsigned NumElems = VT.getVectorNumElements();
4934 SmallVector<int, 8> Mask;
4935 Mask.push_back(NumElems);
4936 for (unsigned i = 1; i != NumElems; ++i)
4938 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4941 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4942 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4944 unsigned NumElems = VT.getVectorNumElements();
4945 SmallVector<int, 8> Mask;
4946 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4948 Mask.push_back(i + NumElems);
4950 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4953 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4954 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4956 unsigned NumElems = VT.getVectorNumElements();
4957 SmallVector<int, 8> Mask;
4958 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4959 Mask.push_back(i + Half);
4960 Mask.push_back(i + NumElems + Half);
4962 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4965 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4966 // a generic shuffle instruction because the target has no such instructions.
4967 // Generate shuffles which repeat i16 and i8 several times until they can be
4968 // represented by v4f32 and then be manipulated by target suported shuffles.
4969 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4970 MVT VT = V.getSimpleValueType();
4971 int NumElems = VT.getVectorNumElements();
4974 while (NumElems > 4) {
4975 if (EltNo < NumElems/2) {
4976 V = getUnpackl(DAG, dl, VT, V, V);
4978 V = getUnpackh(DAG, dl, VT, V, V);
4979 EltNo -= NumElems/2;
4986 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4987 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4988 MVT VT = V.getSimpleValueType();
4991 if (VT.is128BitVector()) {
4992 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4993 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4994 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4996 } else if (VT.is256BitVector()) {
4997 // To use VPERMILPS to splat scalars, the second half of indicies must
4998 // refer to the higher part, which is a duplication of the lower one,
4999 // because VPERMILPS can only handle in-lane permutations.
5000 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5001 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5003 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5004 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5007 llvm_unreachable("Vector size not supported");
5009 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5012 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5013 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5014 MVT SrcVT = SV->getSimpleValueType(0);
5015 SDValue V1 = SV->getOperand(0);
5018 int EltNo = SV->getSplatIndex();
5019 int NumElems = SrcVT.getVectorNumElements();
5020 bool Is256BitVec = SrcVT.is256BitVector();
5022 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5023 "Unknown how to promote splat for type");
5025 // Extract the 128-bit part containing the splat element and update
5026 // the splat element index when it refers to the higher register.
5028 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5029 if (EltNo >= NumElems/2)
5030 EltNo -= NumElems/2;
5033 // All i16 and i8 vector types can't be used directly by a generic shuffle
5034 // instruction because the target has no such instruction. Generate shuffles
5035 // which repeat i16 and i8 several times until they fit in i32, and then can
5036 // be manipulated by target suported shuffles.
5037 MVT EltVT = SrcVT.getVectorElementType();
5038 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5039 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5041 // Recreate the 256-bit vector and place the same 128-bit vector
5042 // into the low and high part. This is necessary because we want
5043 // to use VPERM* to shuffle the vectors
5045 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5048 return getLegalSplat(DAG, V1, EltNo);
5051 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5052 /// vector of zero or undef vector. This produces a shuffle where the low
5053 /// element of V2 is swizzled into the zero/undef vector, landing at element
5054 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5055 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5057 const X86Subtarget *Subtarget,
5058 SelectionDAG &DAG) {
5059 MVT VT = V2.getSimpleValueType();
5061 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5062 unsigned NumElems = VT.getVectorNumElements();
5063 SmallVector<int, 16> MaskVec;
5064 for (unsigned i = 0; i != NumElems; ++i)
5065 // If this is the insertion idx, put the low elt of V2 here.
5066 MaskVec.push_back(i == Idx ? NumElems : i);
5067 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5070 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5071 /// target specific opcode. Returns true if the Mask could be calculated.
5072 /// Sets IsUnary to true if only uses one source.
5073 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5074 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5075 unsigned NumElems = VT.getVectorNumElements();
5079 switch(N->getOpcode()) {
5081 ImmN = N->getOperand(N->getNumOperands()-1);
5082 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5084 case X86ISD::UNPCKH:
5085 DecodeUNPCKHMask(VT, Mask);
5087 case X86ISD::UNPCKL:
5088 DecodeUNPCKLMask(VT, Mask);
5090 case X86ISD::MOVHLPS:
5091 DecodeMOVHLPSMask(NumElems, Mask);
5093 case X86ISD::MOVLHPS:
5094 DecodeMOVLHPSMask(NumElems, Mask);
5096 case X86ISD::PALIGNR:
5097 ImmN = N->getOperand(N->getNumOperands()-1);
5098 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5100 case X86ISD::PSHUFD:
5101 case X86ISD::VPERMILP:
5102 ImmN = N->getOperand(N->getNumOperands()-1);
5103 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5106 case X86ISD::PSHUFHW:
5107 ImmN = N->getOperand(N->getNumOperands()-1);
5108 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5111 case X86ISD::PSHUFLW:
5112 ImmN = N->getOperand(N->getNumOperands()-1);
5113 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5116 case X86ISD::VPERMI:
5117 ImmN = N->getOperand(N->getNumOperands()-1);
5118 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5122 case X86ISD::MOVSD: {
5123 // The index 0 always comes from the first element of the second source,
5124 // this is why MOVSS and MOVSD are used in the first place. The other
5125 // elements come from the other positions of the first source vector
5126 Mask.push_back(NumElems);
5127 for (unsigned i = 1; i != NumElems; ++i) {
5132 case X86ISD::VPERM2X128:
5133 ImmN = N->getOperand(N->getNumOperands()-1);
5134 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5135 if (Mask.empty()) return false;
5137 case X86ISD::MOVDDUP:
5138 case X86ISD::MOVLHPD:
5139 case X86ISD::MOVLPD:
5140 case X86ISD::MOVLPS:
5141 case X86ISD::MOVSHDUP:
5142 case X86ISD::MOVSLDUP:
5143 // Not yet implemented
5145 default: llvm_unreachable("unknown target shuffle node");
5151 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5152 /// element of the result of the vector shuffle.
5153 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5156 return SDValue(); // Limit search depth.
5158 SDValue V = SDValue(N, 0);
5159 EVT VT = V.getValueType();
5160 unsigned Opcode = V.getOpcode();
5162 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5163 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5164 int Elt = SV->getMaskElt(Index);
5167 return DAG.getUNDEF(VT.getVectorElementType());
5169 unsigned NumElems = VT.getVectorNumElements();
5170 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5171 : SV->getOperand(1);
5172 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5175 // Recurse into target specific vector shuffles to find scalars.
5176 if (isTargetShuffle(Opcode)) {
5177 MVT ShufVT = V.getSimpleValueType();
5178 unsigned NumElems = ShufVT.getVectorNumElements();
5179 SmallVector<int, 16> ShuffleMask;
5182 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5185 int Elt = ShuffleMask[Index];
5187 return DAG.getUNDEF(ShufVT.getVectorElementType());
5189 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5191 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5195 // Actual nodes that may contain scalar elements
5196 if (Opcode == ISD::BITCAST) {
5197 V = V.getOperand(0);
5198 EVT SrcVT = V.getValueType();
5199 unsigned NumElems = VT.getVectorNumElements();
5201 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5205 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5206 return (Index == 0) ? V.getOperand(0)
5207 : DAG.getUNDEF(VT.getVectorElementType());
5209 if (V.getOpcode() == ISD::BUILD_VECTOR)
5210 return V.getOperand(Index);
5215 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5216 /// shuffle operation which come from a consecutively from a zero. The
5217 /// search can start in two different directions, from left or right.
5218 /// We count undefs as zeros until PreferredNum is reached.
5219 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5220 unsigned NumElems, bool ZerosFromLeft,
5222 unsigned PreferredNum = -1U) {
5223 unsigned NumZeros = 0;
5224 for (unsigned i = 0; i != NumElems; ++i) {
5225 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5226 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5230 if (X86::isZeroNode(Elt))
5232 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5233 NumZeros = std::min(NumZeros + 1, PreferredNum);
5241 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5242 /// correspond consecutively to elements from one of the vector operands,
5243 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5245 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5246 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5247 unsigned NumElems, unsigned &OpNum) {
5248 bool SeenV1 = false;
5249 bool SeenV2 = false;
5251 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5252 int Idx = SVOp->getMaskElt(i);
5253 // Ignore undef indicies
5257 if (Idx < (int)NumElems)
5262 // Only accept consecutive elements from the same vector
5263 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5267 OpNum = SeenV1 ? 0 : 1;
5271 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5272 /// logical left shift of a vector.
5273 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5274 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5276 SVOp->getSimpleValueType(0).getVectorNumElements();
5277 unsigned NumZeros = getNumOfConsecutiveZeros(
5278 SVOp, NumElems, false /* check zeros from right */, DAG,
5279 SVOp->getMaskElt(0));
5285 // Considering the elements in the mask that are not consecutive zeros,
5286 // check if they consecutively come from only one of the source vectors.
5288 // V1 = {X, A, B, C} 0
5290 // vector_shuffle V1, V2 <1, 2, 3, X>
5292 if (!isShuffleMaskConsecutive(SVOp,
5293 0, // Mask Start Index
5294 NumElems-NumZeros, // Mask End Index(exclusive)
5295 NumZeros, // Where to start looking in the src vector
5296 NumElems, // Number of elements in vector
5297 OpSrc)) // Which source operand ?
5302 ShVal = SVOp->getOperand(OpSrc);
5306 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5307 /// logical left shift of a vector.
5308 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5309 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5311 SVOp->getSimpleValueType(0).getVectorNumElements();
5312 unsigned NumZeros = getNumOfConsecutiveZeros(
5313 SVOp, NumElems, true /* check zeros from left */, DAG,
5314 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5320 // Considering the elements in the mask that are not consecutive zeros,
5321 // check if they consecutively come from only one of the source vectors.
5323 // 0 { A, B, X, X } = V2
5325 // vector_shuffle V1, V2 <X, X, 4, 5>
5327 if (!isShuffleMaskConsecutive(SVOp,
5328 NumZeros, // Mask Start Index
5329 NumElems, // Mask End Index(exclusive)
5330 0, // Where to start looking in the src vector
5331 NumElems, // Number of elements in vector
5332 OpSrc)) // Which source operand ?
5337 ShVal = SVOp->getOperand(OpSrc);
5341 /// isVectorShift - Returns true if the shuffle can be implemented as a
5342 /// logical left or right shift of a vector.
5343 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5344 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5345 // Although the logic below support any bitwidth size, there are no
5346 // shift instructions which handle more than 128-bit vectors.
5347 if (!SVOp->getSimpleValueType(0).is128BitVector())
5350 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5351 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5357 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5359 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5360 unsigned NumNonZero, unsigned NumZero,
5362 const X86Subtarget* Subtarget,
5363 const TargetLowering &TLI) {
5370 for (unsigned i = 0; i < 16; ++i) {
5371 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5372 if (ThisIsNonZero && First) {
5374 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5376 V = DAG.getUNDEF(MVT::v8i16);
5381 SDValue ThisElt, LastElt;
5382 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5383 if (LastIsNonZero) {
5384 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5385 MVT::i16, Op.getOperand(i-1));
5387 if (ThisIsNonZero) {
5388 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5389 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5390 ThisElt, DAG.getConstant(8, MVT::i8));
5392 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5396 if (ThisElt.getNode())
5397 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5398 DAG.getIntPtrConstant(i/2));
5402 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5405 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5407 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5408 unsigned NumNonZero, unsigned NumZero,
5410 const X86Subtarget* Subtarget,
5411 const TargetLowering &TLI) {
5418 for (unsigned i = 0; i < 8; ++i) {
5419 bool isNonZero = (NonZeros & (1 << i)) != 0;
5423 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5425 V = DAG.getUNDEF(MVT::v8i16);
5428 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5429 MVT::v8i16, V, Op.getOperand(i),
5430 DAG.getIntPtrConstant(i));
5437 /// getVShift - Return a vector logical shift node.
5439 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5440 unsigned NumBits, SelectionDAG &DAG,
5441 const TargetLowering &TLI, SDLoc dl) {
5442 assert(VT.is128BitVector() && "Unknown type for VShift");
5443 EVT ShVT = MVT::v2i64;
5444 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5445 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5446 return DAG.getNode(ISD::BITCAST, dl, VT,
5447 DAG.getNode(Opc, dl, ShVT, SrcOp,
5448 DAG.getConstant(NumBits,
5449 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5453 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5455 // Check if the scalar load can be widened into a vector load. And if
5456 // the address is "base + cst" see if the cst can be "absorbed" into
5457 // the shuffle mask.
5458 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5459 SDValue Ptr = LD->getBasePtr();
5460 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5462 EVT PVT = LD->getValueType(0);
5463 if (PVT != MVT::i32 && PVT != MVT::f32)
5468 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5469 FI = FINode->getIndex();
5471 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5472 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5473 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5474 Offset = Ptr.getConstantOperandVal(1);
5475 Ptr = Ptr.getOperand(0);
5480 // FIXME: 256-bit vector instructions don't require a strict alignment,
5481 // improve this code to support it better.
5482 unsigned RequiredAlign = VT.getSizeInBits()/8;
5483 SDValue Chain = LD->getChain();
5484 // Make sure the stack object alignment is at least 16 or 32.
5485 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5486 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5487 if (MFI->isFixedObjectIndex(FI)) {
5488 // Can't change the alignment. FIXME: It's possible to compute
5489 // the exact stack offset and reference FI + adjust offset instead.
5490 // If someone *really* cares about this. That's the way to implement it.
5493 MFI->setObjectAlignment(FI, RequiredAlign);
5497 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5498 // Ptr + (Offset & ~15).
5501 if ((Offset % RequiredAlign) & 3)
5503 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5505 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5506 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5508 int EltNo = (Offset - StartOffset) >> 2;
5509 unsigned NumElems = VT.getVectorNumElements();
5511 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5512 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5513 LD->getPointerInfo().getWithOffset(StartOffset),
5514 false, false, false, 0);
5516 SmallVector<int, 8> Mask;
5517 for (unsigned i = 0; i != NumElems; ++i)
5518 Mask.push_back(EltNo);
5520 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5526 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5527 /// vector of type 'VT', see if the elements can be replaced by a single large
5528 /// load which has the same value as a build_vector whose operands are 'elts'.
5530 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5532 /// FIXME: we'd also like to handle the case where the last elements are zero
5533 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5534 /// There's even a handy isZeroNode for that purpose.
5535 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5536 SDLoc &DL, SelectionDAG &DAG,
5537 bool isAfterLegalize) {
5538 EVT EltVT = VT.getVectorElementType();
5539 unsigned NumElems = Elts.size();
5541 LoadSDNode *LDBase = nullptr;
5542 unsigned LastLoadedElt = -1U;
5544 // For each element in the initializer, see if we've found a load or an undef.
5545 // If we don't find an initial load element, or later load elements are
5546 // non-consecutive, bail out.
5547 for (unsigned i = 0; i < NumElems; ++i) {
5548 SDValue Elt = Elts[i];
5550 if (!Elt.getNode() ||
5551 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5554 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5556 LDBase = cast<LoadSDNode>(Elt.getNode());
5560 if (Elt.getOpcode() == ISD::UNDEF)
5563 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5564 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5569 // If we have found an entire vector of loads and undefs, then return a large
5570 // load of the entire vector width starting at the base pointer. If we found
5571 // consecutive loads for the low half, generate a vzext_load node.
5572 if (LastLoadedElt == NumElems - 1) {
5574 if (isAfterLegalize &&
5575 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5578 SDValue NewLd = SDValue();
5580 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5581 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5582 LDBase->getPointerInfo(),
5583 LDBase->isVolatile(), LDBase->isNonTemporal(),
5584 LDBase->isInvariant(), 0);
5585 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5586 LDBase->getPointerInfo(),
5587 LDBase->isVolatile(), LDBase->isNonTemporal(),
5588 LDBase->isInvariant(), LDBase->getAlignment());
5590 if (LDBase->hasAnyUseOfValue(1)) {
5591 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5593 SDValue(NewLd.getNode(), 1));
5594 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5595 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5596 SDValue(NewLd.getNode(), 1));
5601 if (NumElems == 4 && LastLoadedElt == 1 &&
5602 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5603 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5604 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5606 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5607 LDBase->getPointerInfo(),
5608 LDBase->getAlignment(),
5609 false/*isVolatile*/, true/*ReadMem*/,
5612 // Make sure the newly-created LOAD is in the same position as LDBase in
5613 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5614 // update uses of LDBase's output chain to use the TokenFactor.
5615 if (LDBase->hasAnyUseOfValue(1)) {
5616 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5617 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5618 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5619 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5620 SDValue(ResNode.getNode(), 1));
5623 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5628 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5629 /// to generate a splat value for the following cases:
5630 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5631 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5632 /// a scalar load, or a constant.
5633 /// The VBROADCAST node is returned when a pattern is found,
5634 /// or SDValue() otherwise.
5635 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5636 SelectionDAG &DAG) {
5637 if (!Subtarget->hasFp256())
5640 MVT VT = Op.getSimpleValueType();
5643 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5644 "Unsupported vector type for broadcast.");
5649 switch (Op.getOpcode()) {
5651 // Unknown pattern found.
5654 case ISD::BUILD_VECTOR: {
5655 // The BUILD_VECTOR node must be a splat.
5656 if (!isSplatVector(Op.getNode()))
5659 Ld = Op.getOperand(0);
5660 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5661 Ld.getOpcode() == ISD::ConstantFP);
5663 // The suspected load node has several users. Make sure that all
5664 // of its users are from the BUILD_VECTOR node.
5665 // Constants may have multiple users.
5666 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5671 case ISD::VECTOR_SHUFFLE: {
5672 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5674 // Shuffles must have a splat mask where the first element is
5676 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5679 SDValue Sc = Op.getOperand(0);
5680 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5681 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5683 if (!Subtarget->hasInt256())
5686 // Use the register form of the broadcast instruction available on AVX2.
5687 if (VT.getSizeInBits() >= 256)
5688 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5689 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5692 Ld = Sc.getOperand(0);
5693 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5694 Ld.getOpcode() == ISD::ConstantFP);
5696 // The scalar_to_vector node and the suspected
5697 // load node must have exactly one user.
5698 // Constants may have multiple users.
5700 // AVX-512 has register version of the broadcast
5701 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5702 Ld.getValueType().getSizeInBits() >= 32;
5703 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5710 bool IsGE256 = (VT.getSizeInBits() >= 256);
5712 // Handle the broadcasting a single constant scalar from the constant pool
5713 // into a vector. On Sandybridge it is still better to load a constant vector
5714 // from the constant pool and not to broadcast it from a scalar.
5715 if (ConstSplatVal && Subtarget->hasInt256()) {
5716 EVT CVT = Ld.getValueType();
5717 assert(!CVT.isVector() && "Must not broadcast a vector type");
5718 unsigned ScalarSize = CVT.getSizeInBits();
5720 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5721 const Constant *C = nullptr;
5722 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5723 C = CI->getConstantIntValue();
5724 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5725 C = CF->getConstantFPValue();
5727 assert(C && "Invalid constant type");
5729 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5730 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5731 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5732 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5733 MachinePointerInfo::getConstantPool(),
5734 false, false, false, Alignment);
5736 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5740 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5741 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5743 // Handle AVX2 in-register broadcasts.
5744 if (!IsLoad && Subtarget->hasInt256() &&
5745 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5746 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5748 // The scalar source must be a normal load.
5752 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5753 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5755 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5756 // double since there is no vbroadcastsd xmm
5757 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5758 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5759 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5762 // Unsupported broadcast.
5766 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5767 /// underlying vector and index.
5769 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5771 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5773 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5774 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5777 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5779 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5781 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5782 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5785 // In this case the vector is the extract_subvector expression and the index
5786 // is 2, as specified by the shuffle.
5787 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5788 SDValue ShuffleVec = SVOp->getOperand(0);
5789 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5790 assert(ShuffleVecVT.getVectorElementType() ==
5791 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5793 int ShuffleIdx = SVOp->getMaskElt(Idx);
5794 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5795 ExtractedFromVec = ShuffleVec;
5801 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5802 MVT VT = Op.getSimpleValueType();
5804 // Skip if insert_vec_elt is not supported.
5805 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5806 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5810 unsigned NumElems = Op.getNumOperands();
5814 SmallVector<unsigned, 4> InsertIndices;
5815 SmallVector<int, 8> Mask(NumElems, -1);
5817 for (unsigned i = 0; i != NumElems; ++i) {
5818 unsigned Opc = Op.getOperand(i).getOpcode();
5820 if (Opc == ISD::UNDEF)
5823 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5824 // Quit if more than 1 elements need inserting.
5825 if (InsertIndices.size() > 1)
5828 InsertIndices.push_back(i);
5832 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5833 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5834 // Quit if non-constant index.
5835 if (!isa<ConstantSDNode>(ExtIdx))
5837 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5839 // Quit if extracted from vector of different type.
5840 if (ExtractedFromVec.getValueType() != VT)
5843 if (!VecIn1.getNode())
5844 VecIn1 = ExtractedFromVec;
5845 else if (VecIn1 != ExtractedFromVec) {
5846 if (!VecIn2.getNode())
5847 VecIn2 = ExtractedFromVec;
5848 else if (VecIn2 != ExtractedFromVec)
5849 // Quit if more than 2 vectors to shuffle
5853 if (ExtractedFromVec == VecIn1)
5855 else if (ExtractedFromVec == VecIn2)
5856 Mask[i] = Idx + NumElems;
5859 if (!VecIn1.getNode())
5862 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5863 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5864 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5865 unsigned Idx = InsertIndices[i];
5866 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5867 DAG.getIntPtrConstant(Idx));
5873 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5875 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5877 MVT VT = Op.getSimpleValueType();
5878 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5879 "Unexpected type in LowerBUILD_VECTORvXi1!");
5882 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5883 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5884 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5885 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5888 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5889 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5890 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5891 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5894 bool AllContants = true;
5895 uint64_t Immediate = 0;
5896 int NonConstIdx = -1;
5897 bool IsSplat = true;
5898 unsigned NumNonConsts = 0;
5899 unsigned NumConsts = 0;
5900 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5901 SDValue In = Op.getOperand(idx);
5902 if (In.getOpcode() == ISD::UNDEF)
5904 if (!isa<ConstantSDNode>(In)) {
5905 AllContants = false;
5911 if (cast<ConstantSDNode>(In)->getZExtValue())
5912 Immediate |= (1ULL << idx);
5914 if (In != Op.getOperand(0))
5919 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5920 DAG.getConstant(Immediate, MVT::i16));
5921 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5922 DAG.getIntPtrConstant(0));
5925 if (NumNonConsts == 1 && NonConstIdx != 0) {
5928 SDValue VecAsImm = DAG.getConstant(Immediate,
5929 MVT::getIntegerVT(VT.getSizeInBits()));
5930 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5933 DstVec = DAG.getUNDEF(VT);
5934 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5935 Op.getOperand(NonConstIdx),
5936 DAG.getIntPtrConstant(NonConstIdx));
5938 if (!IsSplat && (NonConstIdx != 0))
5939 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5940 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5943 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5944 DAG.getConstant(-1, SelectVT),
5945 DAG.getConstant(0, SelectVT));
5947 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5948 DAG.getConstant((Immediate | 1), SelectVT),
5949 DAG.getConstant(Immediate, SelectVT));
5950 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5954 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5957 MVT VT = Op.getSimpleValueType();
5958 MVT ExtVT = VT.getVectorElementType();
5959 unsigned NumElems = Op.getNumOperands();
5961 // Generate vectors for predicate vectors.
5962 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5963 return LowerBUILD_VECTORvXi1(Op, DAG);
5965 // Vectors containing all zeros can be matched by pxor and xorps later
5966 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5967 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5968 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5969 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5972 return getZeroVector(VT, Subtarget, DAG, dl);
5975 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5976 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5977 // vpcmpeqd on 256-bit vectors.
5978 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5979 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5982 if (!VT.is512BitVector())
5983 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5986 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5987 if (Broadcast.getNode())
5990 unsigned EVTBits = ExtVT.getSizeInBits();
5992 unsigned NumZero = 0;
5993 unsigned NumNonZero = 0;
5994 unsigned NonZeros = 0;
5995 bool IsAllConstants = true;
5996 SmallSet<SDValue, 8> Values;
5997 for (unsigned i = 0; i < NumElems; ++i) {
5998 SDValue Elt = Op.getOperand(i);
5999 if (Elt.getOpcode() == ISD::UNDEF)
6002 if (Elt.getOpcode() != ISD::Constant &&
6003 Elt.getOpcode() != ISD::ConstantFP)
6004 IsAllConstants = false;
6005 if (X86::isZeroNode(Elt))
6008 NonZeros |= (1 << i);
6013 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6014 if (NumNonZero == 0)
6015 return DAG.getUNDEF(VT);
6017 // Special case for single non-zero, non-undef, element.
6018 if (NumNonZero == 1) {
6019 unsigned Idx = countTrailingZeros(NonZeros);
6020 SDValue Item = Op.getOperand(Idx);
6022 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6023 // the value are obviously zero, truncate the value to i32 and do the
6024 // insertion that way. Only do this if the value is non-constant or if the
6025 // value is a constant being inserted into element 0. It is cheaper to do
6026 // a constant pool load than it is to do a movd + shuffle.
6027 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6028 (!IsAllConstants || Idx == 0)) {
6029 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6031 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6032 EVT VecVT = MVT::v4i32;
6033 unsigned VecElts = 4;
6035 // Truncate the value (which may itself be a constant) to i32, and
6036 // convert it to a vector with movd (S2V+shuffle to zero extend).
6037 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6038 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6039 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6041 // Now we have our 32-bit value zero extended in the low element of
6042 // a vector. If Idx != 0, swizzle it into place.
6044 SmallVector<int, 4> Mask;
6045 Mask.push_back(Idx);
6046 for (unsigned i = 1; i != VecElts; ++i)
6048 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6051 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6055 // If we have a constant or non-constant insertion into the low element of
6056 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6057 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6058 // depending on what the source datatype is.
6061 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6063 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6064 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6065 if (VT.is256BitVector() || VT.is512BitVector()) {
6066 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6067 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6068 Item, DAG.getIntPtrConstant(0));
6070 assert(VT.is128BitVector() && "Expected an SSE value type!");
6071 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6072 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6073 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6076 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6077 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6078 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6079 if (VT.is256BitVector()) {
6080 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6081 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6083 assert(VT.is128BitVector() && "Expected an SSE value type!");
6084 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6086 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6090 // Is it a vector logical left shift?
6091 if (NumElems == 2 && Idx == 1 &&
6092 X86::isZeroNode(Op.getOperand(0)) &&
6093 !X86::isZeroNode(Op.getOperand(1))) {
6094 unsigned NumBits = VT.getSizeInBits();
6095 return getVShift(true, VT,
6096 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6097 VT, Op.getOperand(1)),
6098 NumBits/2, DAG, *this, dl);
6101 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6104 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6105 // is a non-constant being inserted into an element other than the low one,
6106 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6107 // movd/movss) to move this into the low element, then shuffle it into
6109 if (EVTBits == 32) {
6110 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6112 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6113 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6114 SmallVector<int, 8> MaskVec;
6115 for (unsigned i = 0; i != NumElems; ++i)
6116 MaskVec.push_back(i == Idx ? 0 : 1);
6117 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6121 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6122 if (Values.size() == 1) {
6123 if (EVTBits == 32) {
6124 // Instead of a shuffle like this:
6125 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6126 // Check if it's possible to issue this instead.
6127 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6128 unsigned Idx = countTrailingZeros(NonZeros);
6129 SDValue Item = Op.getOperand(Idx);
6130 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6131 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6136 // A vector full of immediates; various special cases are already
6137 // handled, so this is best done with a single constant-pool load.
6141 // For AVX-length vectors, build the individual 128-bit pieces and use
6142 // shuffles to put them in place.
6143 if (VT.is256BitVector() || VT.is512BitVector()) {
6144 SmallVector<SDValue, 64> V;
6145 for (unsigned i = 0; i != NumElems; ++i)
6146 V.push_back(Op.getOperand(i));
6148 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6150 // Build both the lower and upper subvector.
6151 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6152 makeArrayRef(&V[0], NumElems/2));
6153 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6154 makeArrayRef(&V[NumElems / 2], NumElems/2));
6156 // Recreate the wider vector with the lower and upper part.
6157 if (VT.is256BitVector())
6158 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6159 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6162 // Let legalizer expand 2-wide build_vectors.
6163 if (EVTBits == 64) {
6164 if (NumNonZero == 1) {
6165 // One half is zero or undef.
6166 unsigned Idx = countTrailingZeros(NonZeros);
6167 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6168 Op.getOperand(Idx));
6169 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6174 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6175 if (EVTBits == 8 && NumElems == 16) {
6176 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6178 if (V.getNode()) return V;
6181 if (EVTBits == 16 && NumElems == 8) {
6182 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6184 if (V.getNode()) return V;
6187 // If element VT is == 32 bits, turn it into a number of shuffles.
6188 SmallVector<SDValue, 8> V(NumElems);
6189 if (NumElems == 4 && NumZero > 0) {
6190 for (unsigned i = 0; i < 4; ++i) {
6191 bool isZero = !(NonZeros & (1 << i));
6193 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6195 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6198 for (unsigned i = 0; i < 2; ++i) {
6199 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6202 V[i] = V[i*2]; // Must be a zero vector.
6205 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6208 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6211 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6216 bool Reverse1 = (NonZeros & 0x3) == 2;
6217 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6221 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6222 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6224 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6227 if (Values.size() > 1 && VT.is128BitVector()) {
6228 // Check for a build vector of consecutive loads.
6229 for (unsigned i = 0; i < NumElems; ++i)
6230 V[i] = Op.getOperand(i);
6232 // Check for elements which are consecutive loads.
6233 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6237 // Check for a build vector from mostly shuffle plus few inserting.
6238 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6242 // For SSE 4.1, use insertps to put the high elements into the low element.
6243 if (getSubtarget()->hasSSE41()) {
6245 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6246 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6248 Result = DAG.getUNDEF(VT);
6250 for (unsigned i = 1; i < NumElems; ++i) {
6251 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6252 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6253 Op.getOperand(i), DAG.getIntPtrConstant(i));
6258 // Otherwise, expand into a number of unpckl*, start by extending each of
6259 // our (non-undef) elements to the full vector width with the element in the
6260 // bottom slot of the vector (which generates no code for SSE).
6261 for (unsigned i = 0; i < NumElems; ++i) {
6262 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6263 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6265 V[i] = DAG.getUNDEF(VT);
6268 // Next, we iteratively mix elements, e.g. for v4f32:
6269 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6270 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6271 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6272 unsigned EltStride = NumElems >> 1;
6273 while (EltStride != 0) {
6274 for (unsigned i = 0; i < EltStride; ++i) {
6275 // If V[i+EltStride] is undef and this is the first round of mixing,
6276 // then it is safe to just drop this shuffle: V[i] is already in the
6277 // right place, the one element (since it's the first round) being
6278 // inserted as undef can be dropped. This isn't safe for successive
6279 // rounds because they will permute elements within both vectors.
6280 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6281 EltStride == NumElems/2)
6284 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6293 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6294 // to create 256-bit vectors from two other 128-bit ones.
6295 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6297 MVT ResVT = Op.getSimpleValueType();
6299 assert((ResVT.is256BitVector() ||
6300 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6302 SDValue V1 = Op.getOperand(0);
6303 SDValue V2 = Op.getOperand(1);
6304 unsigned NumElems = ResVT.getVectorNumElements();
6305 if(ResVT.is256BitVector())
6306 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6308 if (Op.getNumOperands() == 4) {
6309 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6310 ResVT.getVectorNumElements()/2);
6311 SDValue V3 = Op.getOperand(2);
6312 SDValue V4 = Op.getOperand(3);
6313 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6314 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6316 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6319 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6320 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6321 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6322 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6323 Op.getNumOperands() == 4)));
6325 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6326 // from two other 128-bit ones.
6328 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6329 return LowerAVXCONCAT_VECTORS(Op, DAG);
6332 // Try to lower a shuffle node into a simple blend instruction.
6334 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6335 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6336 SDValue V1 = SVOp->getOperand(0);
6337 SDValue V2 = SVOp->getOperand(1);
6339 MVT VT = SVOp->getSimpleValueType(0);
6340 MVT EltVT = VT.getVectorElementType();
6341 unsigned NumElems = VT.getVectorNumElements();
6343 // There is no blend with immediate in AVX-512.
6344 if (VT.is512BitVector())
6347 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6349 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6352 // Check the mask for BLEND and build the value.
6353 unsigned MaskValue = 0;
6354 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6355 unsigned NumLanes = (NumElems-1)/8 + 1;
6356 unsigned NumElemsInLane = NumElems / NumLanes;
6358 // Blend for v16i16 should be symetric for the both lanes.
6359 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6361 int SndLaneEltIdx = (NumLanes == 2) ?
6362 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6363 int EltIdx = SVOp->getMaskElt(i);
6365 if ((EltIdx < 0 || EltIdx == (int)i) &&
6366 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6369 if (((unsigned)EltIdx == (i + NumElems)) &&
6370 (SndLaneEltIdx < 0 ||
6371 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6372 MaskValue |= (1<<i);
6377 // Convert i32 vectors to floating point if it is not AVX2.
6378 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6380 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6381 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6383 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6384 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6387 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6388 DAG.getConstant(MaskValue, MVT::i32));
6389 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6392 /// In vector type \p VT, return true if the element at index \p InputIdx
6393 /// falls on a different 128-bit lane than \p OutputIdx.
6394 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6395 unsigned OutputIdx) {
6396 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6397 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6400 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6401 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6402 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6403 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6405 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6406 SelectionDAG &DAG) {
6407 MVT VT = V1.getSimpleValueType();
6408 assert(VT.is128BitVector() || VT.is256BitVector());
6410 MVT EltVT = VT.getVectorElementType();
6411 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6412 unsigned NumElts = VT.getVectorNumElements();
6414 SmallVector<SDValue, 32> PshufbMask;
6415 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6416 int InputIdx = MaskVals[OutputIdx];
6417 unsigned InputByteIdx;
6419 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6420 InputByteIdx = 0x80;
6422 // Cross lane is not allowed.
6423 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6425 InputByteIdx = InputIdx * EltSizeInBytes;
6426 // Index is an byte offset within the 128-bit lane.
6427 InputByteIdx &= 0xf;
6430 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6431 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6432 if (InputByteIdx != 0x80)
6437 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6439 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6440 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6441 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6444 // v8i16 shuffles - Prefer shuffles in the following order:
6445 // 1. [all] pshuflw, pshufhw, optional move
6446 // 2. [ssse3] 1 x pshufb
6447 // 3. [ssse3] 2 x pshufb + 1 x por
6448 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6450 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6451 SelectionDAG &DAG) {
6452 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6453 SDValue V1 = SVOp->getOperand(0);
6454 SDValue V2 = SVOp->getOperand(1);
6456 SmallVector<int, 8> MaskVals;
6458 // Determine if more than 1 of the words in each of the low and high quadwords
6459 // of the result come from the same quadword of one of the two inputs. Undef
6460 // mask values count as coming from any quadword, for better codegen.
6462 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6463 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6464 unsigned LoQuad[] = { 0, 0, 0, 0 };
6465 unsigned HiQuad[] = { 0, 0, 0, 0 };
6466 // Indices of quads used.
6467 std::bitset<4> InputQuads;
6468 for (unsigned i = 0; i < 8; ++i) {
6469 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6470 int EltIdx = SVOp->getMaskElt(i);
6471 MaskVals.push_back(EltIdx);
6480 InputQuads.set(EltIdx / 4);
6483 int BestLoQuad = -1;
6484 unsigned MaxQuad = 1;
6485 for (unsigned i = 0; i < 4; ++i) {
6486 if (LoQuad[i] > MaxQuad) {
6488 MaxQuad = LoQuad[i];
6492 int BestHiQuad = -1;
6494 for (unsigned i = 0; i < 4; ++i) {
6495 if (HiQuad[i] > MaxQuad) {
6497 MaxQuad = HiQuad[i];
6501 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6502 // of the two input vectors, shuffle them into one input vector so only a
6503 // single pshufb instruction is necessary. If there are more than 2 input
6504 // quads, disable the next transformation since it does not help SSSE3.
6505 bool V1Used = InputQuads[0] || InputQuads[1];
6506 bool V2Used = InputQuads[2] || InputQuads[3];
6507 if (Subtarget->hasSSSE3()) {
6508 if (InputQuads.count() == 2 && V1Used && V2Used) {
6509 BestLoQuad = InputQuads[0] ? 0 : 1;
6510 BestHiQuad = InputQuads[2] ? 2 : 3;
6512 if (InputQuads.count() > 2) {
6518 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6519 // the shuffle mask. If a quad is scored as -1, that means that it contains
6520 // words from all 4 input quadwords.
6522 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6524 BestLoQuad < 0 ? 0 : BestLoQuad,
6525 BestHiQuad < 0 ? 1 : BestHiQuad
6527 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6528 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6529 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6530 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6532 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6533 // source words for the shuffle, to aid later transformations.
6534 bool AllWordsInNewV = true;
6535 bool InOrder[2] = { true, true };
6536 for (unsigned i = 0; i != 8; ++i) {
6537 int idx = MaskVals[i];
6539 InOrder[i/4] = false;
6540 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6542 AllWordsInNewV = false;
6546 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6547 if (AllWordsInNewV) {
6548 for (int i = 0; i != 8; ++i) {
6549 int idx = MaskVals[i];
6552 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6553 if ((idx != i) && idx < 4)
6555 if ((idx != i) && idx > 3)
6564 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6565 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6566 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6567 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6568 unsigned TargetMask = 0;
6569 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6570 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6571 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6572 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6573 getShufflePSHUFLWImmediate(SVOp);
6574 V1 = NewV.getOperand(0);
6575 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6579 // Promote splats to a larger type which usually leads to more efficient code.
6580 // FIXME: Is this true if pshufb is available?
6581 if (SVOp->isSplat())
6582 return PromoteSplat(SVOp, DAG);
6584 // If we have SSSE3, and all words of the result are from 1 input vector,
6585 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6586 // is present, fall back to case 4.
6587 if (Subtarget->hasSSSE3()) {
6588 SmallVector<SDValue,16> pshufbMask;
6590 // If we have elements from both input vectors, set the high bit of the
6591 // shuffle mask element to zero out elements that come from V2 in the V1
6592 // mask, and elements that come from V1 in the V2 mask, so that the two
6593 // results can be OR'd together.
6594 bool TwoInputs = V1Used && V2Used;
6595 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6597 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6599 // Calculate the shuffle mask for the second input, shuffle it, and
6600 // OR it with the first shuffled input.
6601 CommuteVectorShuffleMask(MaskVals, 8);
6602 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6603 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6604 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6607 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6608 // and update MaskVals with new element order.
6609 std::bitset<8> InOrder;
6610 if (BestLoQuad >= 0) {
6611 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6612 for (int i = 0; i != 4; ++i) {
6613 int idx = MaskVals[i];
6616 } else if ((idx / 4) == BestLoQuad) {
6621 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6624 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6625 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6626 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6628 getShufflePSHUFLWImmediate(SVOp), DAG);
6632 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6633 // and update MaskVals with the new element order.
6634 if (BestHiQuad >= 0) {
6635 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6636 for (unsigned i = 4; i != 8; ++i) {
6637 int idx = MaskVals[i];
6640 } else if ((idx / 4) == BestHiQuad) {
6641 MaskV[i] = (idx & 3) + 4;
6645 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6648 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6649 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6650 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6652 getShufflePSHUFHWImmediate(SVOp), DAG);
6656 // In case BestHi & BestLo were both -1, which means each quadword has a word
6657 // from each of the four input quadwords, calculate the InOrder bitvector now
6658 // before falling through to the insert/extract cleanup.
6659 if (BestLoQuad == -1 && BestHiQuad == -1) {
6661 for (int i = 0; i != 8; ++i)
6662 if (MaskVals[i] < 0 || MaskVals[i] == i)
6666 // The other elements are put in the right place using pextrw and pinsrw.
6667 for (unsigned i = 0; i != 8; ++i) {
6670 int EltIdx = MaskVals[i];
6673 SDValue ExtOp = (EltIdx < 8) ?
6674 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6675 DAG.getIntPtrConstant(EltIdx)) :
6676 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6677 DAG.getIntPtrConstant(EltIdx - 8));
6678 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6679 DAG.getIntPtrConstant(i));
6684 /// \brief v16i16 shuffles
6686 /// FIXME: We only support generation of a single pshufb currently. We can
6687 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6688 /// well (e.g 2 x pshufb + 1 x por).
6690 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6691 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6692 SDValue V1 = SVOp->getOperand(0);
6693 SDValue V2 = SVOp->getOperand(1);
6696 if (V2.getOpcode() != ISD::UNDEF)
6699 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6700 return getPSHUFB(MaskVals, V1, dl, DAG);
6703 // v16i8 shuffles - Prefer shuffles in the following order:
6704 // 1. [ssse3] 1 x pshufb
6705 // 2. [ssse3] 2 x pshufb + 1 x por
6706 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6707 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6708 const X86Subtarget* Subtarget,
6709 SelectionDAG &DAG) {
6710 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6711 SDValue V1 = SVOp->getOperand(0);
6712 SDValue V2 = SVOp->getOperand(1);
6714 ArrayRef<int> MaskVals = SVOp->getMask();
6716 // Promote splats to a larger type which usually leads to more efficient code.
6717 // FIXME: Is this true if pshufb is available?
6718 if (SVOp->isSplat())
6719 return PromoteSplat(SVOp, DAG);
6721 // If we have SSSE3, case 1 is generated when all result bytes come from
6722 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6723 // present, fall back to case 3.
6725 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6726 if (Subtarget->hasSSSE3()) {
6727 SmallVector<SDValue,16> pshufbMask;
6729 // If all result elements are from one input vector, then only translate
6730 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6732 // Otherwise, we have elements from both input vectors, and must zero out
6733 // elements that come from V2 in the first mask, and V1 in the second mask
6734 // so that we can OR them together.
6735 for (unsigned i = 0; i != 16; ++i) {
6736 int EltIdx = MaskVals[i];
6737 if (EltIdx < 0 || EltIdx >= 16)
6739 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6741 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6742 DAG.getNode(ISD::BUILD_VECTOR, dl,
6743 MVT::v16i8, pshufbMask));
6745 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6746 // the 2nd operand if it's undefined or zero.
6747 if (V2.getOpcode() == ISD::UNDEF ||
6748 ISD::isBuildVectorAllZeros(V2.getNode()))
6751 // Calculate the shuffle mask for the second input, shuffle it, and
6752 // OR it with the first shuffled input.
6754 for (unsigned i = 0; i != 16; ++i) {
6755 int EltIdx = MaskVals[i];
6756 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6757 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6759 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6760 DAG.getNode(ISD::BUILD_VECTOR, dl,
6761 MVT::v16i8, pshufbMask));
6762 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6765 // No SSSE3 - Calculate in place words and then fix all out of place words
6766 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6767 // the 16 different words that comprise the two doublequadword input vectors.
6768 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6769 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6771 for (int i = 0; i != 8; ++i) {
6772 int Elt0 = MaskVals[i*2];
6773 int Elt1 = MaskVals[i*2+1];
6775 // This word of the result is all undef, skip it.
6776 if (Elt0 < 0 && Elt1 < 0)
6779 // This word of the result is already in the correct place, skip it.
6780 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6783 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6784 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6787 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6788 // using a single extract together, load it and store it.
6789 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6790 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6791 DAG.getIntPtrConstant(Elt1 / 2));
6792 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6793 DAG.getIntPtrConstant(i));
6797 // If Elt1 is defined, extract it from the appropriate source. If the
6798 // source byte is not also odd, shift the extracted word left 8 bits
6799 // otherwise clear the bottom 8 bits if we need to do an or.
6801 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6802 DAG.getIntPtrConstant(Elt1 / 2));
6803 if ((Elt1 & 1) == 0)
6804 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6806 TLI.getShiftAmountTy(InsElt.getValueType())));
6808 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6809 DAG.getConstant(0xFF00, MVT::i16));
6811 // If Elt0 is defined, extract it from the appropriate source. If the
6812 // source byte is not also even, shift the extracted word right 8 bits. If
6813 // Elt1 was also defined, OR the extracted values together before
6814 // inserting them in the result.
6816 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6817 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6818 if ((Elt0 & 1) != 0)
6819 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6821 TLI.getShiftAmountTy(InsElt0.getValueType())));
6823 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6824 DAG.getConstant(0x00FF, MVT::i16));
6825 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6828 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6829 DAG.getIntPtrConstant(i));
6831 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6834 // v32i8 shuffles - Translate to VPSHUFB if possible.
6836 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6837 const X86Subtarget *Subtarget,
6838 SelectionDAG &DAG) {
6839 MVT VT = SVOp->getSimpleValueType(0);
6840 SDValue V1 = SVOp->getOperand(0);
6841 SDValue V2 = SVOp->getOperand(1);
6843 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6845 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6846 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6847 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6849 // VPSHUFB may be generated if
6850 // (1) one of input vector is undefined or zeroinitializer.
6851 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6852 // And (2) the mask indexes don't cross the 128-bit lane.
6853 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6854 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6857 if (V1IsAllZero && !V2IsAllZero) {
6858 CommuteVectorShuffleMask(MaskVals, 32);
6861 return getPSHUFB(MaskVals, V1, dl, DAG);
6864 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6865 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6866 /// done when every pair / quad of shuffle mask elements point to elements in
6867 /// the right sequence. e.g.
6868 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6870 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6871 SelectionDAG &DAG) {
6872 MVT VT = SVOp->getSimpleValueType(0);
6874 unsigned NumElems = VT.getVectorNumElements();
6877 switch (VT.SimpleTy) {
6878 default: llvm_unreachable("Unexpected!");
6879 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6880 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6881 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6882 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6883 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6884 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6887 SmallVector<int, 8> MaskVec;
6888 for (unsigned i = 0; i != NumElems; i += Scale) {
6890 for (unsigned j = 0; j != Scale; ++j) {
6891 int EltIdx = SVOp->getMaskElt(i+j);
6895 StartIdx = (EltIdx / Scale);
6896 if (EltIdx != (int)(StartIdx*Scale + j))
6899 MaskVec.push_back(StartIdx);
6902 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6903 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6904 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6907 /// getVZextMovL - Return a zero-extending vector move low node.
6909 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6910 SDValue SrcOp, SelectionDAG &DAG,
6911 const X86Subtarget *Subtarget, SDLoc dl) {
6912 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6913 LoadSDNode *LD = nullptr;
6914 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6915 LD = dyn_cast<LoadSDNode>(SrcOp);
6917 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6919 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6920 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6921 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6922 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6923 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6925 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6926 return DAG.getNode(ISD::BITCAST, dl, VT,
6927 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6928 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6936 return DAG.getNode(ISD::BITCAST, dl, VT,
6937 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6938 DAG.getNode(ISD::BITCAST, dl,
6942 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6943 /// which could not be matched by any known target speficic shuffle
6945 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6947 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6948 if (NewOp.getNode())
6951 MVT VT = SVOp->getSimpleValueType(0);
6953 unsigned NumElems = VT.getVectorNumElements();
6954 unsigned NumLaneElems = NumElems / 2;
6957 MVT EltVT = VT.getVectorElementType();
6958 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6961 SmallVector<int, 16> Mask;
6962 for (unsigned l = 0; l < 2; ++l) {
6963 // Build a shuffle mask for the output, discovering on the fly which
6964 // input vectors to use as shuffle operands (recorded in InputUsed).
6965 // If building a suitable shuffle vector proves too hard, then bail
6966 // out with UseBuildVector set.
6967 bool UseBuildVector = false;
6968 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6969 unsigned LaneStart = l * NumLaneElems;
6970 for (unsigned i = 0; i != NumLaneElems; ++i) {
6971 // The mask element. This indexes into the input.
6972 int Idx = SVOp->getMaskElt(i+LaneStart);
6974 // the mask element does not index into any input vector.
6979 // The input vector this mask element indexes into.
6980 int Input = Idx / NumLaneElems;
6982 // Turn the index into an offset from the start of the input vector.
6983 Idx -= Input * NumLaneElems;
6985 // Find or create a shuffle vector operand to hold this input.
6987 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6988 if (InputUsed[OpNo] == Input)
6989 // This input vector is already an operand.
6991 if (InputUsed[OpNo] < 0) {
6992 // Create a new operand for this input vector.
6993 InputUsed[OpNo] = Input;
6998 if (OpNo >= array_lengthof(InputUsed)) {
6999 // More than two input vectors used! Give up on trying to create a
7000 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7001 UseBuildVector = true;
7005 // Add the mask index for the new shuffle vector.
7006 Mask.push_back(Idx + OpNo * NumLaneElems);
7009 if (UseBuildVector) {
7010 SmallVector<SDValue, 16> SVOps;
7011 for (unsigned i = 0; i != NumLaneElems; ++i) {
7012 // The mask element. This indexes into the input.
7013 int Idx = SVOp->getMaskElt(i+LaneStart);
7015 SVOps.push_back(DAG.getUNDEF(EltVT));
7019 // The input vector this mask element indexes into.
7020 int Input = Idx / NumElems;
7022 // Turn the index into an offset from the start of the input vector.
7023 Idx -= Input * NumElems;
7025 // Extract the vector element by hand.
7026 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7027 SVOp->getOperand(Input),
7028 DAG.getIntPtrConstant(Idx)));
7031 // Construct the output using a BUILD_VECTOR.
7032 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7033 } else if (InputUsed[0] < 0) {
7034 // No input vectors were used! The result is undefined.
7035 Output[l] = DAG.getUNDEF(NVT);
7037 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7038 (InputUsed[0] % 2) * NumLaneElems,
7040 // If only one input was used, use an undefined vector for the other.
7041 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7042 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7043 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7044 // At least one input vector was used. Create a new shuffle vector.
7045 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7051 // Concatenate the result back
7052 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7055 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7056 /// 4 elements, and match them with several different shuffle types.
7058 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7059 SDValue V1 = SVOp->getOperand(0);
7060 SDValue V2 = SVOp->getOperand(1);
7062 MVT VT = SVOp->getSimpleValueType(0);
7064 assert(VT.is128BitVector() && "Unsupported vector size");
7066 std::pair<int, int> Locs[4];
7067 int Mask1[] = { -1, -1, -1, -1 };
7068 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7072 for (unsigned i = 0; i != 4; ++i) {
7073 int Idx = PermMask[i];
7075 Locs[i] = std::make_pair(-1, -1);
7077 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7079 Locs[i] = std::make_pair(0, NumLo);
7083 Locs[i] = std::make_pair(1, NumHi);
7085 Mask1[2+NumHi] = Idx;
7091 if (NumLo <= 2 && NumHi <= 2) {
7092 // If no more than two elements come from either vector. This can be
7093 // implemented with two shuffles. First shuffle gather the elements.
7094 // The second shuffle, which takes the first shuffle as both of its
7095 // vector operands, put the elements into the right order.
7096 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7098 int Mask2[] = { -1, -1, -1, -1 };
7100 for (unsigned i = 0; i != 4; ++i)
7101 if (Locs[i].first != -1) {
7102 unsigned Idx = (i < 2) ? 0 : 4;
7103 Idx += Locs[i].first * 2 + Locs[i].second;
7107 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7110 if (NumLo == 3 || NumHi == 3) {
7111 // Otherwise, we must have three elements from one vector, call it X, and
7112 // one element from the other, call it Y. First, use a shufps to build an
7113 // intermediate vector with the one element from Y and the element from X
7114 // that will be in the same half in the final destination (the indexes don't
7115 // matter). Then, use a shufps to build the final vector, taking the half
7116 // containing the element from Y from the intermediate, and the other half
7119 // Normalize it so the 3 elements come from V1.
7120 CommuteVectorShuffleMask(PermMask, 4);
7124 // Find the element from V2.
7126 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7127 int Val = PermMask[HiIndex];
7134 Mask1[0] = PermMask[HiIndex];
7136 Mask1[2] = PermMask[HiIndex^1];
7138 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7141 Mask1[0] = PermMask[0];
7142 Mask1[1] = PermMask[1];
7143 Mask1[2] = HiIndex & 1 ? 6 : 4;
7144 Mask1[3] = HiIndex & 1 ? 4 : 6;
7145 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7148 Mask1[0] = HiIndex & 1 ? 2 : 0;
7149 Mask1[1] = HiIndex & 1 ? 0 : 2;
7150 Mask1[2] = PermMask[2];
7151 Mask1[3] = PermMask[3];
7156 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7159 // Break it into (shuffle shuffle_hi, shuffle_lo).
7160 int LoMask[] = { -1, -1, -1, -1 };
7161 int HiMask[] = { -1, -1, -1, -1 };
7163 int *MaskPtr = LoMask;
7164 unsigned MaskIdx = 0;
7167 for (unsigned i = 0; i != 4; ++i) {
7174 int Idx = PermMask[i];
7176 Locs[i] = std::make_pair(-1, -1);
7177 } else if (Idx < 4) {
7178 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7179 MaskPtr[LoIdx] = Idx;
7182 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7183 MaskPtr[HiIdx] = Idx;
7188 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7189 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7190 int MaskOps[] = { -1, -1, -1, -1 };
7191 for (unsigned i = 0; i != 4; ++i)
7192 if (Locs[i].first != -1)
7193 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7194 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7197 static bool MayFoldVectorLoad(SDValue V) {
7198 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7199 V = V.getOperand(0);
7201 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7202 V = V.getOperand(0);
7203 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7204 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7205 // BUILD_VECTOR (load), undef
7206 V = V.getOperand(0);
7208 return MayFoldLoad(V);
7212 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7213 MVT VT = Op.getSimpleValueType();
7215 // Canonizalize to v2f64.
7216 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7217 return DAG.getNode(ISD::BITCAST, dl, VT,
7218 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7223 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7225 SDValue V1 = Op.getOperand(0);
7226 SDValue V2 = Op.getOperand(1);
7227 MVT VT = Op.getSimpleValueType();
7229 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7231 if (HasSSE2 && VT == MVT::v2f64)
7232 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7234 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7235 return DAG.getNode(ISD::BITCAST, dl, VT,
7236 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7237 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7238 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7242 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7243 SDValue V1 = Op.getOperand(0);
7244 SDValue V2 = Op.getOperand(1);
7245 MVT VT = Op.getSimpleValueType();
7247 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7248 "unsupported shuffle type");
7250 if (V2.getOpcode() == ISD::UNDEF)
7254 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7258 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7259 SDValue V1 = Op.getOperand(0);
7260 SDValue V2 = Op.getOperand(1);
7261 MVT VT = Op.getSimpleValueType();
7262 unsigned NumElems = VT.getVectorNumElements();
7264 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7265 // operand of these instructions is only memory, so check if there's a
7266 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7268 bool CanFoldLoad = false;
7270 // Trivial case, when V2 comes from a load.
7271 if (MayFoldVectorLoad(V2))
7274 // When V1 is a load, it can be folded later into a store in isel, example:
7275 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7277 // (MOVLPSmr addr:$src1, VR128:$src2)
7278 // So, recognize this potential and also use MOVLPS or MOVLPD
7279 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7282 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7284 if (HasSSE2 && NumElems == 2)
7285 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7288 // If we don't care about the second element, proceed to use movss.
7289 if (SVOp->getMaskElt(1) != -1)
7290 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7293 // movl and movlp will both match v2i64, but v2i64 is never matched by
7294 // movl earlier because we make it strict to avoid messing with the movlp load
7295 // folding logic (see the code above getMOVLP call). Match it here then,
7296 // this is horrible, but will stay like this until we move all shuffle
7297 // matching to x86 specific nodes. Note that for the 1st condition all
7298 // types are matched with movsd.
7300 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7301 // as to remove this logic from here, as much as possible
7302 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7303 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7304 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7307 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7309 // Invert the operand order and use SHUFPS to match it.
7310 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7311 getShuffleSHUFImmediate(SVOp), DAG);
7314 // It is only safe to call this function if isINSERTPSMask is true for
7315 // this shufflevector mask.
7316 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7317 SelectionDAG &DAG) {
7318 // Generate an insertps instruction when inserting an f32 from memory onto a
7319 // v4f32 or when copying a member from one v4f32 to another.
7320 // We also use it for transferring i32 from one register to another,
7321 // since it simply copies the same bits.
7322 // If we're transfering an i32 from memory to a specific element in a
7323 // register, we output a generic DAG that will match the PINSRD
7325 // TODO: Optimize for AVX cases too (VINSERTPS)
7326 MVT VT = SVOp->getSimpleValueType(0);
7327 MVT EVT = VT.getVectorElementType();
7328 SDValue V1 = SVOp->getOperand(0);
7329 SDValue V2 = SVOp->getOperand(1);
7330 auto Mask = SVOp->getMask();
7331 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7332 "unsupported vector type for insertps/pinsrd");
7334 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7335 [](const int &i) { return i < 4; });
7343 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7344 [](const int &i) { return i < 4; }) -
7349 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7350 [](const int &i) { return i >= 4; }) -
7354 if (MayFoldLoad(From)) {
7355 // Trivial case, when From comes from a load and is only used by the
7356 // shuffle. Make it use insertps from the vector that we need from that
7358 SDValue Addr = From.getOperand(1);
7360 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7361 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7362 Addr.getSimpleValueType()));
7364 LoadSDNode *Load = cast<LoadSDNode>(From);
7366 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7367 DAG.getMachineFunction().getMachineMemOperand(
7368 Load->getMemOperand(), 0, EVT.getStoreSize()));
7370 if (EVT == MVT::f32) {
7371 // Create this as a scalar to vector to match the instruction pattern.
7372 SDValue LoadScalarToVector =
7373 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7374 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7375 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7377 } else { // EVT == MVT::i32
7378 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7379 // instruction, to match the PINSRD instruction, which loads an i32 to a
7380 // certain vector element.
7381 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7382 DAG.getConstant(DestIndex, MVT::i32));
7386 // Vector-element-to-vector
7387 unsigned SrcIndex = Mask[DestIndex] % 4;
7388 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7389 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7392 // Reduce a vector shuffle to zext.
7393 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7394 SelectionDAG &DAG) {
7395 // PMOVZX is only available from SSE41.
7396 if (!Subtarget->hasSSE41())
7399 MVT VT = Op.getSimpleValueType();
7401 // Only AVX2 support 256-bit vector integer extending.
7402 if (!Subtarget->hasInt256() && VT.is256BitVector())
7405 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7407 SDValue V1 = Op.getOperand(0);
7408 SDValue V2 = Op.getOperand(1);
7409 unsigned NumElems = VT.getVectorNumElements();
7411 // Extending is an unary operation and the element type of the source vector
7412 // won't be equal to or larger than i64.
7413 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7414 VT.getVectorElementType() == MVT::i64)
7417 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7418 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7419 while ((1U << Shift) < NumElems) {
7420 if (SVOp->getMaskElt(1U << Shift) == 1)
7423 // The maximal ratio is 8, i.e. from i8 to i64.
7428 // Check the shuffle mask.
7429 unsigned Mask = (1U << Shift) - 1;
7430 for (unsigned i = 0; i != NumElems; ++i) {
7431 int EltIdx = SVOp->getMaskElt(i);
7432 if ((i & Mask) != 0 && EltIdx != -1)
7434 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7438 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7439 MVT NeVT = MVT::getIntegerVT(NBits);
7440 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7442 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7445 // Simplify the operand as it's prepared to be fed into shuffle.
7446 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7447 if (V1.getOpcode() == ISD::BITCAST &&
7448 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7449 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7450 V1.getOperand(0).getOperand(0)
7451 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7452 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7453 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7454 ConstantSDNode *CIdx =
7455 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7456 // If it's foldable, i.e. normal load with single use, we will let code
7457 // selection to fold it. Otherwise, we will short the conversion sequence.
7458 if (CIdx && CIdx->getZExtValue() == 0 &&
7459 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7460 MVT FullVT = V.getSimpleValueType();
7461 MVT V1VT = V1.getSimpleValueType();
7462 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7463 // The "ext_vec_elt" node is wider than the result node.
7464 // In this case we should extract subvector from V.
7465 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7466 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7467 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7468 FullVT.getVectorNumElements()/Ratio);
7469 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7470 DAG.getIntPtrConstant(0));
7472 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7476 return DAG.getNode(ISD::BITCAST, DL, VT,
7477 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7481 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7482 SelectionDAG &DAG) {
7483 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7484 MVT VT = Op.getSimpleValueType();
7486 SDValue V1 = Op.getOperand(0);
7487 SDValue V2 = Op.getOperand(1);
7489 if (isZeroShuffle(SVOp))
7490 return getZeroVector(VT, Subtarget, DAG, dl);
7492 // Handle splat operations
7493 if (SVOp->isSplat()) {
7494 // Use vbroadcast whenever the splat comes from a foldable load
7495 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7496 if (Broadcast.getNode())
7500 // Check integer expanding shuffles.
7501 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7502 if (NewOp.getNode())
7505 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7507 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7508 VT == MVT::v16i16 || VT == MVT::v32i8) {
7509 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7510 if (NewOp.getNode())
7511 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7512 } else if ((VT == MVT::v4i32 ||
7513 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7514 // FIXME: Figure out a cleaner way to do this.
7515 // Try to make use of movq to zero out the top part.
7516 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7517 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7518 if (NewOp.getNode()) {
7519 MVT NewVT = NewOp.getSimpleValueType();
7520 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7521 NewVT, true, false))
7522 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7523 DAG, Subtarget, dl);
7525 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7526 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7527 if (NewOp.getNode()) {
7528 MVT NewVT = NewOp.getSimpleValueType();
7529 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7530 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7531 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 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13195 assert(Subtarget->isTargetWin64() && "Unexpected target");
13196 EVT VT = Op.getValueType();
13197 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13198 "Unexpected return type for lowering");
13202 switch (Op->getOpcode()) {
13203 default: llvm_unreachable("Unexpected request for libcall!");
13204 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13205 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13206 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13207 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13208 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13209 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13213 SDValue InChain = DAG.getEntryNode();
13215 TargetLowering::ArgListTy Args;
13216 TargetLowering::ArgListEntry Entry;
13217 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13218 EVT ArgVT = Op->getOperand(i).getValueType();
13219 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13220 "Unexpected argument type for lowering");
13221 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13222 Entry.Node = StackPtr;
13223 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13225 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13226 Entry.Ty = PointerType::get(ArgTy,0);
13227 Entry.isSExt = false;
13228 Entry.isZExt = false;
13229 Args.push_back(Entry);
13232 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13235 TargetLowering::CallLoweringInfo CLI(
13236 InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13237 isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13238 /*isTailCall=*/false,
13239 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13241 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13243 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13246 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13247 SelectionDAG &DAG) {
13248 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13249 EVT VT = Op0.getValueType();
13252 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13253 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13255 // Get the high parts.
13256 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13257 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13258 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13260 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13262 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13263 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13265 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13266 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13267 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13268 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13269 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13271 // Shuffle it back into the right order.
13272 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13273 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13274 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13275 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13277 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13278 // unsigned multiply.
13279 if (IsSigned && !Subtarget->hasSSE41()) {
13281 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13282 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13283 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13284 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13285 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13287 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13288 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13291 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13294 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13295 const X86Subtarget *Subtarget) {
13296 MVT VT = Op.getSimpleValueType();
13298 SDValue R = Op.getOperand(0);
13299 SDValue Amt = Op.getOperand(1);
13301 // Optimize shl/srl/sra with constant shift amount.
13302 if (isSplatVector(Amt.getNode())) {
13303 SDValue SclrAmt = Amt->getOperand(0);
13304 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13305 uint64_t ShiftAmt = C->getZExtValue();
13307 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13308 (Subtarget->hasInt256() &&
13309 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13310 (Subtarget->hasAVX512() &&
13311 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13312 if (Op.getOpcode() == ISD::SHL)
13313 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13315 if (Op.getOpcode() == ISD::SRL)
13316 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13318 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13319 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13323 if (VT == MVT::v16i8) {
13324 if (Op.getOpcode() == ISD::SHL) {
13325 // Make a large shift.
13326 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13327 MVT::v8i16, R, ShiftAmt,
13329 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13330 // Zero out the rightmost bits.
13331 SmallVector<SDValue, 16> V(16,
13332 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13334 return DAG.getNode(ISD::AND, dl, VT, SHL,
13335 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13337 if (Op.getOpcode() == ISD::SRL) {
13338 // Make a large shift.
13339 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13340 MVT::v8i16, R, ShiftAmt,
13342 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13343 // Zero out the leftmost bits.
13344 SmallVector<SDValue, 16> V(16,
13345 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13347 return DAG.getNode(ISD::AND, dl, VT, SRL,
13348 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13350 if (Op.getOpcode() == ISD::SRA) {
13351 if (ShiftAmt == 7) {
13352 // R s>> 7 === R s< 0
13353 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13354 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13357 // R s>> a === ((R u>> a) ^ m) - m
13358 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13359 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13361 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13362 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13363 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13366 llvm_unreachable("Unknown shift opcode.");
13369 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13370 if (Op.getOpcode() == ISD::SHL) {
13371 // Make a large shift.
13372 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13373 MVT::v16i16, R, ShiftAmt,
13375 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13376 // Zero out the rightmost bits.
13377 SmallVector<SDValue, 32> V(32,
13378 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13380 return DAG.getNode(ISD::AND, dl, VT, SHL,
13381 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13383 if (Op.getOpcode() == ISD::SRL) {
13384 // Make a large shift.
13385 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13386 MVT::v16i16, R, ShiftAmt,
13388 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13389 // Zero out the leftmost bits.
13390 SmallVector<SDValue, 32> V(32,
13391 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13393 return DAG.getNode(ISD::AND, dl, VT, SRL,
13394 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13396 if (Op.getOpcode() == ISD::SRA) {
13397 if (ShiftAmt == 7) {
13398 // R s>> 7 === R s< 0
13399 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13400 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13403 // R s>> a === ((R u>> a) ^ m) - m
13404 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13405 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13407 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13408 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13409 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13412 llvm_unreachable("Unknown shift opcode.");
13417 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13418 if (!Subtarget->is64Bit() &&
13419 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13420 Amt.getOpcode() == ISD::BITCAST &&
13421 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13422 Amt = Amt.getOperand(0);
13423 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13424 VT.getVectorNumElements();
13425 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13426 uint64_t ShiftAmt = 0;
13427 for (unsigned i = 0; i != Ratio; ++i) {
13428 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13432 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13434 // Check remaining shift amounts.
13435 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13436 uint64_t ShAmt = 0;
13437 for (unsigned j = 0; j != Ratio; ++j) {
13438 ConstantSDNode *C =
13439 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13443 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13445 if (ShAmt != ShiftAmt)
13448 switch (Op.getOpcode()) {
13450 llvm_unreachable("Unknown shift opcode!");
13452 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13455 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13458 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13466 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13467 const X86Subtarget* Subtarget) {
13468 MVT VT = Op.getSimpleValueType();
13470 SDValue R = Op.getOperand(0);
13471 SDValue Amt = Op.getOperand(1);
13473 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13474 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13475 (Subtarget->hasInt256() &&
13476 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13477 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13478 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13480 EVT EltVT = VT.getVectorElementType();
13482 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13483 unsigned NumElts = VT.getVectorNumElements();
13485 for (i = 0; i != NumElts; ++i) {
13486 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13490 for (j = i; j != NumElts; ++j) {
13491 SDValue Arg = Amt.getOperand(j);
13492 if (Arg.getOpcode() == ISD::UNDEF) continue;
13493 if (Arg != Amt.getOperand(i))
13496 if (i != NumElts && j == NumElts)
13497 BaseShAmt = Amt.getOperand(i);
13499 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13500 Amt = Amt.getOperand(0);
13501 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13502 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13503 SDValue InVec = Amt.getOperand(0);
13504 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13505 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13507 for (; i != NumElts; ++i) {
13508 SDValue Arg = InVec.getOperand(i);
13509 if (Arg.getOpcode() == ISD::UNDEF) continue;
13513 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13514 if (ConstantSDNode *C =
13515 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13516 unsigned SplatIdx =
13517 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13518 if (C->getZExtValue() == SplatIdx)
13519 BaseShAmt = InVec.getOperand(1);
13522 if (!BaseShAmt.getNode())
13523 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13524 DAG.getIntPtrConstant(0));
13528 if (BaseShAmt.getNode()) {
13529 if (EltVT.bitsGT(MVT::i32))
13530 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13531 else if (EltVT.bitsLT(MVT::i32))
13532 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13534 switch (Op.getOpcode()) {
13536 llvm_unreachable("Unknown shift opcode!");
13538 switch (VT.SimpleTy) {
13539 default: return SDValue();
13548 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13551 switch (VT.SimpleTy) {
13552 default: return SDValue();
13559 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13562 switch (VT.SimpleTy) {
13563 default: return SDValue();
13572 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13578 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13579 if (!Subtarget->is64Bit() &&
13580 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13581 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13582 Amt.getOpcode() == ISD::BITCAST &&
13583 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13584 Amt = Amt.getOperand(0);
13585 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13586 VT.getVectorNumElements();
13587 std::vector<SDValue> Vals(Ratio);
13588 for (unsigned i = 0; i != Ratio; ++i)
13589 Vals[i] = Amt.getOperand(i);
13590 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13591 for (unsigned j = 0; j != Ratio; ++j)
13592 if (Vals[j] != Amt.getOperand(i + j))
13595 switch (Op.getOpcode()) {
13597 llvm_unreachable("Unknown shift opcode!");
13599 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13601 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13603 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13610 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13611 SelectionDAG &DAG) {
13613 MVT VT = Op.getSimpleValueType();
13615 SDValue R = Op.getOperand(0);
13616 SDValue Amt = Op.getOperand(1);
13619 if (!Subtarget->hasSSE2())
13622 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13626 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13630 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13632 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13633 if (Subtarget->hasInt256()) {
13634 if (Op.getOpcode() == ISD::SRL &&
13635 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13636 VT == MVT::v4i64 || VT == MVT::v8i32))
13638 if (Op.getOpcode() == ISD::SHL &&
13639 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13640 VT == MVT::v4i64 || VT == MVT::v8i32))
13642 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13646 // If possible, lower this packed shift into a vector multiply instead of
13647 // expanding it into a sequence of scalar shifts.
13648 // Do this only if the vector shift count is a constant build_vector.
13649 if (Op.getOpcode() == ISD::SHL &&
13650 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13651 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13652 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13653 SmallVector<SDValue, 8> Elts;
13654 EVT SVT = VT.getScalarType();
13655 unsigned SVTBits = SVT.getSizeInBits();
13656 const APInt &One = APInt(SVTBits, 1);
13657 unsigned NumElems = VT.getVectorNumElements();
13659 for (unsigned i=0; i !=NumElems; ++i) {
13660 SDValue Op = Amt->getOperand(i);
13661 if (Op->getOpcode() == ISD::UNDEF) {
13662 Elts.push_back(Op);
13666 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13667 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13668 uint64_t ShAmt = C.getZExtValue();
13669 if (ShAmt >= SVTBits) {
13670 Elts.push_back(DAG.getUNDEF(SVT));
13673 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13675 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13676 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13679 // Lower SHL with variable shift amount.
13680 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13681 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13683 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13684 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13685 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13686 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13689 // If possible, lower this shift as a sequence of two shifts by
13690 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13692 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13694 // Could be rewritten as:
13695 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13697 // The advantage is that the two shifts from the example would be
13698 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13699 // the vector shift into four scalar shifts plus four pairs of vector
13701 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13702 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13703 unsigned TargetOpcode = X86ISD::MOVSS;
13704 bool CanBeSimplified;
13705 // The splat value for the first packed shift (the 'X' from the example).
13706 SDValue Amt1 = Amt->getOperand(0);
13707 // The splat value for the second packed shift (the 'Y' from the example).
13708 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13709 Amt->getOperand(2);
13711 // See if it is possible to replace this node with a sequence of
13712 // two shifts followed by a MOVSS/MOVSD
13713 if (VT == MVT::v4i32) {
13714 // Check if it is legal to use a MOVSS.
13715 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13716 Amt2 == Amt->getOperand(3);
13717 if (!CanBeSimplified) {
13718 // Otherwise, check if we can still simplify this node using a MOVSD.
13719 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13720 Amt->getOperand(2) == Amt->getOperand(3);
13721 TargetOpcode = X86ISD::MOVSD;
13722 Amt2 = Amt->getOperand(2);
13725 // Do similar checks for the case where the machine value type
13727 CanBeSimplified = Amt1 == Amt->getOperand(1);
13728 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13729 CanBeSimplified = Amt2 == Amt->getOperand(i);
13731 if (!CanBeSimplified) {
13732 TargetOpcode = X86ISD::MOVSD;
13733 CanBeSimplified = true;
13734 Amt2 = Amt->getOperand(4);
13735 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13736 CanBeSimplified = Amt1 == Amt->getOperand(i);
13737 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13738 CanBeSimplified = Amt2 == Amt->getOperand(j);
13742 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13743 isa<ConstantSDNode>(Amt2)) {
13744 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13745 EVT CastVT = MVT::v4i32;
13747 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13748 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13750 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13751 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13752 if (TargetOpcode == X86ISD::MOVSD)
13753 CastVT = MVT::v2i64;
13754 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13755 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13756 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13758 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13762 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13763 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13766 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13767 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13769 // Turn 'a' into a mask suitable for VSELECT
13770 SDValue VSelM = DAG.getConstant(0x80, VT);
13771 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13772 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13774 SDValue CM1 = DAG.getConstant(0x0f, VT);
13775 SDValue CM2 = DAG.getConstant(0x3f, VT);
13777 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13778 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13779 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13780 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13781 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13784 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13785 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13786 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13788 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13789 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13790 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13791 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13792 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13795 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13796 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13797 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13799 // return VSELECT(r, r+r, a);
13800 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13801 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13805 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13806 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13807 // solution better.
13808 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13809 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13811 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13812 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13813 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13814 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13815 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13818 // Decompose 256-bit shifts into smaller 128-bit shifts.
13819 if (VT.is256BitVector()) {
13820 unsigned NumElems = VT.getVectorNumElements();
13821 MVT EltVT = VT.getVectorElementType();
13822 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13824 // Extract the two vectors
13825 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13826 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13828 // Recreate the shift amount vectors
13829 SDValue Amt1, Amt2;
13830 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13831 // Constant shift amount
13832 SmallVector<SDValue, 4> Amt1Csts;
13833 SmallVector<SDValue, 4> Amt2Csts;
13834 for (unsigned i = 0; i != NumElems/2; ++i)
13835 Amt1Csts.push_back(Amt->getOperand(i));
13836 for (unsigned i = NumElems/2; i != NumElems; ++i)
13837 Amt2Csts.push_back(Amt->getOperand(i));
13839 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13840 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13842 // Variable shift amount
13843 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13844 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13847 // Issue new vector shifts for the smaller types
13848 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13849 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13851 // Concatenate the result back
13852 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13858 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13859 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13860 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13861 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13862 // has only one use.
13863 SDNode *N = Op.getNode();
13864 SDValue LHS = N->getOperand(0);
13865 SDValue RHS = N->getOperand(1);
13866 unsigned BaseOp = 0;
13869 switch (Op.getOpcode()) {
13870 default: llvm_unreachable("Unknown ovf instruction!");
13872 // A subtract of one will be selected as a INC. Note that INC doesn't
13873 // set CF, so we can't do this for UADDO.
13874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13876 BaseOp = X86ISD::INC;
13877 Cond = X86::COND_O;
13880 BaseOp = X86ISD::ADD;
13881 Cond = X86::COND_O;
13884 BaseOp = X86ISD::ADD;
13885 Cond = X86::COND_B;
13888 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13889 // set CF, so we can't do this for USUBO.
13890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13892 BaseOp = X86ISD::DEC;
13893 Cond = X86::COND_O;
13896 BaseOp = X86ISD::SUB;
13897 Cond = X86::COND_O;
13900 BaseOp = X86ISD::SUB;
13901 Cond = X86::COND_B;
13904 BaseOp = X86ISD::SMUL;
13905 Cond = X86::COND_O;
13907 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13908 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13910 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13913 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13914 DAG.getConstant(X86::COND_O, MVT::i32),
13915 SDValue(Sum.getNode(), 2));
13917 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13921 // Also sets EFLAGS.
13922 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13923 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13926 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13927 DAG.getConstant(Cond, MVT::i32),
13928 SDValue(Sum.getNode(), 1));
13930 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13933 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13934 SelectionDAG &DAG) const {
13936 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13937 MVT VT = Op.getSimpleValueType();
13939 if (!Subtarget->hasSSE2() || !VT.isVector())
13942 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13943 ExtraVT.getScalarType().getSizeInBits();
13945 switch (VT.SimpleTy) {
13946 default: return SDValue();
13949 if (!Subtarget->hasFp256())
13951 if (!Subtarget->hasInt256()) {
13952 // needs to be split
13953 unsigned NumElems = VT.getVectorNumElements();
13955 // Extract the LHS vectors
13956 SDValue LHS = Op.getOperand(0);
13957 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13958 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13960 MVT EltVT = VT.getVectorElementType();
13961 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13963 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13964 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13965 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13967 SDValue Extra = DAG.getValueType(ExtraVT);
13969 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13970 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13972 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13977 SDValue Op0 = Op.getOperand(0);
13978 SDValue Op00 = Op0.getOperand(0);
13980 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13981 if (Op0.getOpcode() == ISD::BITCAST &&
13982 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13983 // (sext (vzext x)) -> (vsext x)
13984 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13985 if (Tmp1.getNode()) {
13986 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13987 // This folding is only valid when the in-reg type is a vector of i8,
13989 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13990 ExtraEltVT == MVT::i32) {
13991 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13992 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13993 "This optimization is invalid without a VZEXT.");
13994 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14000 // If the above didn't work, then just use Shift-Left + Shift-Right.
14001 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14003 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14009 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14010 SelectionDAG &DAG) {
14012 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14013 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14014 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14015 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14017 // The only fence that needs an instruction is a sequentially-consistent
14018 // cross-thread fence.
14019 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14020 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14021 // no-sse2). There isn't any reason to disable it if the target processor
14023 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14024 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14026 SDValue Chain = Op.getOperand(0);
14027 SDValue Zero = DAG.getConstant(0, MVT::i32);
14029 DAG.getRegister(X86::ESP, MVT::i32), // Base
14030 DAG.getTargetConstant(1, MVT::i8), // Scale
14031 DAG.getRegister(0, MVT::i32), // Index
14032 DAG.getTargetConstant(0, MVT::i32), // Disp
14033 DAG.getRegister(0, MVT::i32), // Segment.
14037 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14038 return SDValue(Res, 0);
14041 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14042 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14045 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14046 SelectionDAG &DAG) {
14047 MVT T = Op.getSimpleValueType();
14051 switch(T.SimpleTy) {
14052 default: llvm_unreachable("Invalid value type!");
14053 case MVT::i8: Reg = X86::AL; size = 1; break;
14054 case MVT::i16: Reg = X86::AX; size = 2; break;
14055 case MVT::i32: Reg = X86::EAX; size = 4; break;
14057 assert(Subtarget->is64Bit() && "Node not type legal!");
14058 Reg = X86::RAX; size = 8;
14061 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14062 Op.getOperand(2), SDValue());
14063 SDValue Ops[] = { cpIn.getValue(0),
14066 DAG.getTargetConstant(size, MVT::i8),
14067 cpIn.getValue(1) };
14068 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14069 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14070 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14073 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14077 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14078 SelectionDAG &DAG) {
14079 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14080 MVT DstVT = Op.getSimpleValueType();
14081 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14082 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14083 assert((DstVT == MVT::i64 ||
14084 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14085 "Unexpected custom BITCAST");
14086 // i64 <=> MMX conversions are Legal.
14087 if (SrcVT==MVT::i64 && DstVT.isVector())
14089 if (DstVT==MVT::i64 && SrcVT.isVector())
14091 // MMX <=> MMX conversions are Legal.
14092 if (SrcVT.isVector() && DstVT.isVector())
14094 // All other conversions need to be expanded.
14098 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14099 SDNode *Node = Op.getNode();
14101 EVT T = Node->getValueType(0);
14102 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14103 DAG.getConstant(0, T), Node->getOperand(2));
14104 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14105 cast<AtomicSDNode>(Node)->getMemoryVT(),
14106 Node->getOperand(0),
14107 Node->getOperand(1), negOp,
14108 cast<AtomicSDNode>(Node)->getMemOperand(),
14109 cast<AtomicSDNode>(Node)->getOrdering(),
14110 cast<AtomicSDNode>(Node)->getSynchScope());
14113 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14114 SDNode *Node = Op.getNode();
14116 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14118 // Convert seq_cst store -> xchg
14119 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14120 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14121 // (The only way to get a 16-byte store is cmpxchg16b)
14122 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14123 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14124 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14125 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14126 cast<AtomicSDNode>(Node)->getMemoryVT(),
14127 Node->getOperand(0),
14128 Node->getOperand(1), Node->getOperand(2),
14129 cast<AtomicSDNode>(Node)->getMemOperand(),
14130 cast<AtomicSDNode>(Node)->getOrdering(),
14131 cast<AtomicSDNode>(Node)->getSynchScope());
14132 return Swap.getValue(1);
14134 // Other atomic stores have a simple pattern.
14138 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14139 EVT VT = Op.getNode()->getSimpleValueType(0);
14141 // Let legalize expand this if it isn't a legal type yet.
14142 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14145 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14148 bool ExtraOp = false;
14149 switch (Op.getOpcode()) {
14150 default: llvm_unreachable("Invalid code");
14151 case ISD::ADDC: Opc = X86ISD::ADD; break;
14152 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14153 case ISD::SUBC: Opc = X86ISD::SUB; break;
14154 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14158 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14160 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14161 Op.getOperand(1), Op.getOperand(2));
14164 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14165 SelectionDAG &DAG) {
14166 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14168 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14169 // which returns the values as { float, float } (in XMM0) or
14170 // { double, double } (which is returned in XMM0, XMM1).
14172 SDValue Arg = Op.getOperand(0);
14173 EVT ArgVT = Arg.getValueType();
14174 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14176 TargetLowering::ArgListTy Args;
14177 TargetLowering::ArgListEntry Entry;
14181 Entry.isSExt = false;
14182 Entry.isZExt = false;
14183 Args.push_back(Entry);
14185 bool isF64 = ArgVT == MVT::f64;
14186 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14187 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14188 // the results are returned via SRet in memory.
14189 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14190 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14191 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14193 Type *RetTy = isF64
14194 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14195 : (Type*)VectorType::get(ArgTy, 4);
14197 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14198 false, false, false, false, 0,
14199 CallingConv::C, /*isTaillCall=*/false,
14200 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14201 Callee, Args, DAG, dl);
14202 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14205 // Returned in xmm0 and xmm1.
14206 return CallResult.first;
14208 // Returned in bits 0:31 and 32:64 xmm0.
14209 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14210 CallResult.first, DAG.getIntPtrConstant(0));
14211 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14212 CallResult.first, DAG.getIntPtrConstant(1));
14213 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14214 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14217 /// LowerOperation - Provide custom lowering hooks for some operations.
14219 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14220 switch (Op.getOpcode()) {
14221 default: llvm_unreachable("Should not custom lower this!");
14222 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14223 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14224 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14225 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14226 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14227 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14228 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14229 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14230 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14231 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14232 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14233 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14234 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14235 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14236 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14237 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14238 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14239 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14240 case ISD::SHL_PARTS:
14241 case ISD::SRA_PARTS:
14242 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14243 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14244 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14245 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14246 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14247 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14248 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14249 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14250 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14251 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14252 case ISD::FABS: return LowerFABS(Op, DAG);
14253 case ISD::FNEG: return LowerFNEG(Op, DAG);
14254 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14255 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14256 case ISD::SETCC: return LowerSETCC(Op, DAG);
14257 case ISD::SELECT: return LowerSELECT(Op, DAG);
14258 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14259 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14260 case ISD::VASTART: return LowerVASTART(Op, DAG);
14261 case ISD::VAARG: return LowerVAARG(Op, DAG);
14262 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14263 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14264 case ISD::INTRINSIC_VOID:
14265 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14266 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14267 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14268 case ISD::FRAME_TO_ARGS_OFFSET:
14269 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14270 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14271 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14272 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14273 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14274 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14275 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14276 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14277 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14278 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14279 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14280 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14281 case ISD::UMUL_LOHI:
14282 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14285 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14291 case ISD::UMULO: return LowerXALUO(Op, DAG);
14292 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14293 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14297 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14298 case ISD::ADD: return LowerADD(Op, DAG);
14299 case ISD::SUB: return LowerSUB(Op, DAG);
14300 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14304 static void ReplaceATOMIC_LOAD(SDNode *Node,
14305 SmallVectorImpl<SDValue> &Results,
14306 SelectionDAG &DAG) {
14308 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14310 // Convert wide load -> cmpxchg8b/cmpxchg16b
14311 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14312 // (The only way to get a 16-byte load is cmpxchg16b)
14313 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14314 SDValue Zero = DAG.getConstant(0, VT);
14315 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14316 Node->getOperand(0),
14317 Node->getOperand(1), Zero, Zero,
14318 cast<AtomicSDNode>(Node)->getMemOperand(),
14319 cast<AtomicSDNode>(Node)->getOrdering(),
14320 cast<AtomicSDNode>(Node)->getOrdering(),
14321 cast<AtomicSDNode>(Node)->getSynchScope());
14322 Results.push_back(Swap.getValue(0));
14323 Results.push_back(Swap.getValue(1));
14327 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14328 SelectionDAG &DAG, unsigned NewOp) {
14330 assert (Node->getValueType(0) == MVT::i64 &&
14331 "Only know how to expand i64 atomics");
14333 SDValue Chain = Node->getOperand(0);
14334 SDValue In1 = Node->getOperand(1);
14335 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14336 Node->getOperand(2), DAG.getIntPtrConstant(0));
14337 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14338 Node->getOperand(2), DAG.getIntPtrConstant(1));
14339 SDValue Ops[] = { Chain, In1, In2L, In2H };
14340 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14342 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14343 cast<MemSDNode>(Node)->getMemOperand());
14344 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14345 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14346 Results.push_back(Result.getValue(2));
14349 /// ReplaceNodeResults - Replace a node with an illegal result type
14350 /// with a new node built out of custom code.
14351 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14352 SmallVectorImpl<SDValue>&Results,
14353 SelectionDAG &DAG) const {
14355 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14356 switch (N->getOpcode()) {
14358 llvm_unreachable("Do not know how to custom type legalize this operation!");
14359 case ISD::SIGN_EXTEND_INREG:
14364 // We don't want to expand or promote these.
14371 case ISD::UDIVREM: {
14372 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14373 Results.push_back(V);
14376 case ISD::FP_TO_SINT:
14377 case ISD::FP_TO_UINT: {
14378 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14380 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14383 std::pair<SDValue,SDValue> Vals =
14384 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14385 SDValue FIST = Vals.first, StackSlot = Vals.second;
14386 if (FIST.getNode()) {
14387 EVT VT = N->getValueType(0);
14388 // Return a load from the stack slot.
14389 if (StackSlot.getNode())
14390 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14391 MachinePointerInfo(),
14392 false, false, false, 0));
14394 Results.push_back(FIST);
14398 case ISD::UINT_TO_FP: {
14399 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14400 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14401 N->getValueType(0) != MVT::v2f32)
14403 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14405 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14407 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14408 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14409 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14410 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14411 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14412 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14415 case ISD::FP_ROUND: {
14416 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14418 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14419 Results.push_back(V);
14422 case ISD::INTRINSIC_W_CHAIN: {
14423 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14425 default : llvm_unreachable("Do not know how to custom type "
14426 "legalize this intrinsic operation!");
14427 case Intrinsic::x86_rdtsc:
14428 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14430 case Intrinsic::x86_rdtscp:
14431 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14435 case ISD::READCYCLECOUNTER: {
14436 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14439 case ISD::ATOMIC_CMP_SWAP: {
14440 EVT T = N->getValueType(0);
14441 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14442 bool Regs64bit = T == MVT::i128;
14443 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14444 SDValue cpInL, cpInH;
14445 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14446 DAG.getConstant(0, HalfT));
14447 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14448 DAG.getConstant(1, HalfT));
14449 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14450 Regs64bit ? X86::RAX : X86::EAX,
14452 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14453 Regs64bit ? X86::RDX : X86::EDX,
14454 cpInH, cpInL.getValue(1));
14455 SDValue swapInL, swapInH;
14456 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14457 DAG.getConstant(0, HalfT));
14458 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14459 DAG.getConstant(1, HalfT));
14460 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14461 Regs64bit ? X86::RBX : X86::EBX,
14462 swapInL, cpInH.getValue(1));
14463 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14464 Regs64bit ? X86::RCX : X86::ECX,
14465 swapInH, swapInL.getValue(1));
14466 SDValue Ops[] = { swapInH.getValue(0),
14468 swapInH.getValue(1) };
14469 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14470 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14471 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14472 X86ISD::LCMPXCHG8_DAG;
14473 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14474 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14475 Regs64bit ? X86::RAX : X86::EAX,
14476 HalfT, Result.getValue(1));
14477 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14478 Regs64bit ? X86::RDX : X86::EDX,
14479 HalfT, cpOutL.getValue(2));
14480 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14481 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14482 Results.push_back(cpOutH.getValue(1));
14485 case ISD::ATOMIC_LOAD_ADD:
14486 case ISD::ATOMIC_LOAD_AND:
14487 case ISD::ATOMIC_LOAD_NAND:
14488 case ISD::ATOMIC_LOAD_OR:
14489 case ISD::ATOMIC_LOAD_SUB:
14490 case ISD::ATOMIC_LOAD_XOR:
14491 case ISD::ATOMIC_LOAD_MAX:
14492 case ISD::ATOMIC_LOAD_MIN:
14493 case ISD::ATOMIC_LOAD_UMAX:
14494 case ISD::ATOMIC_LOAD_UMIN:
14495 case ISD::ATOMIC_SWAP: {
14497 switch (N->getOpcode()) {
14498 default: llvm_unreachable("Unexpected opcode");
14499 case ISD::ATOMIC_LOAD_ADD:
14500 Opc = X86ISD::ATOMADD64_DAG;
14502 case ISD::ATOMIC_LOAD_AND:
14503 Opc = X86ISD::ATOMAND64_DAG;
14505 case ISD::ATOMIC_LOAD_NAND:
14506 Opc = X86ISD::ATOMNAND64_DAG;
14508 case ISD::ATOMIC_LOAD_OR:
14509 Opc = X86ISD::ATOMOR64_DAG;
14511 case ISD::ATOMIC_LOAD_SUB:
14512 Opc = X86ISD::ATOMSUB64_DAG;
14514 case ISD::ATOMIC_LOAD_XOR:
14515 Opc = X86ISD::ATOMXOR64_DAG;
14517 case ISD::ATOMIC_LOAD_MAX:
14518 Opc = X86ISD::ATOMMAX64_DAG;
14520 case ISD::ATOMIC_LOAD_MIN:
14521 Opc = X86ISD::ATOMMIN64_DAG;
14523 case ISD::ATOMIC_LOAD_UMAX:
14524 Opc = X86ISD::ATOMUMAX64_DAG;
14526 case ISD::ATOMIC_LOAD_UMIN:
14527 Opc = X86ISD::ATOMUMIN64_DAG;
14529 case ISD::ATOMIC_SWAP:
14530 Opc = X86ISD::ATOMSWAP64_DAG;
14533 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14536 case ISD::ATOMIC_LOAD:
14537 ReplaceATOMIC_LOAD(N, Results, DAG);
14541 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14543 default: return nullptr;
14544 case X86ISD::BSF: return "X86ISD::BSF";
14545 case X86ISD::BSR: return "X86ISD::BSR";
14546 case X86ISD::SHLD: return "X86ISD::SHLD";
14547 case X86ISD::SHRD: return "X86ISD::SHRD";
14548 case X86ISD::FAND: return "X86ISD::FAND";
14549 case X86ISD::FANDN: return "X86ISD::FANDN";
14550 case X86ISD::FOR: return "X86ISD::FOR";
14551 case X86ISD::FXOR: return "X86ISD::FXOR";
14552 case X86ISD::FSRL: return "X86ISD::FSRL";
14553 case X86ISD::FILD: return "X86ISD::FILD";
14554 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14555 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14556 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14557 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14558 case X86ISD::FLD: return "X86ISD::FLD";
14559 case X86ISD::FST: return "X86ISD::FST";
14560 case X86ISD::CALL: return "X86ISD::CALL";
14561 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14562 case X86ISD::BT: return "X86ISD::BT";
14563 case X86ISD::CMP: return "X86ISD::CMP";
14564 case X86ISD::COMI: return "X86ISD::COMI";
14565 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14566 case X86ISD::CMPM: return "X86ISD::CMPM";
14567 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14568 case X86ISD::SETCC: return "X86ISD::SETCC";
14569 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14570 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14571 case X86ISD::CMOV: return "X86ISD::CMOV";
14572 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14573 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14574 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14575 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14576 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14577 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14578 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14579 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14580 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14581 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14582 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14583 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14584 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14585 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14586 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14587 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14588 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14589 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14590 case X86ISD::HADD: return "X86ISD::HADD";
14591 case X86ISD::HSUB: return "X86ISD::HSUB";
14592 case X86ISD::FHADD: return "X86ISD::FHADD";
14593 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14594 case X86ISD::UMAX: return "X86ISD::UMAX";
14595 case X86ISD::UMIN: return "X86ISD::UMIN";
14596 case X86ISD::SMAX: return "X86ISD::SMAX";
14597 case X86ISD::SMIN: return "X86ISD::SMIN";
14598 case X86ISD::FMAX: return "X86ISD::FMAX";
14599 case X86ISD::FMIN: return "X86ISD::FMIN";
14600 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14601 case X86ISD::FMINC: return "X86ISD::FMINC";
14602 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14603 case X86ISD::FRCP: return "X86ISD::FRCP";
14604 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14605 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14606 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14607 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14608 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14609 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14610 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14611 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14612 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14613 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14614 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14615 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14616 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14617 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14618 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14619 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14620 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14621 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14622 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14623 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14624 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14625 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14626 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14627 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14628 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14629 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14630 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14631 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14632 case X86ISD::VSHL: return "X86ISD::VSHL";
14633 case X86ISD::VSRL: return "X86ISD::VSRL";
14634 case X86ISD::VSRA: return "X86ISD::VSRA";
14635 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14636 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14637 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14638 case X86ISD::CMPP: return "X86ISD::CMPP";
14639 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14640 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14641 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14642 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14643 case X86ISD::ADD: return "X86ISD::ADD";
14644 case X86ISD::SUB: return "X86ISD::SUB";
14645 case X86ISD::ADC: return "X86ISD::ADC";
14646 case X86ISD::SBB: return "X86ISD::SBB";
14647 case X86ISD::SMUL: return "X86ISD::SMUL";
14648 case X86ISD::UMUL: return "X86ISD::UMUL";
14649 case X86ISD::INC: return "X86ISD::INC";
14650 case X86ISD::DEC: return "X86ISD::DEC";
14651 case X86ISD::OR: return "X86ISD::OR";
14652 case X86ISD::XOR: return "X86ISD::XOR";
14653 case X86ISD::AND: return "X86ISD::AND";
14654 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14655 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14656 case X86ISD::PTEST: return "X86ISD::PTEST";
14657 case X86ISD::TESTP: return "X86ISD::TESTP";
14658 case X86ISD::TESTM: return "X86ISD::TESTM";
14659 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14660 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14661 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14662 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14663 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14664 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14665 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14666 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14667 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14668 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14669 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14670 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14671 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14672 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14673 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14674 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14675 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14676 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14677 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14678 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14679 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14680 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14681 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14682 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14683 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14684 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14685 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14686 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14687 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14688 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14689 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14690 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14691 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14692 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14693 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14694 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14695 case X86ISD::SAHF: return "X86ISD::SAHF";
14696 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14697 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14698 case X86ISD::FMADD: return "X86ISD::FMADD";
14699 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14700 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14701 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14702 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14703 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14704 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14705 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14706 case X86ISD::XTEST: return "X86ISD::XTEST";
14710 // isLegalAddressingMode - Return true if the addressing mode represented
14711 // by AM is legal for this target, for a load/store of the specified type.
14712 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14714 // X86 supports extremely general addressing modes.
14715 CodeModel::Model M = getTargetMachine().getCodeModel();
14716 Reloc::Model R = getTargetMachine().getRelocationModel();
14718 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14719 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14724 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14726 // If a reference to this global requires an extra load, we can't fold it.
14727 if (isGlobalStubReference(GVFlags))
14730 // If BaseGV requires a register for the PIC base, we cannot also have a
14731 // BaseReg specified.
14732 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14735 // If lower 4G is not available, then we must use rip-relative addressing.
14736 if ((M != CodeModel::Small || R != Reloc::Static) &&
14737 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14741 switch (AM.Scale) {
14747 // These scales always work.
14752 // These scales are formed with basereg+scalereg. Only accept if there is
14757 default: // Other stuff never works.
14764 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14765 unsigned Bits = Ty->getScalarSizeInBits();
14767 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14768 // particularly cheaper than those without.
14772 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14773 // variable shifts just as cheap as scalar ones.
14774 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14777 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14778 // fully general vector.
14782 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14783 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14785 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14786 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14787 return NumBits1 > NumBits2;
14790 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14791 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14794 if (!isTypeLegal(EVT::getEVT(Ty1)))
14797 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14799 // Assuming the caller doesn't have a zeroext or signext return parameter,
14800 // truncation all the way down to i1 is valid.
14804 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14805 return isInt<32>(Imm);
14808 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14809 // Can also use sub to handle negated immediates.
14810 return isInt<32>(Imm);
14813 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14814 if (!VT1.isInteger() || !VT2.isInteger())
14816 unsigned NumBits1 = VT1.getSizeInBits();
14817 unsigned NumBits2 = VT2.getSizeInBits();
14818 return NumBits1 > NumBits2;
14821 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14822 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14823 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14826 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14827 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14828 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14831 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14832 EVT VT1 = Val.getValueType();
14833 if (isZExtFree(VT1, VT2))
14836 if (Val.getOpcode() != ISD::LOAD)
14839 if (!VT1.isSimple() || !VT1.isInteger() ||
14840 !VT2.isSimple() || !VT2.isInteger())
14843 switch (VT1.getSimpleVT().SimpleTy) {
14848 // X86 has 8, 16, and 32-bit zero-extending loads.
14856 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14857 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14860 VT = VT.getScalarType();
14862 if (!VT.isSimple())
14865 switch (VT.getSimpleVT().SimpleTy) {
14876 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14877 // i16 instructions are longer (0x66 prefix) and potentially slower.
14878 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14881 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14882 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14883 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14884 /// are assumed to be legal.
14886 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14888 if (!VT.isSimple())
14891 MVT SVT = VT.getSimpleVT();
14893 // Very little shuffling can be done for 64-bit vectors right now.
14894 if (VT.getSizeInBits() == 64)
14897 // FIXME: pshufb, blends, shifts.
14898 return (SVT.getVectorNumElements() == 2 ||
14899 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14900 isMOVLMask(M, SVT) ||
14901 isSHUFPMask(M, SVT) ||
14902 isPSHUFDMask(M, SVT) ||
14903 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14904 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14905 isPALIGNRMask(M, SVT, Subtarget) ||
14906 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14907 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14908 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14909 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14913 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14915 if (!VT.isSimple())
14918 MVT SVT = VT.getSimpleVT();
14919 unsigned NumElts = SVT.getVectorNumElements();
14920 // FIXME: This collection of masks seems suspect.
14923 if (NumElts == 4 && SVT.is128BitVector()) {
14924 return (isMOVLMask(Mask, SVT) ||
14925 isCommutedMOVLMask(Mask, SVT, true) ||
14926 isSHUFPMask(Mask, SVT) ||
14927 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14932 //===----------------------------------------------------------------------===//
14933 // X86 Scheduler Hooks
14934 //===----------------------------------------------------------------------===//
14936 /// Utility function to emit xbegin specifying the start of an RTM region.
14937 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14938 const TargetInstrInfo *TII) {
14939 DebugLoc DL = MI->getDebugLoc();
14941 const BasicBlock *BB = MBB->getBasicBlock();
14942 MachineFunction::iterator I = MBB;
14945 // For the v = xbegin(), we generate
14956 MachineBasicBlock *thisMBB = MBB;
14957 MachineFunction *MF = MBB->getParent();
14958 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14959 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14960 MF->insert(I, mainMBB);
14961 MF->insert(I, sinkMBB);
14963 // Transfer the remainder of BB and its successor edges to sinkMBB.
14964 sinkMBB->splice(sinkMBB->begin(), MBB,
14965 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14966 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14970 // # fallthrough to mainMBB
14971 // # abortion to sinkMBB
14972 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14973 thisMBB->addSuccessor(mainMBB);
14974 thisMBB->addSuccessor(sinkMBB);
14978 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14979 mainMBB->addSuccessor(sinkMBB);
14982 // EAX is live into the sinkMBB
14983 sinkMBB->addLiveIn(X86::EAX);
14984 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14985 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14988 MI->eraseFromParent();
14992 // Get CMPXCHG opcode for the specified data type.
14993 static unsigned getCmpXChgOpcode(EVT VT) {
14994 switch (VT.getSimpleVT().SimpleTy) {
14995 case MVT::i8: return X86::LCMPXCHG8;
14996 case MVT::i16: return X86::LCMPXCHG16;
14997 case MVT::i32: return X86::LCMPXCHG32;
14998 case MVT::i64: return X86::LCMPXCHG64;
15002 llvm_unreachable("Invalid operand size!");
15005 // Get LOAD opcode for the specified data type.
15006 static unsigned getLoadOpcode(EVT VT) {
15007 switch (VT.getSimpleVT().SimpleTy) {
15008 case MVT::i8: return X86::MOV8rm;
15009 case MVT::i16: return X86::MOV16rm;
15010 case MVT::i32: return X86::MOV32rm;
15011 case MVT::i64: return X86::MOV64rm;
15015 llvm_unreachable("Invalid operand size!");
15018 // Get opcode of the non-atomic one from the specified atomic instruction.
15019 static unsigned getNonAtomicOpcode(unsigned Opc) {
15021 case X86::ATOMAND8: return X86::AND8rr;
15022 case X86::ATOMAND16: return X86::AND16rr;
15023 case X86::ATOMAND32: return X86::AND32rr;
15024 case X86::ATOMAND64: return X86::AND64rr;
15025 case X86::ATOMOR8: return X86::OR8rr;
15026 case X86::ATOMOR16: return X86::OR16rr;
15027 case X86::ATOMOR32: return X86::OR32rr;
15028 case X86::ATOMOR64: return X86::OR64rr;
15029 case X86::ATOMXOR8: return X86::XOR8rr;
15030 case X86::ATOMXOR16: return X86::XOR16rr;
15031 case X86::ATOMXOR32: return X86::XOR32rr;
15032 case X86::ATOMXOR64: return X86::XOR64rr;
15034 llvm_unreachable("Unhandled atomic-load-op opcode!");
15037 // Get opcode of the non-atomic one from the specified atomic instruction with
15039 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15040 unsigned &ExtraOpc) {
15042 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15043 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15044 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15045 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15046 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15047 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15048 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15049 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15050 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15051 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15052 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15053 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15054 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15055 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15056 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15057 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15058 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15059 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15060 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15061 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15063 llvm_unreachable("Unhandled atomic-load-op opcode!");
15066 // Get opcode of the non-atomic one from the specified atomic instruction for
15067 // 64-bit data type on 32-bit target.
15068 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15070 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15071 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15072 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15073 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15074 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15075 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15076 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15077 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15078 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15079 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15081 llvm_unreachable("Unhandled atomic-load-op opcode!");
15084 // Get opcode of the non-atomic one from the specified atomic instruction for
15085 // 64-bit data type on 32-bit target with extra opcode.
15086 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15088 unsigned &ExtraOpc) {
15090 case X86::ATOMNAND6432:
15091 ExtraOpc = X86::NOT32r;
15092 HiOpc = X86::AND32rr;
15093 return X86::AND32rr;
15095 llvm_unreachable("Unhandled atomic-load-op opcode!");
15098 // Get pseudo CMOV opcode from the specified data type.
15099 static unsigned getPseudoCMOVOpc(EVT VT) {
15100 switch (VT.getSimpleVT().SimpleTy) {
15101 case MVT::i8: return X86::CMOV_GR8;
15102 case MVT::i16: return X86::CMOV_GR16;
15103 case MVT::i32: return X86::CMOV_GR32;
15107 llvm_unreachable("Unknown CMOV opcode!");
15110 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15111 // They will be translated into a spin-loop or compare-exchange loop from
15114 // dst = atomic-fetch-op MI.addr, MI.val
15120 // t1 = LOAD MI.addr
15122 // t4 = phi(t1, t3 / loop)
15123 // t2 = OP MI.val, t4
15125 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15131 MachineBasicBlock *
15132 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15133 MachineBasicBlock *MBB) const {
15134 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15135 DebugLoc DL = MI->getDebugLoc();
15137 MachineFunction *MF = MBB->getParent();
15138 MachineRegisterInfo &MRI = MF->getRegInfo();
15140 const BasicBlock *BB = MBB->getBasicBlock();
15141 MachineFunction::iterator I = MBB;
15144 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15145 "Unexpected number of operands");
15147 assert(MI->hasOneMemOperand() &&
15148 "Expected atomic-load-op to have one memoperand");
15150 // Memory Reference
15151 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15152 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15154 unsigned DstReg, SrcReg;
15155 unsigned MemOpndSlot;
15157 unsigned CurOp = 0;
15159 DstReg = MI->getOperand(CurOp++).getReg();
15160 MemOpndSlot = CurOp;
15161 CurOp += X86::AddrNumOperands;
15162 SrcReg = MI->getOperand(CurOp++).getReg();
15164 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15165 MVT::SimpleValueType VT = *RC->vt_begin();
15166 unsigned t1 = MRI.createVirtualRegister(RC);
15167 unsigned t2 = MRI.createVirtualRegister(RC);
15168 unsigned t3 = MRI.createVirtualRegister(RC);
15169 unsigned t4 = MRI.createVirtualRegister(RC);
15170 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15172 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15173 unsigned LOADOpc = getLoadOpcode(VT);
15175 // For the atomic load-arith operator, we generate
15178 // t1 = LOAD [MI.addr]
15180 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15181 // t1 = OP MI.val, EAX
15183 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15189 MachineBasicBlock *thisMBB = MBB;
15190 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15191 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15192 MF->insert(I, mainMBB);
15193 MF->insert(I, sinkMBB);
15195 MachineInstrBuilder MIB;
15197 // Transfer the remainder of BB and its successor edges to sinkMBB.
15198 sinkMBB->splice(sinkMBB->begin(), MBB,
15199 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15200 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15203 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15204 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15205 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15207 NewMO.setIsKill(false);
15208 MIB.addOperand(NewMO);
15210 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15211 unsigned flags = (*MMOI)->getFlags();
15212 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15213 MachineMemOperand *MMO =
15214 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15215 (*MMOI)->getSize(),
15216 (*MMOI)->getBaseAlignment(),
15217 (*MMOI)->getTBAAInfo(),
15218 (*MMOI)->getRanges());
15219 MIB.addMemOperand(MMO);
15222 thisMBB->addSuccessor(mainMBB);
15225 MachineBasicBlock *origMainMBB = mainMBB;
15228 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15229 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15231 unsigned Opc = MI->getOpcode();
15234 llvm_unreachable("Unhandled atomic-load-op opcode!");
15235 case X86::ATOMAND8:
15236 case X86::ATOMAND16:
15237 case X86::ATOMAND32:
15238 case X86::ATOMAND64:
15240 case X86::ATOMOR16:
15241 case X86::ATOMOR32:
15242 case X86::ATOMOR64:
15243 case X86::ATOMXOR8:
15244 case X86::ATOMXOR16:
15245 case X86::ATOMXOR32:
15246 case X86::ATOMXOR64: {
15247 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15248 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15252 case X86::ATOMNAND8:
15253 case X86::ATOMNAND16:
15254 case X86::ATOMNAND32:
15255 case X86::ATOMNAND64: {
15256 unsigned Tmp = MRI.createVirtualRegister(RC);
15258 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15259 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15261 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15264 case X86::ATOMMAX8:
15265 case X86::ATOMMAX16:
15266 case X86::ATOMMAX32:
15267 case X86::ATOMMAX64:
15268 case X86::ATOMMIN8:
15269 case X86::ATOMMIN16:
15270 case X86::ATOMMIN32:
15271 case X86::ATOMMIN64:
15272 case X86::ATOMUMAX8:
15273 case X86::ATOMUMAX16:
15274 case X86::ATOMUMAX32:
15275 case X86::ATOMUMAX64:
15276 case X86::ATOMUMIN8:
15277 case X86::ATOMUMIN16:
15278 case X86::ATOMUMIN32:
15279 case X86::ATOMUMIN64: {
15281 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15283 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15287 if (Subtarget->hasCMov()) {
15288 if (VT != MVT::i8) {
15290 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15294 // Promote i8 to i32 to use CMOV32
15295 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15296 const TargetRegisterClass *RC32 =
15297 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15298 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15299 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15300 unsigned Tmp = MRI.createVirtualRegister(RC32);
15302 unsigned Undef = MRI.createVirtualRegister(RC32);
15303 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15305 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15308 .addImm(X86::sub_8bit);
15309 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15312 .addImm(X86::sub_8bit);
15314 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15318 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15319 .addReg(Tmp, 0, X86::sub_8bit);
15322 // Use pseudo select and lower them.
15323 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15324 "Invalid atomic-load-op transformation!");
15325 unsigned SelOpc = getPseudoCMOVOpc(VT);
15326 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15327 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15328 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15329 .addReg(SrcReg).addReg(t4)
15331 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15332 // Replace the original PHI node as mainMBB is changed after CMOV
15334 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15335 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15336 Phi->eraseFromParent();
15342 // Copy PhyReg back from virtual register.
15343 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15346 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15347 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15348 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15350 NewMO.setIsKill(false);
15351 MIB.addOperand(NewMO);
15354 MIB.setMemRefs(MMOBegin, MMOEnd);
15356 // Copy PhyReg back to virtual register.
15357 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15360 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15362 mainMBB->addSuccessor(origMainMBB);
15363 mainMBB->addSuccessor(sinkMBB);
15366 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15367 TII->get(TargetOpcode::COPY), DstReg)
15370 MI->eraseFromParent();
15374 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15375 // instructions. They will be translated into a spin-loop or compare-exchange
15379 // dst = atomic-fetch-op MI.addr, MI.val
15385 // t1L = LOAD [MI.addr + 0]
15386 // t1H = LOAD [MI.addr + 4]
15388 // t4L = phi(t1L, t3L / loop)
15389 // t4H = phi(t1H, t3H / loop)
15390 // t2L = OP MI.val.lo, t4L
15391 // t2H = OP MI.val.hi, t4H
15396 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15404 MachineBasicBlock *
15405 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15406 MachineBasicBlock *MBB) const {
15407 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15408 DebugLoc DL = MI->getDebugLoc();
15410 MachineFunction *MF = MBB->getParent();
15411 MachineRegisterInfo &MRI = MF->getRegInfo();
15413 const BasicBlock *BB = MBB->getBasicBlock();
15414 MachineFunction::iterator I = MBB;
15417 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15418 "Unexpected number of operands");
15420 assert(MI->hasOneMemOperand() &&
15421 "Expected atomic-load-op32 to have one memoperand");
15423 // Memory Reference
15424 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15425 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15427 unsigned DstLoReg, DstHiReg;
15428 unsigned SrcLoReg, SrcHiReg;
15429 unsigned MemOpndSlot;
15431 unsigned CurOp = 0;
15433 DstLoReg = MI->getOperand(CurOp++).getReg();
15434 DstHiReg = MI->getOperand(CurOp++).getReg();
15435 MemOpndSlot = CurOp;
15436 CurOp += X86::AddrNumOperands;
15437 SrcLoReg = MI->getOperand(CurOp++).getReg();
15438 SrcHiReg = MI->getOperand(CurOp++).getReg();
15440 const TargetRegisterClass *RC = &X86::GR32RegClass;
15441 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15443 unsigned t1L = MRI.createVirtualRegister(RC);
15444 unsigned t1H = MRI.createVirtualRegister(RC);
15445 unsigned t2L = MRI.createVirtualRegister(RC);
15446 unsigned t2H = MRI.createVirtualRegister(RC);
15447 unsigned t3L = MRI.createVirtualRegister(RC);
15448 unsigned t3H = MRI.createVirtualRegister(RC);
15449 unsigned t4L = MRI.createVirtualRegister(RC);
15450 unsigned t4H = MRI.createVirtualRegister(RC);
15452 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15453 unsigned LOADOpc = X86::MOV32rm;
15455 // For the atomic load-arith operator, we generate
15458 // t1L = LOAD [MI.addr + 0]
15459 // t1H = LOAD [MI.addr + 4]
15461 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15462 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15463 // t2L = OP MI.val.lo, t4L
15464 // t2H = OP MI.val.hi, t4H
15467 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15475 MachineBasicBlock *thisMBB = MBB;
15476 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15477 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15478 MF->insert(I, mainMBB);
15479 MF->insert(I, sinkMBB);
15481 MachineInstrBuilder MIB;
15483 // Transfer the remainder of BB and its successor edges to sinkMBB.
15484 sinkMBB->splice(sinkMBB->begin(), MBB,
15485 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15486 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15490 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15491 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15492 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15494 NewMO.setIsKill(false);
15495 MIB.addOperand(NewMO);
15497 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15498 unsigned flags = (*MMOI)->getFlags();
15499 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15500 MachineMemOperand *MMO =
15501 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15502 (*MMOI)->getSize(),
15503 (*MMOI)->getBaseAlignment(),
15504 (*MMOI)->getTBAAInfo(),
15505 (*MMOI)->getRanges());
15506 MIB.addMemOperand(MMO);
15508 MachineInstr *LowMI = MIB;
15511 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15512 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15513 if (i == X86::AddrDisp) {
15514 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15516 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15518 NewMO.setIsKill(false);
15519 MIB.addOperand(NewMO);
15522 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15524 thisMBB->addSuccessor(mainMBB);
15527 MachineBasicBlock *origMainMBB = mainMBB;
15530 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15531 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15532 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15533 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15535 unsigned Opc = MI->getOpcode();
15538 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15539 case X86::ATOMAND6432:
15540 case X86::ATOMOR6432:
15541 case X86::ATOMXOR6432:
15542 case X86::ATOMADD6432:
15543 case X86::ATOMSUB6432: {
15545 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15546 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15548 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15552 case X86::ATOMNAND6432: {
15553 unsigned HiOpc, NOTOpc;
15554 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15555 unsigned TmpL = MRI.createVirtualRegister(RC);
15556 unsigned TmpH = MRI.createVirtualRegister(RC);
15557 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15559 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15561 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15562 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15565 case X86::ATOMMAX6432:
15566 case X86::ATOMMIN6432:
15567 case X86::ATOMUMAX6432:
15568 case X86::ATOMUMIN6432: {
15570 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15571 unsigned cL = MRI.createVirtualRegister(RC8);
15572 unsigned cH = MRI.createVirtualRegister(RC8);
15573 unsigned cL32 = MRI.createVirtualRegister(RC);
15574 unsigned cH32 = MRI.createVirtualRegister(RC);
15575 unsigned cc = MRI.createVirtualRegister(RC);
15576 // cl := cmp src_lo, lo
15577 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15578 .addReg(SrcLoReg).addReg(t4L);
15579 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15580 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15581 // ch := cmp src_hi, hi
15582 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15583 .addReg(SrcHiReg).addReg(t4H);
15584 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15585 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15586 // cc := if (src_hi == hi) ? cl : ch;
15587 if (Subtarget->hasCMov()) {
15588 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15589 .addReg(cH32).addReg(cL32);
15591 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15592 .addReg(cH32).addReg(cL32)
15593 .addImm(X86::COND_E);
15594 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15596 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15597 if (Subtarget->hasCMov()) {
15598 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15599 .addReg(SrcLoReg).addReg(t4L);
15600 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15601 .addReg(SrcHiReg).addReg(t4H);
15603 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15604 .addReg(SrcLoReg).addReg(t4L)
15605 .addImm(X86::COND_NE);
15606 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15607 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15608 // 2nd CMOV lowering.
15609 mainMBB->addLiveIn(X86::EFLAGS);
15610 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15611 .addReg(SrcHiReg).addReg(t4H)
15612 .addImm(X86::COND_NE);
15613 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15614 // Replace the original PHI node as mainMBB is changed after CMOV
15616 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15617 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15618 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15619 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15620 PhiL->eraseFromParent();
15621 PhiH->eraseFromParent();
15625 case X86::ATOMSWAP6432: {
15627 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15628 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15629 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15634 // Copy EDX:EAX back from HiReg:LoReg
15635 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15636 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15637 // Copy ECX:EBX from t1H:t1L
15638 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15639 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15641 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15642 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15643 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15645 NewMO.setIsKill(false);
15646 MIB.addOperand(NewMO);
15648 MIB.setMemRefs(MMOBegin, MMOEnd);
15650 // Copy EDX:EAX back to t3H:t3L
15651 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15652 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15654 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15656 mainMBB->addSuccessor(origMainMBB);
15657 mainMBB->addSuccessor(sinkMBB);
15660 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15661 TII->get(TargetOpcode::COPY), DstLoReg)
15663 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15664 TII->get(TargetOpcode::COPY), DstHiReg)
15667 MI->eraseFromParent();
15671 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15672 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15673 // in the .td file.
15674 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15675 const TargetInstrInfo *TII) {
15677 switch (MI->getOpcode()) {
15678 default: llvm_unreachable("illegal opcode!");
15679 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15680 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15681 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15682 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15683 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15684 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15685 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15686 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15689 DebugLoc dl = MI->getDebugLoc();
15690 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15692 unsigned NumArgs = MI->getNumOperands();
15693 for (unsigned i = 1; i < NumArgs; ++i) {
15694 MachineOperand &Op = MI->getOperand(i);
15695 if (!(Op.isReg() && Op.isImplicit()))
15696 MIB.addOperand(Op);
15698 if (MI->hasOneMemOperand())
15699 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15701 BuildMI(*BB, MI, dl,
15702 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15703 .addReg(X86::XMM0);
15705 MI->eraseFromParent();
15709 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15710 // defs in an instruction pattern
15711 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15712 const TargetInstrInfo *TII) {
15714 switch (MI->getOpcode()) {
15715 default: llvm_unreachable("illegal opcode!");
15716 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15717 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15718 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15719 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15720 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15721 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15722 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15723 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15726 DebugLoc dl = MI->getDebugLoc();
15727 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15729 unsigned NumArgs = MI->getNumOperands(); // remove the results
15730 for (unsigned i = 1; i < NumArgs; ++i) {
15731 MachineOperand &Op = MI->getOperand(i);
15732 if (!(Op.isReg() && Op.isImplicit()))
15733 MIB.addOperand(Op);
15735 if (MI->hasOneMemOperand())
15736 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15738 BuildMI(*BB, MI, dl,
15739 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15742 MI->eraseFromParent();
15746 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15747 const TargetInstrInfo *TII,
15748 const X86Subtarget* Subtarget) {
15749 DebugLoc dl = MI->getDebugLoc();
15751 // Address into RAX/EAX, other two args into ECX, EDX.
15752 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15753 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15754 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15755 for (int i = 0; i < X86::AddrNumOperands; ++i)
15756 MIB.addOperand(MI->getOperand(i));
15758 unsigned ValOps = X86::AddrNumOperands;
15759 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15760 .addReg(MI->getOperand(ValOps).getReg());
15761 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15762 .addReg(MI->getOperand(ValOps+1).getReg());
15764 // The instruction doesn't actually take any operands though.
15765 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15767 MI->eraseFromParent(); // The pseudo is gone now.
15771 MachineBasicBlock *
15772 X86TargetLowering::EmitVAARG64WithCustomInserter(
15774 MachineBasicBlock *MBB) const {
15775 // Emit va_arg instruction on X86-64.
15777 // Operands to this pseudo-instruction:
15778 // 0 ) Output : destination address (reg)
15779 // 1-5) Input : va_list address (addr, i64mem)
15780 // 6 ) ArgSize : Size (in bytes) of vararg type
15781 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15782 // 8 ) Align : Alignment of type
15783 // 9 ) EFLAGS (implicit-def)
15785 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15786 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15788 unsigned DestReg = MI->getOperand(0).getReg();
15789 MachineOperand &Base = MI->getOperand(1);
15790 MachineOperand &Scale = MI->getOperand(2);
15791 MachineOperand &Index = MI->getOperand(3);
15792 MachineOperand &Disp = MI->getOperand(4);
15793 MachineOperand &Segment = MI->getOperand(5);
15794 unsigned ArgSize = MI->getOperand(6).getImm();
15795 unsigned ArgMode = MI->getOperand(7).getImm();
15796 unsigned Align = MI->getOperand(8).getImm();
15798 // Memory Reference
15799 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15800 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15801 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15803 // Machine Information
15804 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15805 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15806 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15807 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15808 DebugLoc DL = MI->getDebugLoc();
15810 // struct va_list {
15813 // i64 overflow_area (address)
15814 // i64 reg_save_area (address)
15816 // sizeof(va_list) = 24
15817 // alignment(va_list) = 8
15819 unsigned TotalNumIntRegs = 6;
15820 unsigned TotalNumXMMRegs = 8;
15821 bool UseGPOffset = (ArgMode == 1);
15822 bool UseFPOffset = (ArgMode == 2);
15823 unsigned MaxOffset = TotalNumIntRegs * 8 +
15824 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15826 /* Align ArgSize to a multiple of 8 */
15827 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15828 bool NeedsAlign = (Align > 8);
15830 MachineBasicBlock *thisMBB = MBB;
15831 MachineBasicBlock *overflowMBB;
15832 MachineBasicBlock *offsetMBB;
15833 MachineBasicBlock *endMBB;
15835 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15836 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15837 unsigned OffsetReg = 0;
15839 if (!UseGPOffset && !UseFPOffset) {
15840 // If we only pull from the overflow region, we don't create a branch.
15841 // We don't need to alter control flow.
15842 OffsetDestReg = 0; // unused
15843 OverflowDestReg = DestReg;
15845 offsetMBB = nullptr;
15846 overflowMBB = thisMBB;
15849 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15850 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15851 // If not, pull from overflow_area. (branch to overflowMBB)
15856 // offsetMBB overflowMBB
15861 // Registers for the PHI in endMBB
15862 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15863 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15865 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15866 MachineFunction *MF = MBB->getParent();
15867 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15868 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15869 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15871 MachineFunction::iterator MBBIter = MBB;
15874 // Insert the new basic blocks
15875 MF->insert(MBBIter, offsetMBB);
15876 MF->insert(MBBIter, overflowMBB);
15877 MF->insert(MBBIter, endMBB);
15879 // Transfer the remainder of MBB and its successor edges to endMBB.
15880 endMBB->splice(endMBB->begin(), thisMBB,
15881 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15882 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15884 // Make offsetMBB and overflowMBB successors of thisMBB
15885 thisMBB->addSuccessor(offsetMBB);
15886 thisMBB->addSuccessor(overflowMBB);
15888 // endMBB is a successor of both offsetMBB and overflowMBB
15889 offsetMBB->addSuccessor(endMBB);
15890 overflowMBB->addSuccessor(endMBB);
15892 // Load the offset value into a register
15893 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15894 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15898 .addDisp(Disp, UseFPOffset ? 4 : 0)
15899 .addOperand(Segment)
15900 .setMemRefs(MMOBegin, MMOEnd);
15902 // Check if there is enough room left to pull this argument.
15903 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15905 .addImm(MaxOffset + 8 - ArgSizeA8);
15907 // Branch to "overflowMBB" if offset >= max
15908 // Fall through to "offsetMBB" otherwise
15909 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15910 .addMBB(overflowMBB);
15913 // In offsetMBB, emit code to use the reg_save_area.
15915 assert(OffsetReg != 0);
15917 // Read the reg_save_area address.
15918 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15919 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15924 .addOperand(Segment)
15925 .setMemRefs(MMOBegin, MMOEnd);
15927 // Zero-extend the offset
15928 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15929 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15932 .addImm(X86::sub_32bit);
15934 // Add the offset to the reg_save_area to get the final address.
15935 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15936 .addReg(OffsetReg64)
15937 .addReg(RegSaveReg);
15939 // Compute the offset for the next argument
15940 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15941 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15943 .addImm(UseFPOffset ? 16 : 8);
15945 // Store it back into the va_list.
15946 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15950 .addDisp(Disp, UseFPOffset ? 4 : 0)
15951 .addOperand(Segment)
15952 .addReg(NextOffsetReg)
15953 .setMemRefs(MMOBegin, MMOEnd);
15956 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15961 // Emit code to use overflow area
15964 // Load the overflow_area address into a register.
15965 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15966 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15971 .addOperand(Segment)
15972 .setMemRefs(MMOBegin, MMOEnd);
15974 // If we need to align it, do so. Otherwise, just copy the address
15975 // to OverflowDestReg.
15977 // Align the overflow address
15978 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15979 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15981 // aligned_addr = (addr + (align-1)) & ~(align-1)
15982 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15983 .addReg(OverflowAddrReg)
15986 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15988 .addImm(~(uint64_t)(Align-1));
15990 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15991 .addReg(OverflowAddrReg);
15994 // Compute the next overflow address after this argument.
15995 // (the overflow address should be kept 8-byte aligned)
15996 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15997 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15998 .addReg(OverflowDestReg)
15999 .addImm(ArgSizeA8);
16001 // Store the new overflow address.
16002 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16007 .addOperand(Segment)
16008 .addReg(NextAddrReg)
16009 .setMemRefs(MMOBegin, MMOEnd);
16011 // If we branched, emit the PHI to the front of endMBB.
16013 BuildMI(*endMBB, endMBB->begin(), DL,
16014 TII->get(X86::PHI), DestReg)
16015 .addReg(OffsetDestReg).addMBB(offsetMBB)
16016 .addReg(OverflowDestReg).addMBB(overflowMBB);
16019 // Erase the pseudo instruction
16020 MI->eraseFromParent();
16025 MachineBasicBlock *
16026 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16028 MachineBasicBlock *MBB) const {
16029 // Emit code to save XMM registers to the stack. The ABI says that the
16030 // number of registers to save is given in %al, so it's theoretically
16031 // possible to do an indirect jump trick to avoid saving all of them,
16032 // however this code takes a simpler approach and just executes all
16033 // of the stores if %al is non-zero. It's less code, and it's probably
16034 // easier on the hardware branch predictor, and stores aren't all that
16035 // expensive anyway.
16037 // Create the new basic blocks. One block contains all the XMM stores,
16038 // and one block is the final destination regardless of whether any
16039 // stores were performed.
16040 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16041 MachineFunction *F = MBB->getParent();
16042 MachineFunction::iterator MBBIter = MBB;
16044 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16045 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16046 F->insert(MBBIter, XMMSaveMBB);
16047 F->insert(MBBIter, EndMBB);
16049 // Transfer the remainder of MBB and its successor edges to EndMBB.
16050 EndMBB->splice(EndMBB->begin(), MBB,
16051 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16052 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16054 // The original block will now fall through to the XMM save block.
16055 MBB->addSuccessor(XMMSaveMBB);
16056 // The XMMSaveMBB will fall through to the end block.
16057 XMMSaveMBB->addSuccessor(EndMBB);
16059 // Now add the instructions.
16060 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16061 DebugLoc DL = MI->getDebugLoc();
16063 unsigned CountReg = MI->getOperand(0).getReg();
16064 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16065 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16067 if (!Subtarget->isTargetWin64()) {
16068 // If %al is 0, branch around the XMM save block.
16069 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16070 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16071 MBB->addSuccessor(EndMBB);
16074 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16075 // that was just emitted, but clearly shouldn't be "saved".
16076 assert((MI->getNumOperands() <= 3 ||
16077 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16078 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16079 && "Expected last argument to be EFLAGS");
16080 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16081 // In the XMM save block, save all the XMM argument registers.
16082 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16083 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16084 MachineMemOperand *MMO =
16085 F->getMachineMemOperand(
16086 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16087 MachineMemOperand::MOStore,
16088 /*Size=*/16, /*Align=*/16);
16089 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16090 .addFrameIndex(RegSaveFrameIndex)
16091 .addImm(/*Scale=*/1)
16092 .addReg(/*IndexReg=*/0)
16093 .addImm(/*Disp=*/Offset)
16094 .addReg(/*Segment=*/0)
16095 .addReg(MI->getOperand(i).getReg())
16096 .addMemOperand(MMO);
16099 MI->eraseFromParent(); // The pseudo instruction is gone now.
16104 // The EFLAGS operand of SelectItr might be missing a kill marker
16105 // because there were multiple uses of EFLAGS, and ISel didn't know
16106 // which to mark. Figure out whether SelectItr should have had a
16107 // kill marker, and set it if it should. Returns the correct kill
16109 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16110 MachineBasicBlock* BB,
16111 const TargetRegisterInfo* TRI) {
16112 // Scan forward through BB for a use/def of EFLAGS.
16113 MachineBasicBlock::iterator miI(std::next(SelectItr));
16114 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16115 const MachineInstr& mi = *miI;
16116 if (mi.readsRegister(X86::EFLAGS))
16118 if (mi.definesRegister(X86::EFLAGS))
16119 break; // Should have kill-flag - update below.
16122 // If we hit the end of the block, check whether EFLAGS is live into a
16124 if (miI == BB->end()) {
16125 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16126 sEnd = BB->succ_end();
16127 sItr != sEnd; ++sItr) {
16128 MachineBasicBlock* succ = *sItr;
16129 if (succ->isLiveIn(X86::EFLAGS))
16134 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16135 // out. SelectMI should have a kill flag on EFLAGS.
16136 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16140 MachineBasicBlock *
16141 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16142 MachineBasicBlock *BB) const {
16143 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16144 DebugLoc DL = MI->getDebugLoc();
16146 // To "insert" a SELECT_CC instruction, we actually have to insert the
16147 // diamond control-flow pattern. The incoming instruction knows the
16148 // destination vreg to set, the condition code register to branch on, the
16149 // true/false values to select between, and a branch opcode to use.
16150 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16151 MachineFunction::iterator It = BB;
16157 // cmpTY ccX, r1, r2
16159 // fallthrough --> copy0MBB
16160 MachineBasicBlock *thisMBB = BB;
16161 MachineFunction *F = BB->getParent();
16162 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16163 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16164 F->insert(It, copy0MBB);
16165 F->insert(It, sinkMBB);
16167 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16168 // live into the sink and copy blocks.
16169 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16170 if (!MI->killsRegister(X86::EFLAGS) &&
16171 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16172 copy0MBB->addLiveIn(X86::EFLAGS);
16173 sinkMBB->addLiveIn(X86::EFLAGS);
16176 // Transfer the remainder of BB and its successor edges to sinkMBB.
16177 sinkMBB->splice(sinkMBB->begin(), BB,
16178 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16179 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16181 // Add the true and fallthrough blocks as its successors.
16182 BB->addSuccessor(copy0MBB);
16183 BB->addSuccessor(sinkMBB);
16185 // Create the conditional branch instruction.
16187 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16188 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16191 // %FalseValue = ...
16192 // # fallthrough to sinkMBB
16193 copy0MBB->addSuccessor(sinkMBB);
16196 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16198 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16199 TII->get(X86::PHI), MI->getOperand(0).getReg())
16200 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16201 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16203 MI->eraseFromParent(); // The pseudo instruction is gone now.
16207 MachineBasicBlock *
16208 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16209 bool Is64Bit) const {
16210 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16211 DebugLoc DL = MI->getDebugLoc();
16212 MachineFunction *MF = BB->getParent();
16213 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16215 assert(MF->shouldSplitStack());
16217 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16218 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16221 // ... [Till the alloca]
16222 // If stacklet is not large enough, jump to mallocMBB
16225 // Allocate by subtracting from RSP
16226 // Jump to continueMBB
16229 // Allocate by call to runtime
16233 // [rest of original BB]
16236 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16237 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16238 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16240 MachineRegisterInfo &MRI = MF->getRegInfo();
16241 const TargetRegisterClass *AddrRegClass =
16242 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16244 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16245 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16246 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16247 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16248 sizeVReg = MI->getOperand(1).getReg(),
16249 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16251 MachineFunction::iterator MBBIter = BB;
16254 MF->insert(MBBIter, bumpMBB);
16255 MF->insert(MBBIter, mallocMBB);
16256 MF->insert(MBBIter, continueMBB);
16258 continueMBB->splice(continueMBB->begin(), BB,
16259 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16260 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16262 // Add code to the main basic block to check if the stack limit has been hit,
16263 // and if so, jump to mallocMBB otherwise to bumpMBB.
16264 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16265 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16266 .addReg(tmpSPVReg).addReg(sizeVReg);
16267 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16268 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16269 .addReg(SPLimitVReg);
16270 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16272 // bumpMBB simply decreases the stack pointer, since we know the current
16273 // stacklet has enough space.
16274 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16275 .addReg(SPLimitVReg);
16276 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16277 .addReg(SPLimitVReg);
16278 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16280 // Calls into a routine in libgcc to allocate more space from the heap.
16281 const uint32_t *RegMask =
16282 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16284 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16286 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16287 .addExternalSymbol("__morestack_allocate_stack_space")
16288 .addRegMask(RegMask)
16289 .addReg(X86::RDI, RegState::Implicit)
16290 .addReg(X86::RAX, RegState::ImplicitDefine);
16292 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16294 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16295 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16296 .addExternalSymbol("__morestack_allocate_stack_space")
16297 .addRegMask(RegMask)
16298 .addReg(X86::EAX, RegState::ImplicitDefine);
16302 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16305 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16306 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16307 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16309 // Set up the CFG correctly.
16310 BB->addSuccessor(bumpMBB);
16311 BB->addSuccessor(mallocMBB);
16312 mallocMBB->addSuccessor(continueMBB);
16313 bumpMBB->addSuccessor(continueMBB);
16315 // Take care of the PHI nodes.
16316 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16317 MI->getOperand(0).getReg())
16318 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16319 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16321 // Delete the original pseudo instruction.
16322 MI->eraseFromParent();
16325 return continueMBB;
16328 MachineBasicBlock *
16329 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16330 MachineBasicBlock *BB) const {
16331 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16332 DebugLoc DL = MI->getDebugLoc();
16334 assert(!Subtarget->isTargetMacho());
16336 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16337 // non-trivial part is impdef of ESP.
16339 if (Subtarget->isTargetWin64()) {
16340 if (Subtarget->isTargetCygMing()) {
16341 // ___chkstk(Mingw64):
16342 // Clobbers R10, R11, RAX and EFLAGS.
16344 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16345 .addExternalSymbol("___chkstk")
16346 .addReg(X86::RAX, RegState::Implicit)
16347 .addReg(X86::RSP, RegState::Implicit)
16348 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16349 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16350 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16352 // __chkstk(MSVCRT): does not update stack pointer.
16353 // Clobbers R10, R11 and EFLAGS.
16354 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16355 .addExternalSymbol("__chkstk")
16356 .addReg(X86::RAX, RegState::Implicit)
16357 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16358 // RAX has the offset to be subtracted from RSP.
16359 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16364 const char *StackProbeSymbol =
16365 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16367 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16368 .addExternalSymbol(StackProbeSymbol)
16369 .addReg(X86::EAX, RegState::Implicit)
16370 .addReg(X86::ESP, RegState::Implicit)
16371 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16372 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16373 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16376 MI->eraseFromParent(); // The pseudo instruction is gone now.
16380 MachineBasicBlock *
16381 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16382 MachineBasicBlock *BB) const {
16383 // This is pretty easy. We're taking the value that we received from
16384 // our load from the relocation, sticking it in either RDI (x86-64)
16385 // or EAX and doing an indirect call. The return value will then
16386 // be in the normal return register.
16387 const X86InstrInfo *TII
16388 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16389 DebugLoc DL = MI->getDebugLoc();
16390 MachineFunction *F = BB->getParent();
16392 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16393 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16395 // Get a register mask for the lowered call.
16396 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16397 // proper register mask.
16398 const uint32_t *RegMask =
16399 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16400 if (Subtarget->is64Bit()) {
16401 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16402 TII->get(X86::MOV64rm), X86::RDI)
16404 .addImm(0).addReg(0)
16405 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16406 MI->getOperand(3).getTargetFlags())
16408 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16409 addDirectMem(MIB, X86::RDI);
16410 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16411 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16412 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16413 TII->get(X86::MOV32rm), X86::EAX)
16415 .addImm(0).addReg(0)
16416 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16417 MI->getOperand(3).getTargetFlags())
16419 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16420 addDirectMem(MIB, X86::EAX);
16421 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16423 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16424 TII->get(X86::MOV32rm), X86::EAX)
16425 .addReg(TII->getGlobalBaseReg(F))
16426 .addImm(0).addReg(0)
16427 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16428 MI->getOperand(3).getTargetFlags())
16430 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16431 addDirectMem(MIB, X86::EAX);
16432 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16435 MI->eraseFromParent(); // The pseudo instruction is gone now.
16439 MachineBasicBlock *
16440 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16441 MachineBasicBlock *MBB) const {
16442 DebugLoc DL = MI->getDebugLoc();
16443 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16445 MachineFunction *MF = MBB->getParent();
16446 MachineRegisterInfo &MRI = MF->getRegInfo();
16448 const BasicBlock *BB = MBB->getBasicBlock();
16449 MachineFunction::iterator I = MBB;
16452 // Memory Reference
16453 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16454 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16457 unsigned MemOpndSlot = 0;
16459 unsigned CurOp = 0;
16461 DstReg = MI->getOperand(CurOp++).getReg();
16462 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16463 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16464 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16465 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16467 MemOpndSlot = CurOp;
16469 MVT PVT = getPointerTy();
16470 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16471 "Invalid Pointer Size!");
16473 // For v = setjmp(buf), we generate
16476 // buf[LabelOffset] = restoreMBB
16477 // SjLjSetup restoreMBB
16483 // v = phi(main, restore)
16488 MachineBasicBlock *thisMBB = MBB;
16489 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16490 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16491 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16492 MF->insert(I, mainMBB);
16493 MF->insert(I, sinkMBB);
16494 MF->push_back(restoreMBB);
16496 MachineInstrBuilder MIB;
16498 // Transfer the remainder of BB and its successor edges to sinkMBB.
16499 sinkMBB->splice(sinkMBB->begin(), MBB,
16500 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16501 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16504 unsigned PtrStoreOpc = 0;
16505 unsigned LabelReg = 0;
16506 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16507 Reloc::Model RM = getTargetMachine().getRelocationModel();
16508 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16509 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16511 // Prepare IP either in reg or imm.
16512 if (!UseImmLabel) {
16513 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16514 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16515 LabelReg = MRI.createVirtualRegister(PtrRC);
16516 if (Subtarget->is64Bit()) {
16517 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16521 .addMBB(restoreMBB)
16524 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16525 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16526 .addReg(XII->getGlobalBaseReg(MF))
16529 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16533 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16535 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16536 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16537 if (i == X86::AddrDisp)
16538 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16540 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16543 MIB.addReg(LabelReg);
16545 MIB.addMBB(restoreMBB);
16546 MIB.setMemRefs(MMOBegin, MMOEnd);
16548 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16549 .addMBB(restoreMBB);
16551 const X86RegisterInfo *RegInfo =
16552 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16553 MIB.addRegMask(RegInfo->getNoPreservedMask());
16554 thisMBB->addSuccessor(mainMBB);
16555 thisMBB->addSuccessor(restoreMBB);
16559 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16560 mainMBB->addSuccessor(sinkMBB);
16563 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16564 TII->get(X86::PHI), DstReg)
16565 .addReg(mainDstReg).addMBB(mainMBB)
16566 .addReg(restoreDstReg).addMBB(restoreMBB);
16569 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16570 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16571 restoreMBB->addSuccessor(sinkMBB);
16573 MI->eraseFromParent();
16577 MachineBasicBlock *
16578 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16579 MachineBasicBlock *MBB) const {
16580 DebugLoc DL = MI->getDebugLoc();
16581 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16583 MachineFunction *MF = MBB->getParent();
16584 MachineRegisterInfo &MRI = MF->getRegInfo();
16586 // Memory Reference
16587 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16588 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16590 MVT PVT = getPointerTy();
16591 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16592 "Invalid Pointer Size!");
16594 const TargetRegisterClass *RC =
16595 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16596 unsigned Tmp = MRI.createVirtualRegister(RC);
16597 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16598 const X86RegisterInfo *RegInfo =
16599 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16600 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16601 unsigned SP = RegInfo->getStackRegister();
16603 MachineInstrBuilder MIB;
16605 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16606 const int64_t SPOffset = 2 * PVT.getStoreSize();
16608 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16609 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16612 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16613 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16614 MIB.addOperand(MI->getOperand(i));
16615 MIB.setMemRefs(MMOBegin, MMOEnd);
16617 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16618 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16619 if (i == X86::AddrDisp)
16620 MIB.addDisp(MI->getOperand(i), LabelOffset);
16622 MIB.addOperand(MI->getOperand(i));
16624 MIB.setMemRefs(MMOBegin, MMOEnd);
16626 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16627 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16628 if (i == X86::AddrDisp)
16629 MIB.addDisp(MI->getOperand(i), SPOffset);
16631 MIB.addOperand(MI->getOperand(i));
16633 MIB.setMemRefs(MMOBegin, MMOEnd);
16635 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16637 MI->eraseFromParent();
16641 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16642 // accumulator loops. Writing back to the accumulator allows the coalescer
16643 // to remove extra copies in the loop.
16644 MachineBasicBlock *
16645 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16646 MachineBasicBlock *MBB) const {
16647 MachineOperand &AddendOp = MI->getOperand(3);
16649 // Bail out early if the addend isn't a register - we can't switch these.
16650 if (!AddendOp.isReg())
16653 MachineFunction &MF = *MBB->getParent();
16654 MachineRegisterInfo &MRI = MF.getRegInfo();
16656 // Check whether the addend is defined by a PHI:
16657 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16658 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16659 if (!AddendDef.isPHI())
16662 // Look for the following pattern:
16664 // %addend = phi [%entry, 0], [%loop, %result]
16666 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16670 // %addend = phi [%entry, 0], [%loop, %result]
16672 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16674 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16675 assert(AddendDef.getOperand(i).isReg());
16676 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16677 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16678 if (&PHISrcInst == MI) {
16679 // Found a matching instruction.
16680 unsigned NewFMAOpc = 0;
16681 switch (MI->getOpcode()) {
16682 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16683 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16684 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16685 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16686 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16687 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16688 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16689 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16690 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16691 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16692 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16693 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16694 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16695 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16696 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16697 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16698 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16699 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16700 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16701 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16702 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16703 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16704 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16705 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16706 default: llvm_unreachable("Unrecognized FMA variant.");
16709 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16710 MachineInstrBuilder MIB =
16711 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16712 .addOperand(MI->getOperand(0))
16713 .addOperand(MI->getOperand(3))
16714 .addOperand(MI->getOperand(2))
16715 .addOperand(MI->getOperand(1));
16716 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16717 MI->eraseFromParent();
16724 MachineBasicBlock *
16725 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16726 MachineBasicBlock *BB) const {
16727 switch (MI->getOpcode()) {
16728 default: llvm_unreachable("Unexpected instr type to insert");
16729 case X86::TAILJMPd64:
16730 case X86::TAILJMPr64:
16731 case X86::TAILJMPm64:
16732 llvm_unreachable("TAILJMP64 would not be touched here.");
16733 case X86::TCRETURNdi64:
16734 case X86::TCRETURNri64:
16735 case X86::TCRETURNmi64:
16737 case X86::WIN_ALLOCA:
16738 return EmitLoweredWinAlloca(MI, BB);
16739 case X86::SEG_ALLOCA_32:
16740 return EmitLoweredSegAlloca(MI, BB, false);
16741 case X86::SEG_ALLOCA_64:
16742 return EmitLoweredSegAlloca(MI, BB, true);
16743 case X86::TLSCall_32:
16744 case X86::TLSCall_64:
16745 return EmitLoweredTLSCall(MI, BB);
16746 case X86::CMOV_GR8:
16747 case X86::CMOV_FR32:
16748 case X86::CMOV_FR64:
16749 case X86::CMOV_V4F32:
16750 case X86::CMOV_V2F64:
16751 case X86::CMOV_V2I64:
16752 case X86::CMOV_V8F32:
16753 case X86::CMOV_V4F64:
16754 case X86::CMOV_V4I64:
16755 case X86::CMOV_V16F32:
16756 case X86::CMOV_V8F64:
16757 case X86::CMOV_V8I64:
16758 case X86::CMOV_GR16:
16759 case X86::CMOV_GR32:
16760 case X86::CMOV_RFP32:
16761 case X86::CMOV_RFP64:
16762 case X86::CMOV_RFP80:
16763 return EmitLoweredSelect(MI, BB);
16765 case X86::FP32_TO_INT16_IN_MEM:
16766 case X86::FP32_TO_INT32_IN_MEM:
16767 case X86::FP32_TO_INT64_IN_MEM:
16768 case X86::FP64_TO_INT16_IN_MEM:
16769 case X86::FP64_TO_INT32_IN_MEM:
16770 case X86::FP64_TO_INT64_IN_MEM:
16771 case X86::FP80_TO_INT16_IN_MEM:
16772 case X86::FP80_TO_INT32_IN_MEM:
16773 case X86::FP80_TO_INT64_IN_MEM: {
16774 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16775 DebugLoc DL = MI->getDebugLoc();
16777 // Change the floating point control register to use "round towards zero"
16778 // mode when truncating to an integer value.
16779 MachineFunction *F = BB->getParent();
16780 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16781 addFrameReference(BuildMI(*BB, MI, DL,
16782 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16784 // Load the old value of the high byte of the control word...
16786 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16787 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16790 // Set the high part to be round to zero...
16791 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16794 // Reload the modified control word now...
16795 addFrameReference(BuildMI(*BB, MI, DL,
16796 TII->get(X86::FLDCW16m)), CWFrameIdx);
16798 // Restore the memory image of control word to original value
16799 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16802 // Get the X86 opcode to use.
16804 switch (MI->getOpcode()) {
16805 default: llvm_unreachable("illegal opcode!");
16806 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16807 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16808 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16809 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16810 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16811 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16812 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16813 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16814 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16818 MachineOperand &Op = MI->getOperand(0);
16820 AM.BaseType = X86AddressMode::RegBase;
16821 AM.Base.Reg = Op.getReg();
16823 AM.BaseType = X86AddressMode::FrameIndexBase;
16824 AM.Base.FrameIndex = Op.getIndex();
16826 Op = MI->getOperand(1);
16828 AM.Scale = Op.getImm();
16829 Op = MI->getOperand(2);
16831 AM.IndexReg = Op.getImm();
16832 Op = MI->getOperand(3);
16833 if (Op.isGlobal()) {
16834 AM.GV = Op.getGlobal();
16836 AM.Disp = Op.getImm();
16838 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16839 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16841 // Reload the original control word now.
16842 addFrameReference(BuildMI(*BB, MI, DL,
16843 TII->get(X86::FLDCW16m)), CWFrameIdx);
16845 MI->eraseFromParent(); // The pseudo instruction is gone now.
16848 // String/text processing lowering.
16849 case X86::PCMPISTRM128REG:
16850 case X86::VPCMPISTRM128REG:
16851 case X86::PCMPISTRM128MEM:
16852 case X86::VPCMPISTRM128MEM:
16853 case X86::PCMPESTRM128REG:
16854 case X86::VPCMPESTRM128REG:
16855 case X86::PCMPESTRM128MEM:
16856 case X86::VPCMPESTRM128MEM:
16857 assert(Subtarget->hasSSE42() &&
16858 "Target must have SSE4.2 or AVX features enabled");
16859 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16861 // String/text processing lowering.
16862 case X86::PCMPISTRIREG:
16863 case X86::VPCMPISTRIREG:
16864 case X86::PCMPISTRIMEM:
16865 case X86::VPCMPISTRIMEM:
16866 case X86::PCMPESTRIREG:
16867 case X86::VPCMPESTRIREG:
16868 case X86::PCMPESTRIMEM:
16869 case X86::VPCMPESTRIMEM:
16870 assert(Subtarget->hasSSE42() &&
16871 "Target must have SSE4.2 or AVX features enabled");
16872 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16874 // Thread synchronization.
16876 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16880 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16882 // Atomic Lowering.
16883 case X86::ATOMAND8:
16884 case X86::ATOMAND16:
16885 case X86::ATOMAND32:
16886 case X86::ATOMAND64:
16889 case X86::ATOMOR16:
16890 case X86::ATOMOR32:
16891 case X86::ATOMOR64:
16893 case X86::ATOMXOR16:
16894 case X86::ATOMXOR8:
16895 case X86::ATOMXOR32:
16896 case X86::ATOMXOR64:
16898 case X86::ATOMNAND8:
16899 case X86::ATOMNAND16:
16900 case X86::ATOMNAND32:
16901 case X86::ATOMNAND64:
16903 case X86::ATOMMAX8:
16904 case X86::ATOMMAX16:
16905 case X86::ATOMMAX32:
16906 case X86::ATOMMAX64:
16908 case X86::ATOMMIN8:
16909 case X86::ATOMMIN16:
16910 case X86::ATOMMIN32:
16911 case X86::ATOMMIN64:
16913 case X86::ATOMUMAX8:
16914 case X86::ATOMUMAX16:
16915 case X86::ATOMUMAX32:
16916 case X86::ATOMUMAX64:
16918 case X86::ATOMUMIN8:
16919 case X86::ATOMUMIN16:
16920 case X86::ATOMUMIN32:
16921 case X86::ATOMUMIN64:
16922 return EmitAtomicLoadArith(MI, BB);
16924 // This group does 64-bit operations on a 32-bit host.
16925 case X86::ATOMAND6432:
16926 case X86::ATOMOR6432:
16927 case X86::ATOMXOR6432:
16928 case X86::ATOMNAND6432:
16929 case X86::ATOMADD6432:
16930 case X86::ATOMSUB6432:
16931 case X86::ATOMMAX6432:
16932 case X86::ATOMMIN6432:
16933 case X86::ATOMUMAX6432:
16934 case X86::ATOMUMIN6432:
16935 case X86::ATOMSWAP6432:
16936 return EmitAtomicLoadArith6432(MI, BB);
16938 case X86::VASTART_SAVE_XMM_REGS:
16939 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16941 case X86::VAARG_64:
16942 return EmitVAARG64WithCustomInserter(MI, BB);
16944 case X86::EH_SjLj_SetJmp32:
16945 case X86::EH_SjLj_SetJmp64:
16946 return emitEHSjLjSetJmp(MI, BB);
16948 case X86::EH_SjLj_LongJmp32:
16949 case X86::EH_SjLj_LongJmp64:
16950 return emitEHSjLjLongJmp(MI, BB);
16952 case TargetOpcode::STACKMAP:
16953 case TargetOpcode::PATCHPOINT:
16954 return emitPatchPoint(MI, BB);
16956 case X86::VFMADDPDr213r:
16957 case X86::VFMADDPSr213r:
16958 case X86::VFMADDSDr213r:
16959 case X86::VFMADDSSr213r:
16960 case X86::VFMSUBPDr213r:
16961 case X86::VFMSUBPSr213r:
16962 case X86::VFMSUBSDr213r:
16963 case X86::VFMSUBSSr213r:
16964 case X86::VFNMADDPDr213r:
16965 case X86::VFNMADDPSr213r:
16966 case X86::VFNMADDSDr213r:
16967 case X86::VFNMADDSSr213r:
16968 case X86::VFNMSUBPDr213r:
16969 case X86::VFNMSUBPSr213r:
16970 case X86::VFNMSUBSDr213r:
16971 case X86::VFNMSUBSSr213r:
16972 case X86::VFMADDPDr213rY:
16973 case X86::VFMADDPSr213rY:
16974 case X86::VFMSUBPDr213rY:
16975 case X86::VFMSUBPSr213rY:
16976 case X86::VFNMADDPDr213rY:
16977 case X86::VFNMADDPSr213rY:
16978 case X86::VFNMSUBPDr213rY:
16979 case X86::VFNMSUBPSr213rY:
16980 return emitFMA3Instr(MI, BB);
16984 //===----------------------------------------------------------------------===//
16985 // X86 Optimization Hooks
16986 //===----------------------------------------------------------------------===//
16988 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16991 const SelectionDAG &DAG,
16992 unsigned Depth) const {
16993 unsigned BitWidth = KnownZero.getBitWidth();
16994 unsigned Opc = Op.getOpcode();
16995 assert((Opc >= ISD::BUILTIN_OP_END ||
16996 Opc == ISD::INTRINSIC_WO_CHAIN ||
16997 Opc == ISD::INTRINSIC_W_CHAIN ||
16998 Opc == ISD::INTRINSIC_VOID) &&
16999 "Should use MaskedValueIsZero if you don't know whether Op"
17000 " is a target node!");
17002 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17016 // These nodes' second result is a boolean.
17017 if (Op.getResNo() == 0)
17020 case X86ISD::SETCC:
17021 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17023 case ISD::INTRINSIC_WO_CHAIN: {
17024 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17025 unsigned NumLoBits = 0;
17028 case Intrinsic::x86_sse_movmsk_ps:
17029 case Intrinsic::x86_avx_movmsk_ps_256:
17030 case Intrinsic::x86_sse2_movmsk_pd:
17031 case Intrinsic::x86_avx_movmsk_pd_256:
17032 case Intrinsic::x86_mmx_pmovmskb:
17033 case Intrinsic::x86_sse2_pmovmskb_128:
17034 case Intrinsic::x86_avx2_pmovmskb: {
17035 // High bits of movmskp{s|d}, pmovmskb are known zero.
17037 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17038 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17039 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17040 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17041 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17042 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17043 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17044 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17046 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17055 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17057 const SelectionDAG &,
17058 unsigned Depth) const {
17059 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17060 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17061 return Op.getValueType().getScalarType().getSizeInBits();
17067 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17068 /// node is a GlobalAddress + offset.
17069 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17070 const GlobalValue* &GA,
17071 int64_t &Offset) const {
17072 if (N->getOpcode() == X86ISD::Wrapper) {
17073 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17074 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17075 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17079 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17082 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17083 /// same as extracting the high 128-bit part of 256-bit vector and then
17084 /// inserting the result into the low part of a new 256-bit vector
17085 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17086 EVT VT = SVOp->getValueType(0);
17087 unsigned NumElems = VT.getVectorNumElements();
17089 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17090 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17091 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17092 SVOp->getMaskElt(j) >= 0)
17098 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17099 /// same as extracting the low 128-bit part of 256-bit vector and then
17100 /// inserting the result into the high part of a new 256-bit vector
17101 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17102 EVT VT = SVOp->getValueType(0);
17103 unsigned NumElems = VT.getVectorNumElements();
17105 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17106 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17107 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17108 SVOp->getMaskElt(j) >= 0)
17114 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17115 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17116 TargetLowering::DAGCombinerInfo &DCI,
17117 const X86Subtarget* Subtarget) {
17119 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17120 SDValue V1 = SVOp->getOperand(0);
17121 SDValue V2 = SVOp->getOperand(1);
17122 EVT VT = SVOp->getValueType(0);
17123 unsigned NumElems = VT.getVectorNumElements();
17125 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17126 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17130 // V UNDEF BUILD_VECTOR UNDEF
17132 // CONCAT_VECTOR CONCAT_VECTOR
17135 // RESULT: V + zero extended
17137 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17138 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17139 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17142 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17145 // To match the shuffle mask, the first half of the mask should
17146 // be exactly the first vector, and all the rest a splat with the
17147 // first element of the second one.
17148 for (unsigned i = 0; i != NumElems/2; ++i)
17149 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17150 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17153 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17154 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17155 if (Ld->hasNUsesOfValue(1, 0)) {
17156 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17157 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17159 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17161 Ld->getPointerInfo(),
17162 Ld->getAlignment(),
17163 false/*isVolatile*/, true/*ReadMem*/,
17164 false/*WriteMem*/);
17166 // Make sure the newly-created LOAD is in the same position as Ld in
17167 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17168 // and update uses of Ld's output chain to use the TokenFactor.
17169 if (Ld->hasAnyUseOfValue(1)) {
17170 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17171 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17172 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17173 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17174 SDValue(ResNode.getNode(), 1));
17177 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17181 // Emit a zeroed vector and insert the desired subvector on its
17183 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17184 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17185 return DCI.CombineTo(N, InsV);
17188 //===--------------------------------------------------------------------===//
17189 // Combine some shuffles into subvector extracts and inserts:
17192 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17193 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17194 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17195 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17196 return DCI.CombineTo(N, InsV);
17199 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17200 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17201 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17202 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17203 return DCI.CombineTo(N, InsV);
17209 /// PerformShuffleCombine - Performs several different shuffle combines.
17210 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17211 TargetLowering::DAGCombinerInfo &DCI,
17212 const X86Subtarget *Subtarget) {
17214 EVT VT = N->getValueType(0);
17216 // Don't create instructions with illegal types after legalize types has run.
17217 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17218 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17221 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17222 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17223 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17224 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17226 // Only handle 128 wide vector from here on.
17227 if (!VT.is128BitVector())
17230 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17231 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17232 // consecutive, non-overlapping, and in the right order.
17233 SmallVector<SDValue, 16> Elts;
17234 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17235 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17237 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17240 /// PerformTruncateCombine - Converts truncate operation to
17241 /// a sequence of vector shuffle operations.
17242 /// It is possible when we truncate 256-bit vector to 128-bit vector
17243 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17244 TargetLowering::DAGCombinerInfo &DCI,
17245 const X86Subtarget *Subtarget) {
17249 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17250 /// specific shuffle of a load can be folded into a single element load.
17251 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17252 /// shuffles have been customed lowered so we need to handle those here.
17253 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17254 TargetLowering::DAGCombinerInfo &DCI) {
17255 if (DCI.isBeforeLegalizeOps())
17258 SDValue InVec = N->getOperand(0);
17259 SDValue EltNo = N->getOperand(1);
17261 if (!isa<ConstantSDNode>(EltNo))
17264 EVT VT = InVec.getValueType();
17266 bool HasShuffleIntoBitcast = false;
17267 if (InVec.getOpcode() == ISD::BITCAST) {
17268 // Don't duplicate a load with other uses.
17269 if (!InVec.hasOneUse())
17271 EVT BCVT = InVec.getOperand(0).getValueType();
17272 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17274 InVec = InVec.getOperand(0);
17275 HasShuffleIntoBitcast = true;
17278 if (!isTargetShuffle(InVec.getOpcode()))
17281 // Don't duplicate a load with other uses.
17282 if (!InVec.hasOneUse())
17285 SmallVector<int, 16> ShuffleMask;
17287 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17291 // Select the input vector, guarding against out of range extract vector.
17292 unsigned NumElems = VT.getVectorNumElements();
17293 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17294 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17295 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17296 : InVec.getOperand(1);
17298 // If inputs to shuffle are the same for both ops, then allow 2 uses
17299 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17301 if (LdNode.getOpcode() == ISD::BITCAST) {
17302 // Don't duplicate a load with other uses.
17303 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17306 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17307 LdNode = LdNode.getOperand(0);
17310 if (!ISD::isNormalLoad(LdNode.getNode()))
17313 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17315 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17318 if (HasShuffleIntoBitcast) {
17319 // If there's a bitcast before the shuffle, check if the load type and
17320 // alignment is valid.
17321 unsigned Align = LN0->getAlignment();
17322 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17323 unsigned NewAlign = TLI.getDataLayout()->
17324 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17326 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17330 // All checks match so transform back to vector_shuffle so that DAG combiner
17331 // can finish the job
17334 // Create shuffle node taking into account the case that its a unary shuffle
17335 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17336 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17337 InVec.getOperand(0), Shuffle,
17339 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17340 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17344 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17345 /// generation and convert it from being a bunch of shuffles and extracts
17346 /// to a simple store and scalar loads to extract the elements.
17347 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17348 TargetLowering::DAGCombinerInfo &DCI) {
17349 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17350 if (NewOp.getNode())
17353 SDValue InputVector = N->getOperand(0);
17355 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17356 // from mmx to v2i32 has a single usage.
17357 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17358 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17359 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17360 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17361 N->getValueType(0),
17362 InputVector.getNode()->getOperand(0));
17364 // Only operate on vectors of 4 elements, where the alternative shuffling
17365 // gets to be more expensive.
17366 if (InputVector.getValueType() != MVT::v4i32)
17369 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17370 // single use which is a sign-extend or zero-extend, and all elements are
17372 SmallVector<SDNode *, 4> Uses;
17373 unsigned ExtractedElements = 0;
17374 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17375 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17376 if (UI.getUse().getResNo() != InputVector.getResNo())
17379 SDNode *Extract = *UI;
17380 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17383 if (Extract->getValueType(0) != MVT::i32)
17385 if (!Extract->hasOneUse())
17387 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17388 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17390 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17393 // Record which element was extracted.
17394 ExtractedElements |=
17395 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17397 Uses.push_back(Extract);
17400 // If not all the elements were used, this may not be worthwhile.
17401 if (ExtractedElements != 15)
17404 // Ok, we've now decided to do the transformation.
17405 SDLoc dl(InputVector);
17407 // Store the value to a temporary stack slot.
17408 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17409 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17410 MachinePointerInfo(), false, false, 0);
17412 // Replace each use (extract) with a load of the appropriate element.
17413 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17414 UE = Uses.end(); UI != UE; ++UI) {
17415 SDNode *Extract = *UI;
17417 // cOMpute the element's address.
17418 SDValue Idx = Extract->getOperand(1);
17420 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17421 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17422 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17423 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17425 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17426 StackPtr, OffsetVal);
17428 // Load the scalar.
17429 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17430 ScalarAddr, MachinePointerInfo(),
17431 false, false, false, 0);
17433 // Replace the exact with the load.
17434 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17437 // The replacement was made in place; don't return anything.
17441 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17442 static std::pair<unsigned, bool>
17443 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17444 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17445 if (!VT.isVector())
17446 return std::make_pair(0, false);
17448 bool NeedSplit = false;
17449 switch (VT.getSimpleVT().SimpleTy) {
17450 default: return std::make_pair(0, false);
17454 if (!Subtarget->hasAVX2())
17456 if (!Subtarget->hasAVX())
17457 return std::make_pair(0, false);
17462 if (!Subtarget->hasSSE2())
17463 return std::make_pair(0, false);
17466 // SSE2 has only a small subset of the operations.
17467 bool hasUnsigned = Subtarget->hasSSE41() ||
17468 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17469 bool hasSigned = Subtarget->hasSSE41() ||
17470 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17472 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17475 // Check for x CC y ? x : y.
17476 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17477 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17482 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17485 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17488 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17491 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17493 // Check for x CC y ? y : x -- a min/max with reversed arms.
17494 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17495 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17500 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17503 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17506 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17509 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17513 return std::make_pair(Opc, NeedSplit);
17516 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17518 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17519 TargetLowering::DAGCombinerInfo &DCI,
17520 const X86Subtarget *Subtarget) {
17522 SDValue Cond = N->getOperand(0);
17523 // Get the LHS/RHS of the select.
17524 SDValue LHS = N->getOperand(1);
17525 SDValue RHS = N->getOperand(2);
17526 EVT VT = LHS.getValueType();
17527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17529 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17530 // instructions match the semantics of the common C idiom x<y?x:y but not
17531 // x<=y?x:y, because of how they handle negative zero (which can be
17532 // ignored in unsafe-math mode).
17533 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17534 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17535 (Subtarget->hasSSE2() ||
17536 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17537 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17539 unsigned Opcode = 0;
17540 // Check for x CC y ? x : y.
17541 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17542 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17546 // Converting this to a min would handle NaNs incorrectly, and swapping
17547 // the operands would cause it to handle comparisons between positive
17548 // and negative zero incorrectly.
17549 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17550 if (!DAG.getTarget().Options.UnsafeFPMath &&
17551 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17553 std::swap(LHS, RHS);
17555 Opcode = X86ISD::FMIN;
17558 // Converting this to a min would handle comparisons between positive
17559 // and negative zero incorrectly.
17560 if (!DAG.getTarget().Options.UnsafeFPMath &&
17561 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17563 Opcode = X86ISD::FMIN;
17566 // Converting this to a min would handle both negative zeros and NaNs
17567 // incorrectly, but we can swap the operands to fix both.
17568 std::swap(LHS, RHS);
17572 Opcode = X86ISD::FMIN;
17576 // Converting this to a max would handle comparisons between positive
17577 // and negative zero incorrectly.
17578 if (!DAG.getTarget().Options.UnsafeFPMath &&
17579 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17581 Opcode = X86ISD::FMAX;
17584 // Converting this to a max would handle NaNs incorrectly, and swapping
17585 // the operands would cause it to handle comparisons between positive
17586 // and negative zero incorrectly.
17587 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17588 if (!DAG.getTarget().Options.UnsafeFPMath &&
17589 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(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;
17605 // Check for x CC y ? y : x -- a min/max with reversed arms.
17606 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17607 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17611 // Converting this to a min would handle comparisons between positive
17612 // and negative zero incorrectly, and swapping the operands would
17613 // cause it to handle NaNs incorrectly.
17614 if (!DAG.getTarget().Options.UnsafeFPMath &&
17615 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17616 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17618 std::swap(LHS, RHS);
17620 Opcode = X86ISD::FMIN;
17623 // Converting this to a min would handle NaNs incorrectly.
17624 if (!DAG.getTarget().Options.UnsafeFPMath &&
17625 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17627 Opcode = X86ISD::FMIN;
17630 // Converting this to a min would handle both negative zeros and NaNs
17631 // incorrectly, but we can swap the operands to fix both.
17632 std::swap(LHS, RHS);
17636 Opcode = X86ISD::FMIN;
17640 // Converting this to a max would handle NaNs incorrectly.
17641 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17643 Opcode = X86ISD::FMAX;
17646 // Converting this to a max would handle comparisons between positive
17647 // and negative zero incorrectly, and swapping the operands would
17648 // cause it to handle NaNs incorrectly.
17649 if (!DAG.getTarget().Options.UnsafeFPMath &&
17650 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17651 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17653 std::swap(LHS, RHS);
17655 Opcode = X86ISD::FMAX;
17658 // Converting this to a max would handle both negative zeros and NaNs
17659 // incorrectly, but we can swap the operands to fix both.
17660 std::swap(LHS, RHS);
17664 Opcode = X86ISD::FMAX;
17670 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17673 EVT CondVT = Cond.getValueType();
17674 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17675 CondVT.getVectorElementType() == MVT::i1) {
17676 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17677 // lowering on AVX-512. In this case we convert it to
17678 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17679 // The same situation for all 128 and 256-bit vectors of i8 and i16
17680 EVT OpVT = LHS.getValueType();
17681 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17682 (OpVT.getVectorElementType() == MVT::i8 ||
17683 OpVT.getVectorElementType() == MVT::i16)) {
17684 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17685 DCI.AddToWorklist(Cond.getNode());
17686 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17689 // If this is a select between two integer constants, try to do some
17691 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17692 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17693 // Don't do this for crazy integer types.
17694 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17695 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17696 // so that TrueC (the true value) is larger than FalseC.
17697 bool NeedsCondInvert = false;
17699 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17700 // Efficiently invertible.
17701 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17702 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17703 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17704 NeedsCondInvert = true;
17705 std::swap(TrueC, FalseC);
17708 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17709 if (FalseC->getAPIntValue() == 0 &&
17710 TrueC->getAPIntValue().isPowerOf2()) {
17711 if (NeedsCondInvert) // Invert the condition if needed.
17712 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17713 DAG.getConstant(1, Cond.getValueType()));
17715 // Zero extend the condition if needed.
17716 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17718 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17719 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17720 DAG.getConstant(ShAmt, MVT::i8));
17723 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17724 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17725 if (NeedsCondInvert) // Invert the condition if needed.
17726 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17727 DAG.getConstant(1, Cond.getValueType()));
17729 // Zero extend the condition if needed.
17730 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17731 FalseC->getValueType(0), Cond);
17732 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17733 SDValue(FalseC, 0));
17736 // Optimize cases that will turn into an LEA instruction. This requires
17737 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17738 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17739 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17740 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17742 bool isFastMultiplier = false;
17744 switch ((unsigned char)Diff) {
17746 case 1: // result = add base, cond
17747 case 2: // result = lea base( , cond*2)
17748 case 3: // result = lea base(cond, cond*2)
17749 case 4: // result = lea base( , cond*4)
17750 case 5: // result = lea base(cond, cond*4)
17751 case 8: // result = lea base( , cond*8)
17752 case 9: // result = lea base(cond, cond*8)
17753 isFastMultiplier = true;
17758 if (isFastMultiplier) {
17759 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17760 if (NeedsCondInvert) // Invert the condition if needed.
17761 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17762 DAG.getConstant(1, Cond.getValueType()));
17764 // Zero extend the condition if needed.
17765 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17767 // Scale the condition by the difference.
17769 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17770 DAG.getConstant(Diff, Cond.getValueType()));
17772 // Add the base if non-zero.
17773 if (FalseC->getAPIntValue() != 0)
17774 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17775 SDValue(FalseC, 0));
17782 // Canonicalize max and min:
17783 // (x > y) ? x : y -> (x >= y) ? x : y
17784 // (x < y) ? x : y -> (x <= y) ? x : y
17785 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17786 // the need for an extra compare
17787 // against zero. e.g.
17788 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17790 // testl %edi, %edi
17792 // cmovgl %edi, %eax
17796 // cmovsl %eax, %edi
17797 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17798 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17799 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17800 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17805 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17806 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17807 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17808 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17813 // Early exit check
17814 if (!TLI.isTypeLegal(VT))
17817 // Match VSELECTs into subs with unsigned saturation.
17818 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17819 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17820 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17821 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17822 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17824 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17825 // left side invert the predicate to simplify logic below.
17827 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17829 CC = ISD::getSetCCInverse(CC, true);
17830 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17834 if (Other.getNode() && Other->getNumOperands() == 2 &&
17835 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17836 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17837 SDValue CondRHS = Cond->getOperand(1);
17839 // Look for a general sub with unsigned saturation first.
17840 // x >= y ? x-y : 0 --> subus x, y
17841 // x > y ? x-y : 0 --> subus x, y
17842 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17843 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17844 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17846 // If the RHS is a constant we have to reverse the const canonicalization.
17847 // x > C-1 ? x+-C : 0 --> subus x, C
17848 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17849 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17850 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17851 if (CondRHS.getConstantOperandVal(0) == -A-1)
17852 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17853 DAG.getConstant(-A, VT));
17856 // Another special case: If C was a sign bit, the sub has been
17857 // canonicalized into a xor.
17858 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17859 // it's safe to decanonicalize the xor?
17860 // x s< 0 ? x^C : 0 --> subus x, C
17861 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17862 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17863 isSplatVector(OpRHS.getNode())) {
17864 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17866 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17871 // Try to match a min/max vector operation.
17872 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17873 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17874 unsigned Opc = ret.first;
17875 bool NeedSplit = ret.second;
17877 if (Opc && NeedSplit) {
17878 unsigned NumElems = VT.getVectorNumElements();
17879 // Extract the LHS vectors
17880 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17881 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17883 // Extract the RHS vectors
17884 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17885 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17887 // Create min/max for each subvector
17888 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17889 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17891 // Merge the result
17892 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17894 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17897 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17898 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17899 // Check if SETCC has already been promoted
17900 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17901 // Check that condition value type matches vselect operand type
17904 assert(Cond.getValueType().isVector() &&
17905 "vector select expects a vector selector!");
17907 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17908 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17910 if (!TValIsAllOnes && !FValIsAllZeros) {
17911 // Try invert the condition if true value is not all 1s and false value
17913 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17914 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17916 if (TValIsAllZeros || FValIsAllOnes) {
17917 SDValue CC = Cond.getOperand(2);
17918 ISD::CondCode NewCC =
17919 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17920 Cond.getOperand(0).getValueType().isInteger());
17921 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17922 std::swap(LHS, RHS);
17923 TValIsAllOnes = FValIsAllOnes;
17924 FValIsAllZeros = TValIsAllZeros;
17928 if (TValIsAllOnes || FValIsAllZeros) {
17931 if (TValIsAllOnes && FValIsAllZeros)
17933 else if (TValIsAllOnes)
17934 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17935 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17936 else if (FValIsAllZeros)
17937 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17938 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17940 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17944 // Try to fold this VSELECT into a MOVSS/MOVSD
17945 if (N->getOpcode() == ISD::VSELECT &&
17946 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17947 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17948 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17949 bool CanFold = false;
17950 unsigned NumElems = Cond.getNumOperands();
17954 if (isZero(Cond.getOperand(0))) {
17957 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17958 // fold (vselect <0,-1> -> (movsd A, B)
17959 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17960 CanFold = isAllOnes(Cond.getOperand(i));
17961 } else if (isAllOnes(Cond.getOperand(0))) {
17965 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17966 // fold (vselect <-1,0> -> (movsd B, A)
17967 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17968 CanFold = isZero(Cond.getOperand(i));
17972 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17973 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17974 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17977 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17978 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17979 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17980 // (v2i64 (bitcast B)))))
17982 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17983 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17984 // (v2f64 (bitcast B)))))
17986 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17987 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17988 // (v2i64 (bitcast A)))))
17990 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17991 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17992 // (v2f64 (bitcast A)))))
17994 CanFold = (isZero(Cond.getOperand(0)) &&
17995 isZero(Cond.getOperand(1)) &&
17996 isAllOnes(Cond.getOperand(2)) &&
17997 isAllOnes(Cond.getOperand(3)));
17999 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18000 isAllOnes(Cond.getOperand(1)) &&
18001 isZero(Cond.getOperand(2)) &&
18002 isZero(Cond.getOperand(3))) {
18004 std::swap(LHS, RHS);
18008 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18009 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18010 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18011 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18013 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18019 // If we know that this node is legal then we know that it is going to be
18020 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18021 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18022 // to simplify previous instructions.
18023 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18024 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
18025 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18027 // Don't optimize vector selects that map to mask-registers.
18031 // Check all uses of that condition operand to check whether it will be
18032 // consumed by non-BLEND instructions, which may depend on all bits are set
18034 for (SDNode::use_iterator I = Cond->use_begin(),
18035 E = Cond->use_end(); I != E; ++I)
18036 if (I->getOpcode() != ISD::VSELECT)
18037 // TODO: Add other opcodes eventually lowered into BLEND.
18040 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18041 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18043 APInt KnownZero, KnownOne;
18044 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18045 DCI.isBeforeLegalizeOps());
18046 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18047 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18048 DCI.CommitTargetLoweringOpt(TLO);
18054 // Check whether a boolean test is testing a boolean value generated by
18055 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18058 // Simplify the following patterns:
18059 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18060 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18061 // to (Op EFLAGS Cond)
18063 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18064 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18065 // to (Op EFLAGS !Cond)
18067 // where Op could be BRCOND or CMOV.
18069 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18070 // Quit if not CMP and SUB with its value result used.
18071 if (Cmp.getOpcode() != X86ISD::CMP &&
18072 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18075 // Quit if not used as a boolean value.
18076 if (CC != X86::COND_E && CC != X86::COND_NE)
18079 // Check CMP operands. One of them should be 0 or 1 and the other should be
18080 // an SetCC or extended from it.
18081 SDValue Op1 = Cmp.getOperand(0);
18082 SDValue Op2 = Cmp.getOperand(1);
18085 const ConstantSDNode* C = nullptr;
18086 bool needOppositeCond = (CC == X86::COND_E);
18087 bool checkAgainstTrue = false; // Is it a comparison against 1?
18089 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18091 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18093 else // Quit if all operands are not constants.
18096 if (C->getZExtValue() == 1) {
18097 needOppositeCond = !needOppositeCond;
18098 checkAgainstTrue = true;
18099 } else if (C->getZExtValue() != 0)
18100 // Quit if the constant is neither 0 or 1.
18103 bool truncatedToBoolWithAnd = false;
18104 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18105 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18106 SetCC.getOpcode() == ISD::TRUNCATE ||
18107 SetCC.getOpcode() == ISD::AND) {
18108 if (SetCC.getOpcode() == ISD::AND) {
18110 ConstantSDNode *CS;
18111 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18112 CS->getZExtValue() == 1)
18114 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18115 CS->getZExtValue() == 1)
18119 SetCC = SetCC.getOperand(OpIdx);
18120 truncatedToBoolWithAnd = true;
18122 SetCC = SetCC.getOperand(0);
18125 switch (SetCC.getOpcode()) {
18126 case X86ISD::SETCC_CARRY:
18127 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18128 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18129 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18130 // truncated to i1 using 'and'.
18131 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18133 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18134 "Invalid use of SETCC_CARRY!");
18136 case X86ISD::SETCC:
18137 // Set the condition code or opposite one if necessary.
18138 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18139 if (needOppositeCond)
18140 CC = X86::GetOppositeBranchCondition(CC);
18141 return SetCC.getOperand(1);
18142 case X86ISD::CMOV: {
18143 // Check whether false/true value has canonical one, i.e. 0 or 1.
18144 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18145 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18146 // Quit if true value is not a constant.
18149 // Quit if false value is not a constant.
18151 SDValue Op = SetCC.getOperand(0);
18152 // Skip 'zext' or 'trunc' node.
18153 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18154 Op.getOpcode() == ISD::TRUNCATE)
18155 Op = Op.getOperand(0);
18156 // A special case for rdrand/rdseed, where 0 is set if false cond is
18158 if ((Op.getOpcode() != X86ISD::RDRAND &&
18159 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18162 // Quit if false value is not the constant 0 or 1.
18163 bool FValIsFalse = true;
18164 if (FVal && FVal->getZExtValue() != 0) {
18165 if (FVal->getZExtValue() != 1)
18167 // If FVal is 1, opposite cond is needed.
18168 needOppositeCond = !needOppositeCond;
18169 FValIsFalse = false;
18171 // Quit if TVal is not the constant opposite of FVal.
18172 if (FValIsFalse && TVal->getZExtValue() != 1)
18174 if (!FValIsFalse && TVal->getZExtValue() != 0)
18176 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18177 if (needOppositeCond)
18178 CC = X86::GetOppositeBranchCondition(CC);
18179 return SetCC.getOperand(3);
18186 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18187 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18188 TargetLowering::DAGCombinerInfo &DCI,
18189 const X86Subtarget *Subtarget) {
18192 // If the flag operand isn't dead, don't touch this CMOV.
18193 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18196 SDValue FalseOp = N->getOperand(0);
18197 SDValue TrueOp = N->getOperand(1);
18198 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18199 SDValue Cond = N->getOperand(3);
18201 if (CC == X86::COND_E || CC == X86::COND_NE) {
18202 switch (Cond.getOpcode()) {
18206 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18207 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18208 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18214 Flags = checkBoolTestSetCCCombine(Cond, CC);
18215 if (Flags.getNode() &&
18216 // Extra check as FCMOV only supports a subset of X86 cond.
18217 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18218 SDValue Ops[] = { FalseOp, TrueOp,
18219 DAG.getConstant(CC, MVT::i8), Flags };
18220 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18223 // If this is a select between two integer constants, try to do some
18224 // optimizations. Note that the operands are ordered the opposite of SELECT
18226 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18227 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18228 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18229 // larger than FalseC (the false value).
18230 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18231 CC = X86::GetOppositeBranchCondition(CC);
18232 std::swap(TrueC, FalseC);
18233 std::swap(TrueOp, FalseOp);
18236 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18237 // This is efficient for any integer data type (including i8/i16) and
18239 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18240 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18241 DAG.getConstant(CC, MVT::i8), Cond);
18243 // Zero extend the condition if needed.
18244 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18246 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18247 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18248 DAG.getConstant(ShAmt, MVT::i8));
18249 if (N->getNumValues() == 2) // Dead flag value?
18250 return DCI.CombineTo(N, Cond, SDValue());
18254 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18255 // for any integer data type, including i8/i16.
18256 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18257 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18258 DAG.getConstant(CC, MVT::i8), Cond);
18260 // Zero extend the condition if needed.
18261 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18262 FalseC->getValueType(0), Cond);
18263 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18264 SDValue(FalseC, 0));
18266 if (N->getNumValues() == 2) // Dead flag value?
18267 return DCI.CombineTo(N, Cond, SDValue());
18271 // Optimize cases that will turn into an LEA instruction. This requires
18272 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18273 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18274 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18275 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18277 bool isFastMultiplier = false;
18279 switch ((unsigned char)Diff) {
18281 case 1: // result = add base, cond
18282 case 2: // result = lea base( , cond*2)
18283 case 3: // result = lea base(cond, cond*2)
18284 case 4: // result = lea base( , cond*4)
18285 case 5: // result = lea base(cond, cond*4)
18286 case 8: // result = lea base( , cond*8)
18287 case 9: // result = lea base(cond, cond*8)
18288 isFastMultiplier = true;
18293 if (isFastMultiplier) {
18294 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18295 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18296 DAG.getConstant(CC, MVT::i8), Cond);
18297 // Zero extend the condition if needed.
18298 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18300 // Scale the condition by the difference.
18302 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18303 DAG.getConstant(Diff, Cond.getValueType()));
18305 // Add the base if non-zero.
18306 if (FalseC->getAPIntValue() != 0)
18307 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18308 SDValue(FalseC, 0));
18309 if (N->getNumValues() == 2) // Dead flag value?
18310 return DCI.CombineTo(N, Cond, SDValue());
18317 // Handle these cases:
18318 // (select (x != c), e, c) -> select (x != c), e, x),
18319 // (select (x == c), c, e) -> select (x == c), x, e)
18320 // where the c is an integer constant, and the "select" is the combination
18321 // of CMOV and CMP.
18323 // The rationale for this change is that the conditional-move from a constant
18324 // needs two instructions, however, conditional-move from a register needs
18325 // only one instruction.
18327 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18328 // some instruction-combining opportunities. This opt needs to be
18329 // postponed as late as possible.
18331 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18332 // the DCI.xxxx conditions are provided to postpone the optimization as
18333 // late as possible.
18335 ConstantSDNode *CmpAgainst = nullptr;
18336 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18337 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18338 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18340 if (CC == X86::COND_NE &&
18341 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18342 CC = X86::GetOppositeBranchCondition(CC);
18343 std::swap(TrueOp, FalseOp);
18346 if (CC == X86::COND_E &&
18347 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18348 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18349 DAG.getConstant(CC, MVT::i8), Cond };
18350 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18358 /// PerformMulCombine - Optimize a single multiply with constant into two
18359 /// in order to implement it with two cheaper instructions, e.g.
18360 /// LEA + SHL, LEA + LEA.
18361 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18362 TargetLowering::DAGCombinerInfo &DCI) {
18363 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18366 EVT VT = N->getValueType(0);
18367 if (VT != MVT::i64)
18370 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18373 uint64_t MulAmt = C->getZExtValue();
18374 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18377 uint64_t MulAmt1 = 0;
18378 uint64_t MulAmt2 = 0;
18379 if ((MulAmt % 9) == 0) {
18381 MulAmt2 = MulAmt / 9;
18382 } else if ((MulAmt % 5) == 0) {
18384 MulAmt2 = MulAmt / 5;
18385 } else if ((MulAmt % 3) == 0) {
18387 MulAmt2 = MulAmt / 3;
18390 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18393 if (isPowerOf2_64(MulAmt2) &&
18394 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18395 // If second multiplifer is pow2, issue it first. We want the multiply by
18396 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18398 std::swap(MulAmt1, MulAmt2);
18401 if (isPowerOf2_64(MulAmt1))
18402 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18403 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18405 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18406 DAG.getConstant(MulAmt1, VT));
18408 if (isPowerOf2_64(MulAmt2))
18409 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18410 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18412 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18413 DAG.getConstant(MulAmt2, VT));
18415 // Do not add new nodes to DAG combiner worklist.
18416 DCI.CombineTo(N, NewMul, false);
18421 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18422 SDValue N0 = N->getOperand(0);
18423 SDValue N1 = N->getOperand(1);
18424 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18425 EVT VT = N0.getValueType();
18427 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18428 // since the result of setcc_c is all zero's or all ones.
18429 if (VT.isInteger() && !VT.isVector() &&
18430 N1C && N0.getOpcode() == ISD::AND &&
18431 N0.getOperand(1).getOpcode() == ISD::Constant) {
18432 SDValue N00 = N0.getOperand(0);
18433 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18434 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18435 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18436 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18437 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18438 APInt ShAmt = N1C->getAPIntValue();
18439 Mask = Mask.shl(ShAmt);
18441 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18442 N00, DAG.getConstant(Mask, VT));
18446 // Hardware support for vector shifts is sparse which makes us scalarize the
18447 // vector operations in many cases. Also, on sandybridge ADD is faster than
18449 // (shl V, 1) -> add V,V
18450 if (isSplatVector(N1.getNode())) {
18451 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18452 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18453 // We shift all of the values by one. In many cases we do not have
18454 // hardware support for this operation. This is better expressed as an ADD
18456 if (N1C && (1 == N1C->getZExtValue())) {
18457 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18464 /// \brief Returns a vector of 0s if the node in input is a vector logical
18465 /// shift by a constant amount which is known to be bigger than or equal
18466 /// to the vector element size in bits.
18467 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18468 const X86Subtarget *Subtarget) {
18469 EVT VT = N->getValueType(0);
18471 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18472 (!Subtarget->hasInt256() ||
18473 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18476 SDValue Amt = N->getOperand(1);
18478 if (isSplatVector(Amt.getNode())) {
18479 SDValue SclrAmt = Amt->getOperand(0);
18480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18481 APInt ShiftAmt = C->getAPIntValue();
18482 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18484 // SSE2/AVX2 logical shifts always return a vector of 0s
18485 // if the shift amount is bigger than or equal to
18486 // the element size. The constant shift amount will be
18487 // encoded as a 8-bit immediate.
18488 if (ShiftAmt.trunc(8).uge(MaxAmount))
18489 return getZeroVector(VT, Subtarget, DAG, DL);
18496 /// PerformShiftCombine - Combine shifts.
18497 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18498 TargetLowering::DAGCombinerInfo &DCI,
18499 const X86Subtarget *Subtarget) {
18500 if (N->getOpcode() == ISD::SHL) {
18501 SDValue V = PerformSHLCombine(N, DAG);
18502 if (V.getNode()) return V;
18505 if (N->getOpcode() != ISD::SRA) {
18506 // Try to fold this logical shift into a zero vector.
18507 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18508 if (V.getNode()) return V;
18514 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18515 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18516 // and friends. Likewise for OR -> CMPNEQSS.
18517 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18518 TargetLowering::DAGCombinerInfo &DCI,
18519 const X86Subtarget *Subtarget) {
18522 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18523 // we're requiring SSE2 for both.
18524 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18525 SDValue N0 = N->getOperand(0);
18526 SDValue N1 = N->getOperand(1);
18527 SDValue CMP0 = N0->getOperand(1);
18528 SDValue CMP1 = N1->getOperand(1);
18531 // The SETCCs should both refer to the same CMP.
18532 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18535 SDValue CMP00 = CMP0->getOperand(0);
18536 SDValue CMP01 = CMP0->getOperand(1);
18537 EVT VT = CMP00.getValueType();
18539 if (VT == MVT::f32 || VT == MVT::f64) {
18540 bool ExpectingFlags = false;
18541 // Check for any users that want flags:
18542 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18543 !ExpectingFlags && UI != UE; ++UI)
18544 switch (UI->getOpcode()) {
18549 ExpectingFlags = true;
18551 case ISD::CopyToReg:
18552 case ISD::SIGN_EXTEND:
18553 case ISD::ZERO_EXTEND:
18554 case ISD::ANY_EXTEND:
18558 if (!ExpectingFlags) {
18559 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18560 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18562 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18563 X86::CondCode tmp = cc0;
18568 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18569 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18570 // FIXME: need symbolic constants for these magic numbers.
18571 // See X86ATTInstPrinter.cpp:printSSECC().
18572 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18573 if (Subtarget->hasAVX512()) {
18574 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18575 CMP01, DAG.getConstant(x86cc, MVT::i8));
18576 if (N->getValueType(0) != MVT::i1)
18577 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18581 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18582 CMP00.getValueType(), CMP00, CMP01,
18583 DAG.getConstant(x86cc, MVT::i8));
18585 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18586 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18588 if (is64BitFP && !Subtarget->is64Bit()) {
18589 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18590 // 64-bit integer, since that's not a legal type. Since
18591 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18592 // bits, but can do this little dance to extract the lowest 32 bits
18593 // and work with those going forward.
18594 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18596 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18598 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18599 Vector32, DAG.getIntPtrConstant(0));
18603 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18604 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18605 DAG.getConstant(1, IntVT));
18606 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18607 return OneBitOfTruth;
18615 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18616 /// so it can be folded inside ANDNP.
18617 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18618 EVT VT = N->getValueType(0);
18620 // Match direct AllOnes for 128 and 256-bit vectors
18621 if (ISD::isBuildVectorAllOnes(N))
18624 // Look through a bit convert.
18625 if (N->getOpcode() == ISD::BITCAST)
18626 N = N->getOperand(0).getNode();
18628 // Sometimes the operand may come from a insert_subvector building a 256-bit
18630 if (VT.is256BitVector() &&
18631 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18632 SDValue V1 = N->getOperand(0);
18633 SDValue V2 = N->getOperand(1);
18635 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18636 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18637 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18638 ISD::isBuildVectorAllOnes(V2.getNode()))
18645 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18646 // register. In most cases we actually compare or select YMM-sized registers
18647 // and mixing the two types creates horrible code. This method optimizes
18648 // some of the transition sequences.
18649 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18650 TargetLowering::DAGCombinerInfo &DCI,
18651 const X86Subtarget *Subtarget) {
18652 EVT VT = N->getValueType(0);
18653 if (!VT.is256BitVector())
18656 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18657 N->getOpcode() == ISD::ZERO_EXTEND ||
18658 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18660 SDValue Narrow = N->getOperand(0);
18661 EVT NarrowVT = Narrow->getValueType(0);
18662 if (!NarrowVT.is128BitVector())
18665 if (Narrow->getOpcode() != ISD::XOR &&
18666 Narrow->getOpcode() != ISD::AND &&
18667 Narrow->getOpcode() != ISD::OR)
18670 SDValue N0 = Narrow->getOperand(0);
18671 SDValue N1 = Narrow->getOperand(1);
18674 // The Left side has to be a trunc.
18675 if (N0.getOpcode() != ISD::TRUNCATE)
18678 // The type of the truncated inputs.
18679 EVT WideVT = N0->getOperand(0)->getValueType(0);
18683 // The right side has to be a 'trunc' or a constant vector.
18684 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18685 bool RHSConst = (isSplatVector(N1.getNode()) &&
18686 isa<ConstantSDNode>(N1->getOperand(0)));
18687 if (!RHSTrunc && !RHSConst)
18690 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18692 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18695 // Set N0 and N1 to hold the inputs to the new wide operation.
18696 N0 = N0->getOperand(0);
18698 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18699 N1->getOperand(0));
18700 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18701 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18702 } else if (RHSTrunc) {
18703 N1 = N1->getOperand(0);
18706 // Generate the wide operation.
18707 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18708 unsigned Opcode = N->getOpcode();
18710 case ISD::ANY_EXTEND:
18712 case ISD::ZERO_EXTEND: {
18713 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18714 APInt Mask = APInt::getAllOnesValue(InBits);
18715 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18716 return DAG.getNode(ISD::AND, DL, VT,
18717 Op, DAG.getConstant(Mask, VT));
18719 case ISD::SIGN_EXTEND:
18720 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18721 Op, DAG.getValueType(NarrowVT));
18723 llvm_unreachable("Unexpected opcode");
18727 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18728 TargetLowering::DAGCombinerInfo &DCI,
18729 const X86Subtarget *Subtarget) {
18730 EVT VT = N->getValueType(0);
18731 if (DCI.isBeforeLegalizeOps())
18734 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18738 // Create BEXTR instructions
18739 // BEXTR is ((X >> imm) & (2**size-1))
18740 if (VT == MVT::i32 || VT == MVT::i64) {
18741 SDValue N0 = N->getOperand(0);
18742 SDValue N1 = N->getOperand(1);
18745 // Check for BEXTR.
18746 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18747 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18748 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18749 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18750 if (MaskNode && ShiftNode) {
18751 uint64_t Mask = MaskNode->getZExtValue();
18752 uint64_t Shift = ShiftNode->getZExtValue();
18753 if (isMask_64(Mask)) {
18754 uint64_t MaskSize = CountPopulation_64(Mask);
18755 if (Shift + MaskSize <= VT.getSizeInBits())
18756 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18757 DAG.getConstant(Shift | (MaskSize << 8), VT));
18765 // Want to form ANDNP nodes:
18766 // 1) In the hopes of then easily combining them with OR and AND nodes
18767 // to form PBLEND/PSIGN.
18768 // 2) To match ANDN packed intrinsics
18769 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18772 SDValue N0 = N->getOperand(0);
18773 SDValue N1 = N->getOperand(1);
18776 // Check LHS for vnot
18777 if (N0.getOpcode() == ISD::XOR &&
18778 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18779 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18780 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18782 // Check RHS for vnot
18783 if (N1.getOpcode() == ISD::XOR &&
18784 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18785 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18786 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18791 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18792 TargetLowering::DAGCombinerInfo &DCI,
18793 const X86Subtarget *Subtarget) {
18794 if (DCI.isBeforeLegalizeOps())
18797 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18801 SDValue N0 = N->getOperand(0);
18802 SDValue N1 = N->getOperand(1);
18803 EVT VT = N->getValueType(0);
18805 // look for psign/blend
18806 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18807 if (!Subtarget->hasSSSE3() ||
18808 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18811 // Canonicalize pandn to RHS
18812 if (N0.getOpcode() == X86ISD::ANDNP)
18814 // or (and (m, y), (pandn m, x))
18815 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18816 SDValue Mask = N1.getOperand(0);
18817 SDValue X = N1.getOperand(1);
18819 if (N0.getOperand(0) == Mask)
18820 Y = N0.getOperand(1);
18821 if (N0.getOperand(1) == Mask)
18822 Y = N0.getOperand(0);
18824 // Check to see if the mask appeared in both the AND and ANDNP and
18828 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18829 // Look through mask bitcast.
18830 if (Mask.getOpcode() == ISD::BITCAST)
18831 Mask = Mask.getOperand(0);
18832 if (X.getOpcode() == ISD::BITCAST)
18833 X = X.getOperand(0);
18834 if (Y.getOpcode() == ISD::BITCAST)
18835 Y = Y.getOperand(0);
18837 EVT MaskVT = Mask.getValueType();
18839 // Validate that the Mask operand is a vector sra node.
18840 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18841 // there is no psrai.b
18842 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18843 unsigned SraAmt = ~0;
18844 if (Mask.getOpcode() == ISD::SRA) {
18845 SDValue Amt = Mask.getOperand(1);
18846 if (isSplatVector(Amt.getNode())) {
18847 SDValue SclrAmt = Amt->getOperand(0);
18848 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18849 SraAmt = C->getZExtValue();
18851 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18852 SDValue SraC = Mask.getOperand(1);
18853 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18855 if ((SraAmt + 1) != EltBits)
18860 // Now we know we at least have a plendvb with the mask val. See if
18861 // we can form a psignb/w/d.
18862 // psign = x.type == y.type == mask.type && y = sub(0, x);
18863 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18864 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18865 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18866 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18867 "Unsupported VT for PSIGN");
18868 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18869 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18871 // PBLENDVB only available on SSE 4.1
18872 if (!Subtarget->hasSSE41())
18875 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18877 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18878 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18879 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18880 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18881 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18885 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18888 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18889 MachineFunction &MF = DAG.getMachineFunction();
18890 bool OptForSize = MF.getFunction()->getAttributes().
18891 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18893 // SHLD/SHRD instructions have lower register pressure, but on some
18894 // platforms they have higher latency than the equivalent
18895 // series of shifts/or that would otherwise be generated.
18896 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18897 // have higher latencies and we are not optimizing for size.
18898 if (!OptForSize && Subtarget->isSHLDSlow())
18901 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18903 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18905 if (!N0.hasOneUse() || !N1.hasOneUse())
18908 SDValue ShAmt0 = N0.getOperand(1);
18909 if (ShAmt0.getValueType() != MVT::i8)
18911 SDValue ShAmt1 = N1.getOperand(1);
18912 if (ShAmt1.getValueType() != MVT::i8)
18914 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18915 ShAmt0 = ShAmt0.getOperand(0);
18916 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18917 ShAmt1 = ShAmt1.getOperand(0);
18920 unsigned Opc = X86ISD::SHLD;
18921 SDValue Op0 = N0.getOperand(0);
18922 SDValue Op1 = N1.getOperand(0);
18923 if (ShAmt0.getOpcode() == ISD::SUB) {
18924 Opc = X86ISD::SHRD;
18925 std::swap(Op0, Op1);
18926 std::swap(ShAmt0, ShAmt1);
18929 unsigned Bits = VT.getSizeInBits();
18930 if (ShAmt1.getOpcode() == ISD::SUB) {
18931 SDValue Sum = ShAmt1.getOperand(0);
18932 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18933 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18934 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18935 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18936 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18937 return DAG.getNode(Opc, DL, VT,
18939 DAG.getNode(ISD::TRUNCATE, DL,
18942 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18943 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18945 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18946 return DAG.getNode(Opc, DL, VT,
18947 N0.getOperand(0), N1.getOperand(0),
18948 DAG.getNode(ISD::TRUNCATE, DL,
18955 // Generate NEG and CMOV for integer abs.
18956 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18957 EVT VT = N->getValueType(0);
18959 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18960 // 8-bit integer abs to NEG and CMOV.
18961 if (VT.isInteger() && VT.getSizeInBits() == 8)
18964 SDValue N0 = N->getOperand(0);
18965 SDValue N1 = N->getOperand(1);
18968 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18969 // and change it to SUB and CMOV.
18970 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18971 N0.getOpcode() == ISD::ADD &&
18972 N0.getOperand(1) == N1 &&
18973 N1.getOpcode() == ISD::SRA &&
18974 N1.getOperand(0) == N0.getOperand(0))
18975 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18976 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18977 // Generate SUB & CMOV.
18978 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18979 DAG.getConstant(0, VT), N0.getOperand(0));
18981 SDValue Ops[] = { N0.getOperand(0), Neg,
18982 DAG.getConstant(X86::COND_GE, MVT::i8),
18983 SDValue(Neg.getNode(), 1) };
18984 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18989 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18990 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18991 TargetLowering::DAGCombinerInfo &DCI,
18992 const X86Subtarget *Subtarget) {
18993 if (DCI.isBeforeLegalizeOps())
18996 if (Subtarget->hasCMov()) {
18997 SDValue RV = performIntegerAbsCombine(N, DAG);
19005 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19006 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19007 TargetLowering::DAGCombinerInfo &DCI,
19008 const X86Subtarget *Subtarget) {
19009 LoadSDNode *Ld = cast<LoadSDNode>(N);
19010 EVT RegVT = Ld->getValueType(0);
19011 EVT MemVT = Ld->getMemoryVT();
19013 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19014 unsigned RegSz = RegVT.getSizeInBits();
19016 // On Sandybridge unaligned 256bit loads are inefficient.
19017 ISD::LoadExtType Ext = Ld->getExtensionType();
19018 unsigned Alignment = Ld->getAlignment();
19019 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19020 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19021 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19022 unsigned NumElems = RegVT.getVectorNumElements();
19026 SDValue Ptr = Ld->getBasePtr();
19027 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19029 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19031 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19032 Ld->getPointerInfo(), Ld->isVolatile(),
19033 Ld->isNonTemporal(), Ld->isInvariant(),
19035 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19036 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19037 Ld->getPointerInfo(), Ld->isVolatile(),
19038 Ld->isNonTemporal(), Ld->isInvariant(),
19039 std::min(16U, Alignment));
19040 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19042 Load2.getValue(1));
19044 SDValue NewVec = DAG.getUNDEF(RegVT);
19045 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19046 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19047 return DCI.CombineTo(N, NewVec, TF, true);
19050 // If this is a vector EXT Load then attempt to optimize it using a
19051 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19052 // expansion is still better than scalar code.
19053 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19054 // emit a shuffle and a arithmetic shift.
19055 // TODO: It is possible to support ZExt by zeroing the undef values
19056 // during the shuffle phase or after the shuffle.
19057 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19058 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19059 assert(MemVT != RegVT && "Cannot extend to the same type");
19060 assert(MemVT.isVector() && "Must load a vector from memory");
19062 unsigned NumElems = RegVT.getVectorNumElements();
19063 unsigned MemSz = MemVT.getSizeInBits();
19064 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19066 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19069 // All sizes must be a power of two.
19070 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19073 // Attempt to load the original value using scalar loads.
19074 // Find the largest scalar type that divides the total loaded size.
19075 MVT SclrLoadTy = MVT::i8;
19076 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19077 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19078 MVT Tp = (MVT::SimpleValueType)tp;
19079 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19084 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19085 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19087 SclrLoadTy = MVT::f64;
19089 // Calculate the number of scalar loads that we need to perform
19090 // in order to load our vector from memory.
19091 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19092 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19095 unsigned loadRegZize = RegSz;
19096 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19099 // Represent our vector as a sequence of elements which are the
19100 // largest scalar that we can load.
19101 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19102 loadRegZize/SclrLoadTy.getSizeInBits());
19104 // Represent the data using the same element type that is stored in
19105 // memory. In practice, we ''widen'' MemVT.
19107 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19108 loadRegZize/MemVT.getScalarType().getSizeInBits());
19110 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19111 "Invalid vector type");
19113 // We can't shuffle using an illegal type.
19114 if (!TLI.isTypeLegal(WideVecVT))
19117 SmallVector<SDValue, 8> Chains;
19118 SDValue Ptr = Ld->getBasePtr();
19119 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19120 TLI.getPointerTy());
19121 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19123 for (unsigned i = 0; i < NumLoads; ++i) {
19124 // Perform a single load.
19125 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19126 Ptr, Ld->getPointerInfo(),
19127 Ld->isVolatile(), Ld->isNonTemporal(),
19128 Ld->isInvariant(), Ld->getAlignment());
19129 Chains.push_back(ScalarLoad.getValue(1));
19130 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19131 // another round of DAGCombining.
19133 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19135 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19136 ScalarLoad, DAG.getIntPtrConstant(i));
19138 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19141 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19143 // Bitcast the loaded value to a vector of the original element type, in
19144 // the size of the target vector type.
19145 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19146 unsigned SizeRatio = RegSz/MemSz;
19148 if (Ext == ISD::SEXTLOAD) {
19149 // If we have SSE4.1 we can directly emit a VSEXT node.
19150 if (Subtarget->hasSSE41()) {
19151 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19152 return DCI.CombineTo(N, Sext, TF, true);
19155 // Otherwise we'll shuffle the small elements in the high bits of the
19156 // larger type and perform an arithmetic shift. If the shift is not legal
19157 // it's better to scalarize.
19158 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19161 // Redistribute the loaded elements into the different locations.
19162 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19163 for (unsigned i = 0; i != NumElems; ++i)
19164 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19166 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19167 DAG.getUNDEF(WideVecVT),
19170 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19172 // Build the arithmetic shift.
19173 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19174 MemVT.getVectorElementType().getSizeInBits();
19175 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19176 DAG.getConstant(Amt, RegVT));
19178 return DCI.CombineTo(N, Shuff, TF, true);
19181 // Redistribute the loaded elements into the different locations.
19182 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19183 for (unsigned i = 0; i != NumElems; ++i)
19184 ShuffleVec[i*SizeRatio] = i;
19186 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19187 DAG.getUNDEF(WideVecVT),
19190 // Bitcast to the requested type.
19191 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19192 // Replace the original load with the new sequence
19193 // and return the new chain.
19194 return DCI.CombineTo(N, Shuff, TF, true);
19200 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19201 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19202 const X86Subtarget *Subtarget) {
19203 StoreSDNode *St = cast<StoreSDNode>(N);
19204 EVT VT = St->getValue().getValueType();
19205 EVT StVT = St->getMemoryVT();
19207 SDValue StoredVal = St->getOperand(1);
19208 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19210 // If we are saving a concatenation of two XMM registers, perform two stores.
19211 // On Sandy Bridge, 256-bit memory operations are executed by two
19212 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19213 // memory operation.
19214 unsigned Alignment = St->getAlignment();
19215 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19216 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19217 StVT == VT && !IsAligned) {
19218 unsigned NumElems = VT.getVectorNumElements();
19222 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19223 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19225 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19226 SDValue Ptr0 = St->getBasePtr();
19227 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19229 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19230 St->getPointerInfo(), St->isVolatile(),
19231 St->isNonTemporal(), Alignment);
19232 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19233 St->getPointerInfo(), St->isVolatile(),
19234 St->isNonTemporal(),
19235 std::min(16U, Alignment));
19236 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19239 // Optimize trunc store (of multiple scalars) to shuffle and store.
19240 // First, pack all of the elements in one place. Next, store to memory
19241 // in fewer chunks.
19242 if (St->isTruncatingStore() && VT.isVector()) {
19243 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19244 unsigned NumElems = VT.getVectorNumElements();
19245 assert(StVT != VT && "Cannot truncate to the same type");
19246 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19247 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19249 // From, To sizes and ElemCount must be pow of two
19250 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19251 // We are going to use the original vector elt for storing.
19252 // Accumulated smaller vector elements must be a multiple of the store size.
19253 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19255 unsigned SizeRatio = FromSz / ToSz;
19257 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19259 // Create a type on which we perform the shuffle
19260 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19261 StVT.getScalarType(), NumElems*SizeRatio);
19263 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19265 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19266 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19267 for (unsigned i = 0; i != NumElems; ++i)
19268 ShuffleVec[i] = i * SizeRatio;
19270 // Can't shuffle using an illegal type.
19271 if (!TLI.isTypeLegal(WideVecVT))
19274 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19275 DAG.getUNDEF(WideVecVT),
19277 // At this point all of the data is stored at the bottom of the
19278 // register. We now need to save it to mem.
19280 // Find the largest store unit
19281 MVT StoreType = MVT::i8;
19282 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19283 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19284 MVT Tp = (MVT::SimpleValueType)tp;
19285 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19289 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19290 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19291 (64 <= NumElems * ToSz))
19292 StoreType = MVT::f64;
19294 // Bitcast the original vector into a vector of store-size units
19295 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19296 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19297 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19298 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19299 SmallVector<SDValue, 8> Chains;
19300 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19301 TLI.getPointerTy());
19302 SDValue Ptr = St->getBasePtr();
19304 // Perform one or more big stores into memory.
19305 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19306 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19307 StoreType, ShuffWide,
19308 DAG.getIntPtrConstant(i));
19309 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19310 St->getPointerInfo(), St->isVolatile(),
19311 St->isNonTemporal(), St->getAlignment());
19312 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19313 Chains.push_back(Ch);
19316 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19319 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19320 // the FP state in cases where an emms may be missing.
19321 // A preferable solution to the general problem is to figure out the right
19322 // places to insert EMMS. This qualifies as a quick hack.
19324 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19325 if (VT.getSizeInBits() != 64)
19328 const Function *F = DAG.getMachineFunction().getFunction();
19329 bool NoImplicitFloatOps = F->getAttributes().
19330 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19331 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19332 && Subtarget->hasSSE2();
19333 if ((VT.isVector() ||
19334 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19335 isa<LoadSDNode>(St->getValue()) &&
19336 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19337 St->getChain().hasOneUse() && !St->isVolatile()) {
19338 SDNode* LdVal = St->getValue().getNode();
19339 LoadSDNode *Ld = nullptr;
19340 int TokenFactorIndex = -1;
19341 SmallVector<SDValue, 8> Ops;
19342 SDNode* ChainVal = St->getChain().getNode();
19343 // Must be a store of a load. We currently handle two cases: the load
19344 // is a direct child, and it's under an intervening TokenFactor. It is
19345 // possible to dig deeper under nested TokenFactors.
19346 if (ChainVal == LdVal)
19347 Ld = cast<LoadSDNode>(St->getChain());
19348 else if (St->getValue().hasOneUse() &&
19349 ChainVal->getOpcode() == ISD::TokenFactor) {
19350 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19351 if (ChainVal->getOperand(i).getNode() == LdVal) {
19352 TokenFactorIndex = i;
19353 Ld = cast<LoadSDNode>(St->getValue());
19355 Ops.push_back(ChainVal->getOperand(i));
19359 if (!Ld || !ISD::isNormalLoad(Ld))
19362 // If this is not the MMX case, i.e. we are just turning i64 load/store
19363 // into f64 load/store, avoid the transformation if there are multiple
19364 // uses of the loaded value.
19365 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19370 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19371 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19373 if (Subtarget->is64Bit() || F64IsLegal) {
19374 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19375 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19376 Ld->getPointerInfo(), Ld->isVolatile(),
19377 Ld->isNonTemporal(), Ld->isInvariant(),
19378 Ld->getAlignment());
19379 SDValue NewChain = NewLd.getValue(1);
19380 if (TokenFactorIndex != -1) {
19381 Ops.push_back(NewChain);
19382 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19384 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19385 St->getPointerInfo(),
19386 St->isVolatile(), St->isNonTemporal(),
19387 St->getAlignment());
19390 // Otherwise, lower to two pairs of 32-bit loads / stores.
19391 SDValue LoAddr = Ld->getBasePtr();
19392 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19393 DAG.getConstant(4, MVT::i32));
19395 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19396 Ld->getPointerInfo(),
19397 Ld->isVolatile(), Ld->isNonTemporal(),
19398 Ld->isInvariant(), Ld->getAlignment());
19399 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19400 Ld->getPointerInfo().getWithOffset(4),
19401 Ld->isVolatile(), Ld->isNonTemporal(),
19403 MinAlign(Ld->getAlignment(), 4));
19405 SDValue NewChain = LoLd.getValue(1);
19406 if (TokenFactorIndex != -1) {
19407 Ops.push_back(LoLd);
19408 Ops.push_back(HiLd);
19409 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19412 LoAddr = St->getBasePtr();
19413 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19414 DAG.getConstant(4, MVT::i32));
19416 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19417 St->getPointerInfo(),
19418 St->isVolatile(), St->isNonTemporal(),
19419 St->getAlignment());
19420 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19421 St->getPointerInfo().getWithOffset(4),
19423 St->isNonTemporal(),
19424 MinAlign(St->getAlignment(), 4));
19425 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19430 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19431 /// and return the operands for the horizontal operation in LHS and RHS. A
19432 /// horizontal operation performs the binary operation on successive elements
19433 /// of its first operand, then on successive elements of its second operand,
19434 /// returning the resulting values in a vector. For example, if
19435 /// A = < float a0, float a1, float a2, float a3 >
19437 /// B = < float b0, float b1, float b2, float b3 >
19438 /// then the result of doing a horizontal operation on A and B is
19439 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19440 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19441 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19442 /// set to A, RHS to B, and the routine returns 'true'.
19443 /// Note that the binary operation should have the property that if one of the
19444 /// operands is UNDEF then the result is UNDEF.
19445 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19446 // Look for the following pattern: if
19447 // A = < float a0, float a1, float a2, float a3 >
19448 // B = < float b0, float b1, float b2, float b3 >
19450 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19451 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19452 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19453 // which is A horizontal-op B.
19455 // At least one of the operands should be a vector shuffle.
19456 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19457 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19460 MVT VT = LHS.getSimpleValueType();
19462 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19463 "Unsupported vector type for horizontal add/sub");
19465 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19466 // operate independently on 128-bit lanes.
19467 unsigned NumElts = VT.getVectorNumElements();
19468 unsigned NumLanes = VT.getSizeInBits()/128;
19469 unsigned NumLaneElts = NumElts / NumLanes;
19470 assert((NumLaneElts % 2 == 0) &&
19471 "Vector type should have an even number of elements in each lane");
19472 unsigned HalfLaneElts = NumLaneElts/2;
19474 // View LHS in the form
19475 // LHS = VECTOR_SHUFFLE A, B, LMask
19476 // If LHS is not a shuffle then pretend it is the shuffle
19477 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19478 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19481 SmallVector<int, 16> LMask(NumElts);
19482 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19483 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19484 A = LHS.getOperand(0);
19485 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19486 B = LHS.getOperand(1);
19487 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19488 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19490 if (LHS.getOpcode() != ISD::UNDEF)
19492 for (unsigned i = 0; i != NumElts; ++i)
19496 // Likewise, view RHS in the form
19497 // RHS = VECTOR_SHUFFLE C, D, RMask
19499 SmallVector<int, 16> RMask(NumElts);
19500 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19501 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19502 C = RHS.getOperand(0);
19503 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19504 D = RHS.getOperand(1);
19505 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19506 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19508 if (RHS.getOpcode() != ISD::UNDEF)
19510 for (unsigned i = 0; i != NumElts; ++i)
19514 // Check that the shuffles are both shuffling the same vectors.
19515 if (!(A == C && B == D) && !(A == D && B == C))
19518 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19519 if (!A.getNode() && !B.getNode())
19522 // If A and B occur in reverse order in RHS, then "swap" them (which means
19523 // rewriting the mask).
19525 CommuteVectorShuffleMask(RMask, NumElts);
19527 // At this point LHS and RHS are equivalent to
19528 // LHS = VECTOR_SHUFFLE A, B, LMask
19529 // RHS = VECTOR_SHUFFLE A, B, RMask
19530 // Check that the masks correspond to performing a horizontal operation.
19531 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19532 for (unsigned i = 0; i != NumLaneElts; ++i) {
19533 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19535 // Ignore any UNDEF components.
19536 if (LIdx < 0 || RIdx < 0 ||
19537 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19538 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19541 // Check that successive elements are being operated on. If not, this is
19542 // not a horizontal operation.
19543 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19544 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19545 if (!(LIdx == Index && RIdx == Index + 1) &&
19546 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19551 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19552 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19556 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19557 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19558 const X86Subtarget *Subtarget) {
19559 EVT VT = N->getValueType(0);
19560 SDValue LHS = N->getOperand(0);
19561 SDValue RHS = N->getOperand(1);
19563 // Try to synthesize horizontal adds from adds of shuffles.
19564 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19565 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19566 isHorizontalBinOp(LHS, RHS, true))
19567 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19571 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19572 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19573 const X86Subtarget *Subtarget) {
19574 EVT VT = N->getValueType(0);
19575 SDValue LHS = N->getOperand(0);
19576 SDValue RHS = N->getOperand(1);
19578 // Try to synthesize horizontal subs from subs of shuffles.
19579 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19580 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19581 isHorizontalBinOp(LHS, RHS, false))
19582 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19586 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19587 /// X86ISD::FXOR nodes.
19588 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19589 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19590 // F[X]OR(0.0, x) -> x
19591 // F[X]OR(x, 0.0) -> x
19592 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19593 if (C->getValueAPF().isPosZero())
19594 return N->getOperand(1);
19595 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19596 if (C->getValueAPF().isPosZero())
19597 return N->getOperand(0);
19601 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19602 /// X86ISD::FMAX nodes.
19603 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19604 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19606 // Only perform optimizations if UnsafeMath is used.
19607 if (!DAG.getTarget().Options.UnsafeFPMath)
19610 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19611 // into FMINC and FMAXC, which are Commutative operations.
19612 unsigned NewOp = 0;
19613 switch (N->getOpcode()) {
19614 default: llvm_unreachable("unknown opcode");
19615 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19616 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19619 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19620 N->getOperand(0), N->getOperand(1));
19623 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19624 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19625 // FAND(0.0, x) -> 0.0
19626 // FAND(x, 0.0) -> 0.0
19627 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19628 if (C->getValueAPF().isPosZero())
19629 return N->getOperand(0);
19630 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19631 if (C->getValueAPF().isPosZero())
19632 return N->getOperand(1);
19636 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19637 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19638 // FANDN(x, 0.0) -> 0.0
19639 // FANDN(0.0, x) -> x
19640 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19641 if (C->getValueAPF().isPosZero())
19642 return N->getOperand(1);
19643 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19644 if (C->getValueAPF().isPosZero())
19645 return N->getOperand(1);
19649 static SDValue PerformBTCombine(SDNode *N,
19651 TargetLowering::DAGCombinerInfo &DCI) {
19652 // BT ignores high bits in the bit index operand.
19653 SDValue Op1 = N->getOperand(1);
19654 if (Op1.hasOneUse()) {
19655 unsigned BitWidth = Op1.getValueSizeInBits();
19656 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19657 APInt KnownZero, KnownOne;
19658 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19659 !DCI.isBeforeLegalizeOps());
19660 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19661 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19662 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19663 DCI.CommitTargetLoweringOpt(TLO);
19668 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19669 SDValue Op = N->getOperand(0);
19670 if (Op.getOpcode() == ISD::BITCAST)
19671 Op = Op.getOperand(0);
19672 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19673 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19674 VT.getVectorElementType().getSizeInBits() ==
19675 OpVT.getVectorElementType().getSizeInBits()) {
19676 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19681 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19682 const X86Subtarget *Subtarget) {
19683 EVT VT = N->getValueType(0);
19684 if (!VT.isVector())
19687 SDValue N0 = N->getOperand(0);
19688 SDValue N1 = N->getOperand(1);
19689 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19692 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19693 // both SSE and AVX2 since there is no sign-extended shift right
19694 // operation on a vector with 64-bit elements.
19695 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19696 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19697 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19698 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19699 SDValue N00 = N0.getOperand(0);
19701 // EXTLOAD has a better solution on AVX2,
19702 // it may be replaced with X86ISD::VSEXT node.
19703 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19704 if (!ISD::isNormalLoad(N00.getNode()))
19707 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19708 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19710 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19716 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19717 TargetLowering::DAGCombinerInfo &DCI,
19718 const X86Subtarget *Subtarget) {
19719 if (!DCI.isBeforeLegalizeOps())
19722 if (!Subtarget->hasFp256())
19725 EVT VT = N->getValueType(0);
19726 if (VT.isVector() && VT.getSizeInBits() == 256) {
19727 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19735 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19736 const X86Subtarget* Subtarget) {
19738 EVT VT = N->getValueType(0);
19740 // Let legalize expand this if it isn't a legal type yet.
19741 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19744 EVT ScalarVT = VT.getScalarType();
19745 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19746 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19749 SDValue A = N->getOperand(0);
19750 SDValue B = N->getOperand(1);
19751 SDValue C = N->getOperand(2);
19753 bool NegA = (A.getOpcode() == ISD::FNEG);
19754 bool NegB = (B.getOpcode() == ISD::FNEG);
19755 bool NegC = (C.getOpcode() == ISD::FNEG);
19757 // Negative multiplication when NegA xor NegB
19758 bool NegMul = (NegA != NegB);
19760 A = A.getOperand(0);
19762 B = B.getOperand(0);
19764 C = C.getOperand(0);
19768 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19770 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19772 return DAG.getNode(Opcode, dl, VT, A, B, C);
19775 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19776 TargetLowering::DAGCombinerInfo &DCI,
19777 const X86Subtarget *Subtarget) {
19778 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19779 // (and (i32 x86isd::setcc_carry), 1)
19780 // This eliminates the zext. This transformation is necessary because
19781 // ISD::SETCC is always legalized to i8.
19783 SDValue N0 = N->getOperand(0);
19784 EVT VT = N->getValueType(0);
19786 if (N0.getOpcode() == ISD::AND &&
19788 N0.getOperand(0).hasOneUse()) {
19789 SDValue N00 = N0.getOperand(0);
19790 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19791 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19792 if (!C || C->getZExtValue() != 1)
19794 return DAG.getNode(ISD::AND, dl, VT,
19795 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19796 N00.getOperand(0), N00.getOperand(1)),
19797 DAG.getConstant(1, VT));
19801 if (N0.getOpcode() == ISD::TRUNCATE &&
19803 N0.getOperand(0).hasOneUse()) {
19804 SDValue N00 = N0.getOperand(0);
19805 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19806 return DAG.getNode(ISD::AND, dl, VT,
19807 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19808 N00.getOperand(0), N00.getOperand(1)),
19809 DAG.getConstant(1, VT));
19812 if (VT.is256BitVector()) {
19813 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19821 // Optimize x == -y --> x+y == 0
19822 // x != -y --> x+y != 0
19823 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19824 const X86Subtarget* Subtarget) {
19825 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19826 SDValue LHS = N->getOperand(0);
19827 SDValue RHS = N->getOperand(1);
19828 EVT VT = N->getValueType(0);
19831 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19832 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19833 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19834 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19835 LHS.getValueType(), RHS, LHS.getOperand(1));
19836 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19837 addV, DAG.getConstant(0, addV.getValueType()), CC);
19839 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19840 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19841 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19842 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19843 RHS.getValueType(), LHS, RHS.getOperand(1));
19844 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19845 addV, DAG.getConstant(0, addV.getValueType()), CC);
19848 if (VT.getScalarType() == MVT::i1) {
19849 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19850 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19851 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19852 if (!IsSEXT0 && !IsVZero0)
19854 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19855 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19856 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19858 if (!IsSEXT1 && !IsVZero1)
19861 if (IsSEXT0 && IsVZero1) {
19862 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19863 if (CC == ISD::SETEQ)
19864 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19865 return LHS.getOperand(0);
19867 if (IsSEXT1 && IsVZero0) {
19868 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19869 if (CC == ISD::SETEQ)
19870 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19871 return RHS.getOperand(0);
19878 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19879 // as "sbb reg,reg", since it can be extended without zext and produces
19880 // an all-ones bit which is more useful than 0/1 in some cases.
19881 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19884 return DAG.getNode(ISD::AND, DL, VT,
19885 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19886 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19887 DAG.getConstant(1, VT));
19888 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19889 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19890 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19891 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19894 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19895 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19896 TargetLowering::DAGCombinerInfo &DCI,
19897 const X86Subtarget *Subtarget) {
19899 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19900 SDValue EFLAGS = N->getOperand(1);
19902 if (CC == X86::COND_A) {
19903 // Try to convert COND_A into COND_B in an attempt to facilitate
19904 // materializing "setb reg".
19906 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19907 // cannot take an immediate as its first operand.
19909 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19910 EFLAGS.getValueType().isInteger() &&
19911 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19912 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19913 EFLAGS.getNode()->getVTList(),
19914 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19915 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19916 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19920 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19921 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19923 if (CC == X86::COND_B)
19924 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19928 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19929 if (Flags.getNode()) {
19930 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19931 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19937 // Optimize branch condition evaluation.
19939 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19940 TargetLowering::DAGCombinerInfo &DCI,
19941 const X86Subtarget *Subtarget) {
19943 SDValue Chain = N->getOperand(0);
19944 SDValue Dest = N->getOperand(1);
19945 SDValue EFLAGS = N->getOperand(3);
19946 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19950 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19951 if (Flags.getNode()) {
19952 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19953 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19960 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19961 const X86TargetLowering *XTLI) {
19962 SDValue Op0 = N->getOperand(0);
19963 EVT InVT = Op0->getValueType(0);
19965 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19966 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19968 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19969 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19970 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19973 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19974 // a 32-bit target where SSE doesn't support i64->FP operations.
19975 if (Op0.getOpcode() == ISD::LOAD) {
19976 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19977 EVT VT = Ld->getValueType(0);
19978 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19979 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19980 !XTLI->getSubtarget()->is64Bit() &&
19982 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19983 Ld->getChain(), Op0, DAG);
19984 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19991 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19992 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19993 X86TargetLowering::DAGCombinerInfo &DCI) {
19994 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19995 // the result is either zero or one (depending on the input carry bit).
19996 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19997 if (X86::isZeroNode(N->getOperand(0)) &&
19998 X86::isZeroNode(N->getOperand(1)) &&
19999 // We don't have a good way to replace an EFLAGS use, so only do this when
20001 SDValue(N, 1).use_empty()) {
20003 EVT VT = N->getValueType(0);
20004 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20005 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20006 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20007 DAG.getConstant(X86::COND_B,MVT::i8),
20009 DAG.getConstant(1, VT));
20010 return DCI.CombineTo(N, Res1, CarryOut);
20016 // fold (add Y, (sete X, 0)) -> adc 0, Y
20017 // (add Y, (setne X, 0)) -> sbb -1, Y
20018 // (sub (sete X, 0), Y) -> sbb 0, Y
20019 // (sub (setne X, 0), Y) -> adc -1, Y
20020 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20023 // Look through ZExts.
20024 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20025 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20028 SDValue SetCC = Ext.getOperand(0);
20029 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20032 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20033 if (CC != X86::COND_E && CC != X86::COND_NE)
20036 SDValue Cmp = SetCC.getOperand(1);
20037 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20038 !X86::isZeroNode(Cmp.getOperand(1)) ||
20039 !Cmp.getOperand(0).getValueType().isInteger())
20042 SDValue CmpOp0 = Cmp.getOperand(0);
20043 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20044 DAG.getConstant(1, CmpOp0.getValueType()));
20046 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20047 if (CC == X86::COND_NE)
20048 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20049 DL, OtherVal.getValueType(), OtherVal,
20050 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20051 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20052 DL, OtherVal.getValueType(), OtherVal,
20053 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20056 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20057 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20058 const X86Subtarget *Subtarget) {
20059 EVT VT = N->getValueType(0);
20060 SDValue Op0 = N->getOperand(0);
20061 SDValue Op1 = N->getOperand(1);
20063 // Try to synthesize horizontal adds from adds of shuffles.
20064 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20065 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20066 isHorizontalBinOp(Op0, Op1, true))
20067 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20069 return OptimizeConditionalInDecrement(N, DAG);
20072 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20073 const X86Subtarget *Subtarget) {
20074 SDValue Op0 = N->getOperand(0);
20075 SDValue Op1 = N->getOperand(1);
20077 // X86 can't encode an immediate LHS of a sub. See if we can push the
20078 // negation into a preceding instruction.
20079 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20080 // If the RHS of the sub is a XOR with one use and a constant, invert the
20081 // immediate. Then add one to the LHS of the sub so we can turn
20082 // X-Y -> X+~Y+1, saving one register.
20083 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20084 isa<ConstantSDNode>(Op1.getOperand(1))) {
20085 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20086 EVT VT = Op0.getValueType();
20087 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20089 DAG.getConstant(~XorC, VT));
20090 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20091 DAG.getConstant(C->getAPIntValue()+1, VT));
20095 // Try to synthesize horizontal adds from adds of shuffles.
20096 EVT VT = N->getValueType(0);
20097 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20098 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20099 isHorizontalBinOp(Op0, Op1, true))
20100 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20102 return OptimizeConditionalInDecrement(N, DAG);
20105 /// performVZEXTCombine - Performs build vector combines
20106 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20107 TargetLowering::DAGCombinerInfo &DCI,
20108 const X86Subtarget *Subtarget) {
20109 // (vzext (bitcast (vzext (x)) -> (vzext x)
20110 SDValue In = N->getOperand(0);
20111 while (In.getOpcode() == ISD::BITCAST)
20112 In = In.getOperand(0);
20114 if (In.getOpcode() != X86ISD::VZEXT)
20117 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20121 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20122 DAGCombinerInfo &DCI) const {
20123 SelectionDAG &DAG = DCI.DAG;
20124 switch (N->getOpcode()) {
20126 case ISD::EXTRACT_VECTOR_ELT:
20127 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20129 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20130 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20131 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20132 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20133 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20134 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20137 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20138 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20139 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20140 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20141 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20142 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20143 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20144 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20145 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20147 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20149 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20150 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20151 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20152 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20153 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20154 case ISD::ANY_EXTEND:
20155 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20156 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20157 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20158 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20159 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20160 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20161 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20162 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20163 case X86ISD::SHUFP: // Handle all target specific shuffles
20164 case X86ISD::PALIGNR:
20165 case X86ISD::UNPCKH:
20166 case X86ISD::UNPCKL:
20167 case X86ISD::MOVHLPS:
20168 case X86ISD::MOVLHPS:
20169 case X86ISD::PSHUFD:
20170 case X86ISD::PSHUFHW:
20171 case X86ISD::PSHUFLW:
20172 case X86ISD::MOVSS:
20173 case X86ISD::MOVSD:
20174 case X86ISD::VPERMILP:
20175 case X86ISD::VPERM2X128:
20176 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20177 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20183 /// isTypeDesirableForOp - Return true if the target has native support for
20184 /// the specified value type and it is 'desirable' to use the type for the
20185 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20186 /// instruction encodings are longer and some i16 instructions are slow.
20187 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20188 if (!isTypeLegal(VT))
20190 if (VT != MVT::i16)
20197 case ISD::SIGN_EXTEND:
20198 case ISD::ZERO_EXTEND:
20199 case ISD::ANY_EXTEND:
20212 /// IsDesirableToPromoteOp - This method query the target whether it is
20213 /// beneficial for dag combiner to promote the specified node. If true, it
20214 /// should return the desired promotion type by reference.
20215 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20216 EVT VT = Op.getValueType();
20217 if (VT != MVT::i16)
20220 bool Promote = false;
20221 bool Commute = false;
20222 switch (Op.getOpcode()) {
20225 LoadSDNode *LD = cast<LoadSDNode>(Op);
20226 // If the non-extending load has a single use and it's not live out, then it
20227 // might be folded.
20228 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20229 Op.hasOneUse()*/) {
20230 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20231 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20232 // The only case where we'd want to promote LOAD (rather then it being
20233 // promoted as an operand is when it's only use is liveout.
20234 if (UI->getOpcode() != ISD::CopyToReg)
20241 case ISD::SIGN_EXTEND:
20242 case ISD::ZERO_EXTEND:
20243 case ISD::ANY_EXTEND:
20248 SDValue N0 = Op.getOperand(0);
20249 // Look out for (store (shl (load), x)).
20250 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20263 SDValue N0 = Op.getOperand(0);
20264 SDValue N1 = Op.getOperand(1);
20265 if (!Commute && MayFoldLoad(N1))
20267 // Avoid disabling potential load folding opportunities.
20268 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20270 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20280 //===----------------------------------------------------------------------===//
20281 // X86 Inline Assembly Support
20282 //===----------------------------------------------------------------------===//
20285 // Helper to match a string separated by whitespace.
20286 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20287 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20289 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20290 StringRef piece(*args[i]);
20291 if (!s.startswith(piece)) // Check if the piece matches.
20294 s = s.substr(piece.size());
20295 StringRef::size_type pos = s.find_first_not_of(" \t");
20296 if (pos == 0) // We matched a prefix.
20304 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20307 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20309 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20310 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20311 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20312 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20314 if (AsmPieces.size() == 3)
20316 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20323 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20324 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20326 std::string AsmStr = IA->getAsmString();
20328 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20329 if (!Ty || Ty->getBitWidth() % 16 != 0)
20332 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20333 SmallVector<StringRef, 4> AsmPieces;
20334 SplitString(AsmStr, AsmPieces, ";\n");
20336 switch (AsmPieces.size()) {
20337 default: return false;
20339 // FIXME: this should verify that we are targeting a 486 or better. If not,
20340 // we will turn this bswap into something that will be lowered to logical
20341 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20342 // lower so don't worry about this.
20344 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20345 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20346 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20347 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20348 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20349 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20350 // No need to check constraints, nothing other than the equivalent of
20351 // "=r,0" would be valid here.
20352 return IntrinsicLowering::LowerToByteSwap(CI);
20355 // rorw $$8, ${0:w} --> llvm.bswap.i16
20356 if (CI->getType()->isIntegerTy(16) &&
20357 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20358 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20359 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20361 const std::string &ConstraintsStr = IA->getConstraintString();
20362 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20363 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20364 if (clobbersFlagRegisters(AsmPieces))
20365 return IntrinsicLowering::LowerToByteSwap(CI);
20369 if (CI->getType()->isIntegerTy(32) &&
20370 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20371 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20372 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20373 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20375 const std::string &ConstraintsStr = IA->getConstraintString();
20376 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20377 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20378 if (clobbersFlagRegisters(AsmPieces))
20379 return IntrinsicLowering::LowerToByteSwap(CI);
20382 if (CI->getType()->isIntegerTy(64)) {
20383 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20384 if (Constraints.size() >= 2 &&
20385 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20386 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20387 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20388 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20389 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20390 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20391 return IntrinsicLowering::LowerToByteSwap(CI);
20399 /// getConstraintType - Given a constraint letter, return the type of
20400 /// constraint it is for this target.
20401 X86TargetLowering::ConstraintType
20402 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20403 if (Constraint.size() == 1) {
20404 switch (Constraint[0]) {
20415 return C_RegisterClass;
20439 return TargetLowering::getConstraintType(Constraint);
20442 /// Examine constraint type and operand type and determine a weight value.
20443 /// This object must already have been set up with the operand type
20444 /// and the current alternative constraint selected.
20445 TargetLowering::ConstraintWeight
20446 X86TargetLowering::getSingleConstraintMatchWeight(
20447 AsmOperandInfo &info, const char *constraint) const {
20448 ConstraintWeight weight = CW_Invalid;
20449 Value *CallOperandVal = info.CallOperandVal;
20450 // If we don't have a value, we can't do a match,
20451 // but allow it at the lowest weight.
20452 if (!CallOperandVal)
20454 Type *type = CallOperandVal->getType();
20455 // Look at the constraint type.
20456 switch (*constraint) {
20458 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20469 if (CallOperandVal->getType()->isIntegerTy())
20470 weight = CW_SpecificReg;
20475 if (type->isFloatingPointTy())
20476 weight = CW_SpecificReg;
20479 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20480 weight = CW_SpecificReg;
20484 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20485 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20486 weight = CW_Register;
20489 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20490 if (C->getZExtValue() <= 31)
20491 weight = CW_Constant;
20495 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20496 if (C->getZExtValue() <= 63)
20497 weight = CW_Constant;
20501 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20502 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20503 weight = CW_Constant;
20507 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20508 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20509 weight = CW_Constant;
20513 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20514 if (C->getZExtValue() <= 3)
20515 weight = CW_Constant;
20519 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20520 if (C->getZExtValue() <= 0xff)
20521 weight = CW_Constant;
20526 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20527 weight = CW_Constant;
20531 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20532 if ((C->getSExtValue() >= -0x80000000LL) &&
20533 (C->getSExtValue() <= 0x7fffffffLL))
20534 weight = CW_Constant;
20538 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20539 if (C->getZExtValue() <= 0xffffffff)
20540 weight = CW_Constant;
20547 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20548 /// with another that has more specific requirements based on the type of the
20549 /// corresponding operand.
20550 const char *X86TargetLowering::
20551 LowerXConstraint(EVT ConstraintVT) const {
20552 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20553 // 'f' like normal targets.
20554 if (ConstraintVT.isFloatingPoint()) {
20555 if (Subtarget->hasSSE2())
20557 if (Subtarget->hasSSE1())
20561 return TargetLowering::LowerXConstraint(ConstraintVT);
20564 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20565 /// vector. If it is invalid, don't add anything to Ops.
20566 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20567 std::string &Constraint,
20568 std::vector<SDValue>&Ops,
20569 SelectionDAG &DAG) const {
20572 // Only support length 1 constraints for now.
20573 if (Constraint.length() > 1) return;
20575 char ConstraintLetter = Constraint[0];
20576 switch (ConstraintLetter) {
20579 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20580 if (C->getZExtValue() <= 31) {
20581 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20587 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20588 if (C->getZExtValue() <= 63) {
20589 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20595 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20596 if (isInt<8>(C->getSExtValue())) {
20597 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20604 if (C->getZExtValue() <= 255) {
20605 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20611 // 32-bit signed value
20612 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20613 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20614 C->getSExtValue())) {
20615 // Widen to 64 bits here to get it sign extended.
20616 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20619 // FIXME gcc accepts some relocatable values here too, but only in certain
20620 // memory models; it's complicated.
20625 // 32-bit unsigned value
20626 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20627 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20628 C->getZExtValue())) {
20629 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20633 // FIXME gcc accepts some relocatable values here too, but only in certain
20634 // memory models; it's complicated.
20638 // Literal immediates are always ok.
20639 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20640 // Widen to 64 bits here to get it sign extended.
20641 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20645 // In any sort of PIC mode addresses need to be computed at runtime by
20646 // adding in a register or some sort of table lookup. These can't
20647 // be used as immediates.
20648 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20651 // If we are in non-pic codegen mode, we allow the address of a global (with
20652 // an optional displacement) to be used with 'i'.
20653 GlobalAddressSDNode *GA = nullptr;
20654 int64_t Offset = 0;
20656 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20658 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20659 Offset += GA->getOffset();
20661 } else if (Op.getOpcode() == ISD::ADD) {
20662 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20663 Offset += C->getZExtValue();
20664 Op = Op.getOperand(0);
20667 } else if (Op.getOpcode() == ISD::SUB) {
20668 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20669 Offset += -C->getZExtValue();
20670 Op = Op.getOperand(0);
20675 // Otherwise, this isn't something we can handle, reject it.
20679 const GlobalValue *GV = GA->getGlobal();
20680 // If we require an extra load to get this address, as in PIC mode, we
20681 // can't accept it.
20682 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20683 getTargetMachine())))
20686 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20687 GA->getValueType(0), Offset);
20692 if (Result.getNode()) {
20693 Ops.push_back(Result);
20696 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20699 std::pair<unsigned, const TargetRegisterClass*>
20700 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20702 // First, see if this is a constraint that directly corresponds to an LLVM
20704 if (Constraint.size() == 1) {
20705 // GCC Constraint Letters
20706 switch (Constraint[0]) {
20708 // TODO: Slight differences here in allocation order and leaving
20709 // RIP in the class. Do they matter any more here than they do
20710 // in the normal allocation?
20711 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20712 if (Subtarget->is64Bit()) {
20713 if (VT == MVT::i32 || VT == MVT::f32)
20714 return std::make_pair(0U, &X86::GR32RegClass);
20715 if (VT == MVT::i16)
20716 return std::make_pair(0U, &X86::GR16RegClass);
20717 if (VT == MVT::i8 || VT == MVT::i1)
20718 return std::make_pair(0U, &X86::GR8RegClass);
20719 if (VT == MVT::i64 || VT == MVT::f64)
20720 return std::make_pair(0U, &X86::GR64RegClass);
20723 // 32-bit fallthrough
20724 case 'Q': // Q_REGS
20725 if (VT == MVT::i32 || VT == MVT::f32)
20726 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20727 if (VT == MVT::i16)
20728 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20729 if (VT == MVT::i8 || VT == MVT::i1)
20730 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20731 if (VT == MVT::i64)
20732 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20734 case 'r': // GENERAL_REGS
20735 case 'l': // INDEX_REGS
20736 if (VT == MVT::i8 || VT == MVT::i1)
20737 return std::make_pair(0U, &X86::GR8RegClass);
20738 if (VT == MVT::i16)
20739 return std::make_pair(0U, &X86::GR16RegClass);
20740 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20741 return std::make_pair(0U, &X86::GR32RegClass);
20742 return std::make_pair(0U, &X86::GR64RegClass);
20743 case 'R': // LEGACY_REGS
20744 if (VT == MVT::i8 || VT == MVT::i1)
20745 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20746 if (VT == MVT::i16)
20747 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20748 if (VT == MVT::i32 || !Subtarget->is64Bit())
20749 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20750 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20751 case 'f': // FP Stack registers.
20752 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20753 // value to the correct fpstack register class.
20754 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20755 return std::make_pair(0U, &X86::RFP32RegClass);
20756 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20757 return std::make_pair(0U, &X86::RFP64RegClass);
20758 return std::make_pair(0U, &X86::RFP80RegClass);
20759 case 'y': // MMX_REGS if MMX allowed.
20760 if (!Subtarget->hasMMX()) break;
20761 return std::make_pair(0U, &X86::VR64RegClass);
20762 case 'Y': // SSE_REGS if SSE2 allowed
20763 if (!Subtarget->hasSSE2()) break;
20765 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20766 if (!Subtarget->hasSSE1()) break;
20768 switch (VT.SimpleTy) {
20770 // Scalar SSE types.
20773 return std::make_pair(0U, &X86::FR32RegClass);
20776 return std::make_pair(0U, &X86::FR64RegClass);
20784 return std::make_pair(0U, &X86::VR128RegClass);
20792 return std::make_pair(0U, &X86::VR256RegClass);
20797 return std::make_pair(0U, &X86::VR512RegClass);
20803 // Use the default implementation in TargetLowering to convert the register
20804 // constraint into a member of a register class.
20805 std::pair<unsigned, const TargetRegisterClass*> Res;
20806 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20808 // Not found as a standard register?
20810 // Map st(0) -> st(7) -> ST0
20811 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20812 tolower(Constraint[1]) == 's' &&
20813 tolower(Constraint[2]) == 't' &&
20814 Constraint[3] == '(' &&
20815 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20816 Constraint[5] == ')' &&
20817 Constraint[6] == '}') {
20819 Res.first = X86::ST0+Constraint[4]-'0';
20820 Res.second = &X86::RFP80RegClass;
20824 // GCC allows "st(0)" to be called just plain "st".
20825 if (StringRef("{st}").equals_lower(Constraint)) {
20826 Res.first = X86::ST0;
20827 Res.second = &X86::RFP80RegClass;
20832 if (StringRef("{flags}").equals_lower(Constraint)) {
20833 Res.first = X86::EFLAGS;
20834 Res.second = &X86::CCRRegClass;
20838 // 'A' means EAX + EDX.
20839 if (Constraint == "A") {
20840 Res.first = X86::EAX;
20841 Res.second = &X86::GR32_ADRegClass;
20847 // Otherwise, check to see if this is a register class of the wrong value
20848 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20849 // turn into {ax},{dx}.
20850 if (Res.second->hasType(VT))
20851 return Res; // Correct type already, nothing to do.
20853 // All of the single-register GCC register classes map their values onto
20854 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20855 // really want an 8-bit or 32-bit register, map to the appropriate register
20856 // class and return the appropriate register.
20857 if (Res.second == &X86::GR16RegClass) {
20858 if (VT == MVT::i8 || VT == MVT::i1) {
20859 unsigned DestReg = 0;
20860 switch (Res.first) {
20862 case X86::AX: DestReg = X86::AL; break;
20863 case X86::DX: DestReg = X86::DL; break;
20864 case X86::CX: DestReg = X86::CL; break;
20865 case X86::BX: DestReg = X86::BL; break;
20868 Res.first = DestReg;
20869 Res.second = &X86::GR8RegClass;
20871 } else if (VT == MVT::i32 || VT == MVT::f32) {
20872 unsigned DestReg = 0;
20873 switch (Res.first) {
20875 case X86::AX: DestReg = X86::EAX; break;
20876 case X86::DX: DestReg = X86::EDX; break;
20877 case X86::CX: DestReg = X86::ECX; break;
20878 case X86::BX: DestReg = X86::EBX; break;
20879 case X86::SI: DestReg = X86::ESI; break;
20880 case X86::DI: DestReg = X86::EDI; break;
20881 case X86::BP: DestReg = X86::EBP; break;
20882 case X86::SP: DestReg = X86::ESP; break;
20885 Res.first = DestReg;
20886 Res.second = &X86::GR32RegClass;
20888 } else if (VT == MVT::i64 || VT == MVT::f64) {
20889 unsigned DestReg = 0;
20890 switch (Res.first) {
20892 case X86::AX: DestReg = X86::RAX; break;
20893 case X86::DX: DestReg = X86::RDX; break;
20894 case X86::CX: DestReg = X86::RCX; break;
20895 case X86::BX: DestReg = X86::RBX; break;
20896 case X86::SI: DestReg = X86::RSI; break;
20897 case X86::DI: DestReg = X86::RDI; break;
20898 case X86::BP: DestReg = X86::RBP; break;
20899 case X86::SP: DestReg = X86::RSP; break;
20902 Res.first = DestReg;
20903 Res.second = &X86::GR64RegClass;
20906 } else if (Res.second == &X86::FR32RegClass ||
20907 Res.second == &X86::FR64RegClass ||
20908 Res.second == &X86::VR128RegClass ||
20909 Res.second == &X86::VR256RegClass ||
20910 Res.second == &X86::FR32XRegClass ||
20911 Res.second == &X86::FR64XRegClass ||
20912 Res.second == &X86::VR128XRegClass ||
20913 Res.second == &X86::VR256XRegClass ||
20914 Res.second == &X86::VR512RegClass) {
20915 // Handle references to XMM physical registers that got mapped into the
20916 // wrong class. This can happen with constraints like {xmm0} where the
20917 // target independent register mapper will just pick the first match it can
20918 // find, ignoring the required type.
20920 if (VT == MVT::f32 || VT == MVT::i32)
20921 Res.second = &X86::FR32RegClass;
20922 else if (VT == MVT::f64 || VT == MVT::i64)
20923 Res.second = &X86::FR64RegClass;
20924 else if (X86::VR128RegClass.hasType(VT))
20925 Res.second = &X86::VR128RegClass;
20926 else if (X86::VR256RegClass.hasType(VT))
20927 Res.second = &X86::VR256RegClass;
20928 else if (X86::VR512RegClass.hasType(VT))
20929 Res.second = &X86::VR512RegClass;
20935 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20937 // Scaling factors are not free at all.
20938 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20939 // will take 2 allocations in the out of order engine instead of 1
20940 // for plain addressing mode, i.e. inst (reg1).
20942 // vaddps (%rsi,%drx), %ymm0, %ymm1
20943 // Requires two allocations (one for the load, one for the computation)
20945 // vaddps (%rsi), %ymm0, %ymm1
20946 // Requires just 1 allocation, i.e., freeing allocations for other operations
20947 // and having less micro operations to execute.
20949 // For some X86 architectures, this is even worse because for instance for
20950 // stores, the complex addressing mode forces the instruction to use the
20951 // "load" ports instead of the dedicated "store" port.
20952 // E.g., on Haswell:
20953 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
20954 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
20955 if (isLegalAddressingMode(AM, Ty))
20956 // Scale represents reg2 * scale, thus account for 1
20957 // as soon as we use a second register.
20958 return AM.Scale != 0;