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/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 #define DEBUG_TYPE "x86-isel"
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64 SelectionDAG &DAG, SDLoc dl,
65 unsigned vectorWidth) {
66 assert((vectorWidth == 128 || vectorWidth == 256) &&
67 "Unsupported vector width");
68 EVT VT = Vec.getValueType();
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/vectorWidth;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
79 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
81 // This is the index of the first element of the vectorWidth-bit chunk
83 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
86 // If the input is a buildvector just emit a smaller one.
87 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
92 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106 SelectionDAG &DAG, SDLoc dl) {
107 assert((Vec.getValueType().is256BitVector() ||
108 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114 SelectionDAG &DAG, SDLoc dl) {
115 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120 unsigned IdxVal, SelectionDAG &DAG,
121 SDLoc dl, unsigned vectorWidth) {
122 assert((vectorWidth == 128 || vectorWidth == 256) &&
123 "Unsupported vector width");
124 // Inserting UNDEF is Result
125 if (Vec.getOpcode() == ISD::UNDEF)
127 EVT VT = Vec.getValueType();
128 EVT ElVT = VT.getVectorElementType();
129 EVT ResultVT = Result.getValueType();
131 // Insert the relevant vectorWidth bits.
132 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
134 // This is the index of the first element of the vectorWidth-bit chunk
136 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
139 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
143 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference. Idx is an index in the 128 bits
147 /// we want. It need not be aligned to a 128-bit bounday. That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150 unsigned IdxVal, SelectionDAG &DAG,
152 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168 unsigned NumElems, SelectionDAG &DAG,
170 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
181 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
182 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
183 bool is64Bit = Subtarget->is64Bit();
185 if (Subtarget->isTargetMacho()) {
187 return new X86_64MachoTargetObjectFile();
188 return new TargetLoweringObjectFileMachO();
191 if (Subtarget->isTargetLinux())
192 return new X86LinuxTargetObjectFile();
193 if (Subtarget->isTargetELF())
194 return new TargetLoweringObjectFileELF();
195 if (Subtarget->isTargetKnownWindowsMSVC())
196 return new X86WindowsTargetObjectFile();
197 if (Subtarget->isTargetCOFF())
198 return new TargetLoweringObjectFileCOFF();
199 llvm_unreachable("unknown subtarget type");
202 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
203 : TargetLowering(TM, createTLOF(TM)) {
204 Subtarget = &TM.getSubtarget<X86Subtarget>();
205 X86ScalarSSEf64 = Subtarget->hasSSE2();
206 X86ScalarSSEf32 = Subtarget->hasSSE1();
207 TD = getDataLayout();
209 resetOperationActions();
212 void X86TargetLowering::resetOperationActions() {
213 const TargetMachine &TM = getTargetMachine();
214 static bool FirstTimeThrough = true;
216 // If none of the target options have changed, then we don't need to reset the
217 // operation actions.
218 if (!FirstTimeThrough && TO == TM.Options) return;
220 if (!FirstTimeThrough) {
221 // Reinitialize the actions.
223 FirstTimeThrough = false;
228 // Set up the TargetLowering object.
229 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
231 // X86 is weird, it always uses i8 for shift amounts and setcc results.
232 setBooleanContents(ZeroOrOneBooleanContent);
233 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
234 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
236 // For 64-bit since we have so many registers use the ILP scheduler, for
237 // 32-bit code use the register pressure specific scheduling.
238 // For Atom, always use ILP scheduling.
239 if (Subtarget->isAtom())
240 setSchedulingPreference(Sched::ILP);
241 else if (Subtarget->is64Bit())
242 setSchedulingPreference(Sched::ILP);
244 setSchedulingPreference(Sched::RegPressure);
245 const X86RegisterInfo *RegInfo =
246 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
247 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
249 // Bypass expensive divides on Atom when compiling with O2
250 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
251 addBypassSlowDiv(32, 8);
252 if (Subtarget->is64Bit())
253 addBypassSlowDiv(64, 16);
256 if (Subtarget->isTargetKnownWindowsMSVC()) {
257 // Setup Windows compiler runtime calls.
258 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
259 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
260 setLibcallName(RTLIB::SREM_I64, "_allrem");
261 setLibcallName(RTLIB::UREM_I64, "_aullrem");
262 setLibcallName(RTLIB::MUL_I64, "_allmul");
263 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
267 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
269 // The _ftol2 runtime function has an unusual calling conv, which
270 // is modeled by a special pseudo-instruction.
271 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
274 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
277 if (Subtarget->isTargetDarwin()) {
278 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
279 setUseUnderscoreSetJmp(false);
280 setUseUnderscoreLongJmp(false);
281 } else if (Subtarget->isTargetWindowsGNU()) {
282 // MS runtime is weird: it exports _setjmp, but longjmp!
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(false);
286 setUseUnderscoreSetJmp(true);
287 setUseUnderscoreLongJmp(true);
290 // Set up the register classes.
291 addRegisterClass(MVT::i8, &X86::GR8RegClass);
292 addRegisterClass(MVT::i16, &X86::GR16RegClass);
293 addRegisterClass(MVT::i32, &X86::GR32RegClass);
294 if (Subtarget->is64Bit())
295 addRegisterClass(MVT::i64, &X86::GR64RegClass);
297 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
299 // We don't accept any truncstore of integer registers.
300 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
304 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
305 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
307 // SETOEQ and SETUNE require checking two conditions.
308 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
315 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
317 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
319 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
323 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
324 } else if (!TM.Options.UseSoftFloat) {
325 // We have an algorithm for SSE2->double, and we turn this into a
326 // 64-bit FILD followed by conditional FADD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
328 // We have an algorithm for SSE2, and we turn this into a 64-bit
329 // FILD for other targets.
330 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
333 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
335 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
336 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
338 if (!TM.Options.UseSoftFloat) {
339 // SSE has no i16 to fp conversion, only i32
340 if (X86ScalarSSEf32) {
341 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
342 // f32 and f64 cases are Legal, f80 case is not
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
350 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
353 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
354 // are Legal, f80 is custom lowered.
355 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
356 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
358 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
360 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
361 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
363 if (X86ScalarSSEf32) {
364 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
365 // f32 and f64 cases are Legal, f80 case is not
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
369 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
372 // Handle FP_TO_UINT by promoting the destination to a larger signed
374 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
376 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
378 if (Subtarget->is64Bit()) {
379 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
380 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
381 } else if (!TM.Options.UseSoftFloat) {
382 // Since AVX is a superset of SSE3, only check for SSE here.
383 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384 // Expand FP_TO_UINT into a select.
385 // FIXME: We would like to use a Custom expander here eventually to do
386 // the optimal thing for SSE vs. the default expansion in the legalizer.
387 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
389 // With SSE3 we can use fisttpll to convert to a signed i64; without
390 // SSE, we're stuck with a fistpll.
391 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
394 if (isTargetFTOL()) {
395 // Use the _ftol2 runtime function, which has a pseudo-instruction
396 // to handle its weird calling convention.
397 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
400 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401 if (!X86ScalarSSEf64) {
402 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
403 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
404 if (Subtarget->is64Bit()) {
405 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
406 // Without SSE, i64->f64 goes through memory.
407 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
411 // Scalar integer divide and remainder are lowered to use operations that
412 // produce two results, to match the available instructions. This exposes
413 // the two-result form to trivial CSE, which is able to combine x/y and x%y
414 // into a single instruction.
416 // Scalar integer multiply-high is also lowered to use two-result
417 // operations, to match the available instructions. However, plain multiply
418 // (low) operations are left as Legal, as there are single-result
419 // instructions for this in x86. Using the two-result multiply instructions
420 // when both high and low results are needed must be arranged by dagcombine.
421 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
423 setOperationAction(ISD::MULHS, VT, Expand);
424 setOperationAction(ISD::MULHU, VT, Expand);
425 setOperationAction(ISD::SDIV, VT, Expand);
426 setOperationAction(ISD::UDIV, VT, Expand);
427 setOperationAction(ISD::SREM, VT, Expand);
428 setOperationAction(ISD::UREM, VT, Expand);
430 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431 setOperationAction(ISD::ADDC, VT, Custom);
432 setOperationAction(ISD::ADDE, VT, Custom);
433 setOperationAction(ISD::SUBC, VT, Custom);
434 setOperationAction(ISD::SUBE, VT, Custom);
437 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
438 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
439 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
441 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
445 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
447 if (Subtarget->is64Bit())
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
450 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
451 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
452 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
453 setOperationAction(ISD::FREM , MVT::f32 , Expand);
454 setOperationAction(ISD::FREM , MVT::f64 , Expand);
455 setOperationAction(ISD::FREM , MVT::f80 , Expand);
456 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
458 // Promote the i8 variants and force them on up to i32 which has a shorter
460 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
463 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
464 if (Subtarget->hasBMI()) {
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
467 if (Subtarget->is64Bit())
468 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
470 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
471 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
472 if (Subtarget->is64Bit())
473 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
476 if (Subtarget->hasLZCNT()) {
477 // When promoting the i8 variants, force them to i32 for a shorter
479 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
482 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
492 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
494 if (Subtarget->is64Bit()) {
495 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
500 if (Subtarget->hasPOPCNT()) {
501 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
503 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
504 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
505 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
506 if (Subtarget->is64Bit())
507 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
510 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
512 if (!Subtarget->hasMOVBE())
513 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
515 // These should be promoted to a larger select which is supported.
516 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
517 // X86 wants to expand cmov itself.
518 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
519 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
520 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
523 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
530 if (Subtarget->is64Bit()) {
531 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
532 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
534 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
535 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537 // support continuation, user-level threading, and etc.. As a result, no
538 // other SjLj exception interfaces are implemented and please don't build
539 // your own exception handling based on them.
540 // LLVM/Clang supports zero-cost DWARF exception handling.
541 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
545 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
546 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
547 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
549 if (Subtarget->is64Bit())
550 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
551 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
552 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
553 if (Subtarget->is64Bit()) {
554 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
555 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
556 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
557 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
558 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
560 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
561 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
562 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
563 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
566 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
567 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
570 if (Subtarget->hasSSE1())
571 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
573 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
575 // Expand certain atomics
576 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
578 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
579 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
580 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
583 if (!Subtarget->is64Bit()) {
584 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
598 if (Subtarget->hasCmpxchg16b()) {
599 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
602 // FIXME - use subtarget debug flags
603 if (!Subtarget->isTargetDarwin() &&
604 !Subtarget->isTargetELF() &&
605 !Subtarget->isTargetCygMing()) {
606 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
609 if (Subtarget->is64Bit()) {
610 setExceptionPointerRegister(X86::RAX);
611 setExceptionSelectorRegister(X86::RDX);
613 setExceptionPointerRegister(X86::EAX);
614 setExceptionSelectorRegister(X86::EDX);
616 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
617 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
619 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
622 setOperationAction(ISD::TRAP, MVT::Other, Legal);
623 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
625 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
626 setOperationAction(ISD::VASTART , MVT::Other, Custom);
627 setOperationAction(ISD::VAEND , MVT::Other, Expand);
628 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
629 // TargetInfo::X86_64ABIBuiltinVaList
630 setOperationAction(ISD::VAARG , MVT::Other, Custom);
631 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
633 // TargetInfo::CharPtrBuiltinVaList
634 setOperationAction(ISD::VAARG , MVT::Other, Expand);
635 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
638 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
639 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
641 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642 MVT::i64 : MVT::i32, Custom);
644 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645 // f32 and f64 use SSE.
646 // Set up the FP register classes.
647 addRegisterClass(MVT::f32, &X86::FR32RegClass);
648 addRegisterClass(MVT::f64, &X86::FR64RegClass);
650 // Use ANDPD to simulate FABS.
651 setOperationAction(ISD::FABS , MVT::f64, Custom);
652 setOperationAction(ISD::FABS , MVT::f32, Custom);
654 // Use XORP to simulate FNEG.
655 setOperationAction(ISD::FNEG , MVT::f64, Custom);
656 setOperationAction(ISD::FNEG , MVT::f32, Custom);
658 // Use ANDPD and ORPD to simulate FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
662 // Lower this to FGETSIGNx86 plus an AND.
663 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
666 // We don't support sin/cos/fmod
667 setOperationAction(ISD::FSIN , MVT::f64, Expand);
668 setOperationAction(ISD::FCOS , MVT::f64, Expand);
669 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670 setOperationAction(ISD::FSIN , MVT::f32, Expand);
671 setOperationAction(ISD::FCOS , MVT::f32, Expand);
672 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
674 // Expand FP immediates into loads from the stack, except for the special
676 addLegalFPImmediate(APFloat(+0.0)); // xorpd
677 addLegalFPImmediate(APFloat(+0.0f)); // xorps
678 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679 // Use SSE for f32, x87 for f64.
680 // Set up the FP register classes.
681 addRegisterClass(MVT::f32, &X86::FR32RegClass);
682 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
684 // Use ANDPS to simulate FABS.
685 setOperationAction(ISD::FABS , MVT::f32, Custom);
687 // Use XORP to simulate FNEG.
688 setOperationAction(ISD::FNEG , MVT::f32, Custom);
690 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
692 // Use ANDPS and ORPS to simulate FCOPYSIGN.
693 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
696 // We don't support sin/cos/fmod
697 setOperationAction(ISD::FSIN , MVT::f32, Expand);
698 setOperationAction(ISD::FCOS , MVT::f32, Expand);
699 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
701 // Special cases we handle for FP constants.
702 addLegalFPImmediate(APFloat(+0.0f)); // xorps
703 addLegalFPImmediate(APFloat(+0.0)); // FLD0
704 addLegalFPImmediate(APFloat(+1.0)); // FLD1
705 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
708 if (!TM.Options.UnsafeFPMath) {
709 setOperationAction(ISD::FSIN , MVT::f64, Expand);
710 setOperationAction(ISD::FCOS , MVT::f64, Expand);
711 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
713 } else if (!TM.Options.UseSoftFloat) {
714 // f32 and f64 in x87.
715 // Set up the FP register classes.
716 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
719 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
720 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
721 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
724 if (!TM.Options.UnsafeFPMath) {
725 setOperationAction(ISD::FSIN , MVT::f64, Expand);
726 setOperationAction(ISD::FSIN , MVT::f32, Expand);
727 setOperationAction(ISD::FCOS , MVT::f64, Expand);
728 setOperationAction(ISD::FCOS , MVT::f32, Expand);
729 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
732 addLegalFPImmediate(APFloat(+0.0)); // FLD0
733 addLegalFPImmediate(APFloat(+1.0)); // FLD1
734 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
742 // We don't support FMA.
743 setOperationAction(ISD::FMA, MVT::f64, Expand);
744 setOperationAction(ISD::FMA, MVT::f32, Expand);
746 // Long double always uses X87.
747 if (!TM.Options.UseSoftFloat) {
748 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
750 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
752 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753 addLegalFPImmediate(TmpFlt); // FLD0
755 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
758 APFloat TmpFlt2(+1.0);
759 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
761 addLegalFPImmediate(TmpFlt2); // FLD1
762 TmpFlt2.changeSign();
763 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
766 if (!TM.Options.UnsafeFPMath) {
767 setOperationAction(ISD::FSIN , MVT::f80, Expand);
768 setOperationAction(ISD::FCOS , MVT::f80, Expand);
769 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
772 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
774 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775 setOperationAction(ISD::FRINT, MVT::f80, Expand);
776 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777 setOperationAction(ISD::FMA, MVT::f80, Expand);
780 // Always use a library call for pow.
781 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
782 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
783 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
785 setOperationAction(ISD::FLOG, MVT::f80, Expand);
786 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788 setOperationAction(ISD::FEXP, MVT::f80, Expand);
789 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
791 // First set operation action for all vector types to either promote
792 // (for widening) or expand (for scalarization). Then we will selectively
793 // turn on ones that can be effectively codegen'd.
794 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796 MVT VT = (MVT::SimpleValueType)i;
797 setOperationAction(ISD::ADD , VT, Expand);
798 setOperationAction(ISD::SUB , VT, Expand);
799 setOperationAction(ISD::FADD, VT, Expand);
800 setOperationAction(ISD::FNEG, VT, Expand);
801 setOperationAction(ISD::FSUB, VT, Expand);
802 setOperationAction(ISD::MUL , VT, Expand);
803 setOperationAction(ISD::FMUL, VT, Expand);
804 setOperationAction(ISD::SDIV, VT, Expand);
805 setOperationAction(ISD::UDIV, VT, Expand);
806 setOperationAction(ISD::FDIV, VT, Expand);
807 setOperationAction(ISD::SREM, VT, Expand);
808 setOperationAction(ISD::UREM, VT, Expand);
809 setOperationAction(ISD::LOAD, VT, Expand);
810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815 setOperationAction(ISD::FABS, VT, Expand);
816 setOperationAction(ISD::FSIN, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FCOS, VT, Expand);
819 setOperationAction(ISD::FSINCOS, VT, Expand);
820 setOperationAction(ISD::FREM, VT, Expand);
821 setOperationAction(ISD::FMA, VT, Expand);
822 setOperationAction(ISD::FPOWI, VT, Expand);
823 setOperationAction(ISD::FSQRT, VT, Expand);
824 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825 setOperationAction(ISD::FFLOOR, VT, Expand);
826 setOperationAction(ISD::FCEIL, VT, Expand);
827 setOperationAction(ISD::FTRUNC, VT, Expand);
828 setOperationAction(ISD::FRINT, VT, Expand);
829 setOperationAction(ISD::FNEARBYINT, VT, Expand);
830 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::MULHS, VT, Expand);
832 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833 setOperationAction(ISD::MULHU, VT, Expand);
834 setOperationAction(ISD::SDIVREM, VT, Expand);
835 setOperationAction(ISD::UDIVREM, VT, Expand);
836 setOperationAction(ISD::FPOW, VT, Expand);
837 setOperationAction(ISD::CTPOP, VT, Expand);
838 setOperationAction(ISD::CTTZ, VT, Expand);
839 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::CTLZ, VT, Expand);
841 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::SHL, VT, Expand);
843 setOperationAction(ISD::SRA, VT, Expand);
844 setOperationAction(ISD::SRL, VT, Expand);
845 setOperationAction(ISD::ROTL, VT, Expand);
846 setOperationAction(ISD::ROTR, VT, Expand);
847 setOperationAction(ISD::BSWAP, VT, Expand);
848 setOperationAction(ISD::SETCC, VT, Expand);
849 setOperationAction(ISD::FLOG, VT, Expand);
850 setOperationAction(ISD::FLOG2, VT, Expand);
851 setOperationAction(ISD::FLOG10, VT, Expand);
852 setOperationAction(ISD::FEXP, VT, Expand);
853 setOperationAction(ISD::FEXP2, VT, Expand);
854 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859 setOperationAction(ISD::TRUNCATE, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863 setOperationAction(ISD::VSELECT, VT, Expand);
864 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866 setTruncStoreAction(VT,
867 (MVT::SimpleValueType)InnerVT, Expand);
868 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
873 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874 // with -msoft-float, disable use of MMX as well.
875 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877 // No operations on x86mmx supported, everything uses intrinsics.
880 // MMX-sized vectors (other than x86mmx) are expected to be expanded
881 // into smaller operations.
882 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
883 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
884 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
885 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
886 setOperationAction(ISD::AND, MVT::v8i8, Expand);
887 setOperationAction(ISD::AND, MVT::v4i16, Expand);
888 setOperationAction(ISD::AND, MVT::v2i32, Expand);
889 setOperationAction(ISD::AND, MVT::v1i64, Expand);
890 setOperationAction(ISD::OR, MVT::v8i8, Expand);
891 setOperationAction(ISD::OR, MVT::v4i16, Expand);
892 setOperationAction(ISD::OR, MVT::v2i32, Expand);
893 setOperationAction(ISD::OR, MVT::v1i64, Expand);
894 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
895 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
896 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
897 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
902 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
903 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
904 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
905 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
906 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
912 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
915 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
916 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
917 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
918 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
919 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
920 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
921 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
922 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
923 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
924 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
929 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
932 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933 // registers cannot be used even for integer operations.
934 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
939 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
940 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
941 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
942 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
943 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
944 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
945 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
946 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
947 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
948 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
949 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
950 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
951 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
952 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
953 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
954 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
956 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
957 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
958 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
959 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
960 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
962 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
963 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
964 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
965 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
967 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
968 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
970 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
971 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
973 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
974 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
975 MVT VT = (MVT::SimpleValueType)i;
976 // Do not attempt to custom lower non-power-of-2 vectors
977 if (!isPowerOf2_32(VT.getVectorNumElements()))
979 // Do not attempt to custom lower non-128-bit vectors
980 if (!VT.is128BitVector())
982 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
983 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
984 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
987 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
988 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
990 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
994 if (Subtarget->is64Bit()) {
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
999 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1000 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to promote non-128-bit vectors
1004 if (!VT.is128BitVector())
1007 setOperationAction(ISD::AND, VT, Promote);
1008 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1009 setOperationAction(ISD::OR, VT, Promote);
1010 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1011 setOperationAction(ISD::XOR, VT, Promote);
1012 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1013 setOperationAction(ISD::LOAD, VT, Promote);
1014 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1015 setOperationAction(ISD::SELECT, VT, Promote);
1016 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1019 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1021 // Custom lower v2i64 and v2f64 selects.
1022 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1023 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1024 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1025 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1027 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1028 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1031 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1032 // As there is no 64-bit GPR available, we need build a special custom
1033 // sequence to convert from v2i32 to v2f32.
1034 if (!Subtarget->is64Bit())
1035 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1037 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1038 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1040 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1042 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1045 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1046 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1047 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1048 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1049 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1050 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1051 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1052 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1053 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1054 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1055 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1060 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1062 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1064 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1065 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1066 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1068 // FIXME: Do we need to handle scalar-to-vector here?
1069 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1073 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1074 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1075 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1077 // i8 and i16 vectors are custom , because the source register and source
1078 // source memory operand types are not the same width. f32 vectors are
1079 // custom since the immediate controlling the insert encodes additional
1081 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1082 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1083 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1086 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1088 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1089 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1091 // FIXME: these should be Legal but thats only for the case where
1092 // the index is constant. For now custom expand to deal with that.
1093 if (Subtarget->is64Bit()) {
1094 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1095 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1099 if (Subtarget->hasSSE2()) {
1100 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1101 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1103 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1104 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1106 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1107 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1109 // In the customized shift lowering, the legal cases in AVX2 will be
1111 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1112 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1114 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1115 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1117 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1120 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1121 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1126 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1128 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1129 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1130 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1132 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1143 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1145 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1156 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1158 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1159 // even though v8i16 is a legal type.
1160 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1161 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1162 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1164 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1165 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1166 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1168 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1169 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1171 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1173 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1174 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1176 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1179 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1184 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1187 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1188 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1189 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1191 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1192 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1193 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1194 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1196 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1198 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1199 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1200 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1201 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1202 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1203 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1204 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1205 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1206 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1207 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1209 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1210 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1211 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1212 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1213 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1214 setOperationAction(ISD::FMA, MVT::f32, Legal);
1215 setOperationAction(ISD::FMA, MVT::f64, Legal);
1218 if (Subtarget->hasInt256()) {
1219 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1220 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1221 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1222 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1224 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1225 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1226 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1227 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1229 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1230 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1231 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1232 // Don't lower v32i8 because there is no 128-bit byte mul
1234 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1235 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1236 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1237 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1239 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1241 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1242 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1243 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1244 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1246 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1247 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1248 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1249 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1251 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1253 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1254 // Don't lower v32i8 because there is no 128-bit byte mul
1257 // In the customized shift lowering, the legal cases in AVX2 will be
1259 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1260 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1262 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1263 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1265 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1267 // Custom lower several nodes for 256-bit types.
1268 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1269 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1270 MVT VT = (MVT::SimpleValueType)i;
1272 // Extract subvector is special because the value type
1273 // (result) is 128-bit but the source is 256-bit wide.
1274 if (VT.is128BitVector())
1275 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1277 // Do not attempt to custom lower other non-256-bit vectors
1278 if (!VT.is256BitVector())
1281 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1282 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1283 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1284 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1286 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1287 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1290 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1291 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1292 MVT VT = (MVT::SimpleValueType)i;
1294 // Do not attempt to promote non-256-bit vectors
1295 if (!VT.is256BitVector())
1298 setOperationAction(ISD::AND, VT, Promote);
1299 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1300 setOperationAction(ISD::OR, VT, Promote);
1301 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1302 setOperationAction(ISD::XOR, VT, Promote);
1303 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1304 setOperationAction(ISD::LOAD, VT, Promote);
1305 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1306 setOperationAction(ISD::SELECT, VT, Promote);
1307 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1311 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1312 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1314 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1315 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1317 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1318 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1319 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1321 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1322 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1323 setOperationAction(ISD::XOR, MVT::i1, Legal);
1324 setOperationAction(ISD::OR, MVT::i1, Legal);
1325 setOperationAction(ISD::AND, MVT::i1, Legal);
1326 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1328 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1329 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1330 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1331 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1333 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1336 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1337 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1338 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1340 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1344 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1346 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1347 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1349 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1350 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1351 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1352 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1353 if (Subtarget->is64Bit()) {
1354 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1355 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1359 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1361 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1362 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1363 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1364 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1365 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1366 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1367 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1368 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1370 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1373 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1374 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1375 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1376 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1377 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1380 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1381 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1382 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1389 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1391 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1392 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1394 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1400 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1401 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1402 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1403 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1404 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1406 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1407 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1409 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1410 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1412 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1414 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1415 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1417 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1418 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1420 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1421 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1423 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1424 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1425 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1426 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1427 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1428 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1430 // Custom lower several nodes.
1431 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1432 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1433 MVT VT = (MVT::SimpleValueType)i;
1435 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1436 // Extract subvector is special because the value type
1437 // (result) is 256/128-bit but the source is 512-bit wide.
1438 if (VT.is128BitVector() || VT.is256BitVector())
1439 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1441 if (VT.getVectorElementType() == MVT::i1)
1442 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1444 // Do not attempt to custom lower other non-512-bit vectors
1445 if (!VT.is512BitVector())
1448 if ( EltSize >= 32) {
1449 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1450 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1451 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1452 setOperationAction(ISD::VSELECT, VT, Legal);
1453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1454 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1455 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1458 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1459 MVT VT = (MVT::SimpleValueType)i;
1461 // Do not attempt to promote non-256-bit vectors
1462 if (!VT.is512BitVector())
1465 setOperationAction(ISD::SELECT, VT, Promote);
1466 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1470 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1471 // of this type with custom code.
1472 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1473 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1474 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1478 // We want to custom lower some of our intrinsics.
1479 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1480 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1481 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1482 if (!Subtarget->is64Bit())
1483 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1485 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1486 // handle type legalization for these operations here.
1488 // FIXME: We really should do custom legalization for addition and
1489 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1490 // than generic legalization for 64-bit multiplication-with-overflow, though.
1491 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1492 // Add/Sub/Mul with overflow operations are custom lowered.
1494 setOperationAction(ISD::SADDO, VT, Custom);
1495 setOperationAction(ISD::UADDO, VT, Custom);
1496 setOperationAction(ISD::SSUBO, VT, Custom);
1497 setOperationAction(ISD::USUBO, VT, Custom);
1498 setOperationAction(ISD::SMULO, VT, Custom);
1499 setOperationAction(ISD::UMULO, VT, Custom);
1502 // There are no 8-bit 3-address imul/mul instructions
1503 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1504 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1506 if (!Subtarget->is64Bit()) {
1507 // These libcalls are not available in 32-bit.
1508 setLibcallName(RTLIB::SHL_I128, nullptr);
1509 setLibcallName(RTLIB::SRL_I128, nullptr);
1510 setLibcallName(RTLIB::SRA_I128, nullptr);
1513 // Combine sin / cos into one node or libcall if possible.
1514 if (Subtarget->hasSinCos()) {
1515 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1516 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1517 if (Subtarget->isTargetDarwin()) {
1518 // For MacOSX, we don't want to the normal expansion of a libcall to
1519 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1521 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1522 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1526 if (Subtarget->isTargetWin64()) {
1527 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1528 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1529 setOperationAction(ISD::SREM, MVT::i128, Custom);
1530 setOperationAction(ISD::UREM, MVT::i128, Custom);
1531 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1532 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1535 // We have target-specific dag combine patterns for the following nodes:
1536 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1537 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1538 setTargetDAGCombine(ISD::VSELECT);
1539 setTargetDAGCombine(ISD::SELECT);
1540 setTargetDAGCombine(ISD::SHL);
1541 setTargetDAGCombine(ISD::SRA);
1542 setTargetDAGCombine(ISD::SRL);
1543 setTargetDAGCombine(ISD::OR);
1544 setTargetDAGCombine(ISD::AND);
1545 setTargetDAGCombine(ISD::ADD);
1546 setTargetDAGCombine(ISD::FADD);
1547 setTargetDAGCombine(ISD::FSUB);
1548 setTargetDAGCombine(ISD::FMA);
1549 setTargetDAGCombine(ISD::SUB);
1550 setTargetDAGCombine(ISD::LOAD);
1551 setTargetDAGCombine(ISD::STORE);
1552 setTargetDAGCombine(ISD::ZERO_EXTEND);
1553 setTargetDAGCombine(ISD::ANY_EXTEND);
1554 setTargetDAGCombine(ISD::SIGN_EXTEND);
1555 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1556 setTargetDAGCombine(ISD::TRUNCATE);
1557 setTargetDAGCombine(ISD::SINT_TO_FP);
1558 setTargetDAGCombine(ISD::SETCC);
1559 if (Subtarget->is64Bit())
1560 setTargetDAGCombine(ISD::MUL);
1561 setTargetDAGCombine(ISD::XOR);
1563 computeRegisterProperties();
1565 // On Darwin, -Os means optimize for size without hurting performance,
1566 // do not reduce the limit.
1567 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1568 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1569 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1570 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1571 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1572 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1573 setPrefLoopAlignment(4); // 2^4 bytes.
1575 // Predictable cmov don't hurt on atom because it's in-order.
1576 PredictableSelectIsExpensive = !Subtarget->isAtom();
1578 setPrefFunctionAlignment(4); // 2^4 bytes.
1581 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1583 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1585 if (Subtarget->hasAVX512())
1586 switch(VT.getVectorNumElements()) {
1587 case 8: return MVT::v8i1;
1588 case 16: return MVT::v16i1;
1591 return VT.changeVectorElementTypeToInteger();
1594 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1595 /// the desired ByVal argument alignment.
1596 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1599 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1600 if (VTy->getBitWidth() == 128)
1602 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1603 unsigned EltAlign = 0;
1604 getMaxByValAlign(ATy->getElementType(), EltAlign);
1605 if (EltAlign > MaxAlign)
1606 MaxAlign = EltAlign;
1607 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1608 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1609 unsigned EltAlign = 0;
1610 getMaxByValAlign(STy->getElementType(i), EltAlign);
1611 if (EltAlign > MaxAlign)
1612 MaxAlign = EltAlign;
1619 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1620 /// function arguments in the caller parameter area. For X86, aggregates
1621 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1622 /// are at 4-byte boundaries.
1623 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1624 if (Subtarget->is64Bit()) {
1625 // Max of 8 and alignment of type.
1626 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1633 if (Subtarget->hasSSE1())
1634 getMaxByValAlign(Ty, Align);
1638 /// getOptimalMemOpType - Returns the target specific optimal type for load
1639 /// and store operations as a result of memset, memcpy, and memmove
1640 /// lowering. If DstAlign is zero that means it's safe to destination
1641 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1642 /// means there isn't a need to check it against alignment requirement,
1643 /// probably because the source does not need to be loaded. If 'IsMemset' is
1644 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1645 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1646 /// source is constant so it does not need to be loaded.
1647 /// It returns EVT::Other if the type should be determined using generic
1648 /// target-independent logic.
1650 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1651 unsigned DstAlign, unsigned SrcAlign,
1652 bool IsMemset, bool ZeroMemset,
1654 MachineFunction &MF) const {
1655 const Function *F = MF.getFunction();
1656 if ((!IsMemset || ZeroMemset) &&
1657 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1658 Attribute::NoImplicitFloat)) {
1660 (Subtarget->isUnalignedMemAccessFast() ||
1661 ((DstAlign == 0 || DstAlign >= 16) &&
1662 (SrcAlign == 0 || SrcAlign >= 16)))) {
1664 if (Subtarget->hasInt256())
1666 if (Subtarget->hasFp256())
1669 if (Subtarget->hasSSE2())
1671 if (Subtarget->hasSSE1())
1673 } else if (!MemcpyStrSrc && Size >= 8 &&
1674 !Subtarget->is64Bit() &&
1675 Subtarget->hasSSE2()) {
1676 // Do not use f64 to lower memcpy if source is string constant. It's
1677 // better to use i32 to avoid the loads.
1681 if (Subtarget->is64Bit() && Size >= 8)
1686 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1688 return X86ScalarSSEf32;
1689 else if (VT == MVT::f64)
1690 return X86ScalarSSEf64;
1695 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1699 *Fast = Subtarget->isUnalignedMemAccessFast();
1703 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1704 /// current function. The returned value is a member of the
1705 /// MachineJumpTableInfo::JTEntryKind enum.
1706 unsigned X86TargetLowering::getJumpTableEncoding() const {
1707 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1709 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1710 Subtarget->isPICStyleGOT())
1711 return MachineJumpTableInfo::EK_Custom32;
1713 // Otherwise, use the normal jump table encoding heuristics.
1714 return TargetLowering::getJumpTableEncoding();
1718 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1719 const MachineBasicBlock *MBB,
1720 unsigned uid,MCContext &Ctx) const{
1721 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1722 Subtarget->isPICStyleGOT());
1723 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1725 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1726 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1729 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1731 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1732 SelectionDAG &DAG) const {
1733 if (!Subtarget->is64Bit())
1734 // This doesn't have SDLoc associated with it, but is not really the
1735 // same as a Register.
1736 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1740 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1741 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1743 const MCExpr *X86TargetLowering::
1744 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1745 MCContext &Ctx) const {
1746 // X86-64 uses RIP relative addressing based on the jump table label.
1747 if (Subtarget->isPICStyleRIPRel())
1748 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1750 // Otherwise, the reference is relative to the PIC base.
1751 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1754 // FIXME: Why this routine is here? Move to RegInfo!
1755 std::pair<const TargetRegisterClass*, uint8_t>
1756 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1757 const TargetRegisterClass *RRC = nullptr;
1759 switch (VT.SimpleTy) {
1761 return TargetLowering::findRepresentativeClass(VT);
1762 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1763 RRC = Subtarget->is64Bit() ?
1764 (const TargetRegisterClass*)&X86::GR64RegClass :
1765 (const TargetRegisterClass*)&X86::GR32RegClass;
1768 RRC = &X86::VR64RegClass;
1770 case MVT::f32: case MVT::f64:
1771 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1772 case MVT::v4f32: case MVT::v2f64:
1773 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1775 RRC = &X86::VR128RegClass;
1778 return std::make_pair(RRC, Cost);
1781 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1782 unsigned &Offset) const {
1783 if (!Subtarget->isTargetLinux())
1786 if (Subtarget->is64Bit()) {
1787 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1789 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1801 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1802 unsigned DestAS) const {
1803 assert(SrcAS != DestAS && "Expected different address spaces!");
1805 return SrcAS < 256 && DestAS < 256;
1808 //===----------------------------------------------------------------------===//
1809 // Return Value Calling Convention Implementation
1810 //===----------------------------------------------------------------------===//
1812 #include "X86GenCallingConv.inc"
1815 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1816 MachineFunction &MF, bool isVarArg,
1817 const SmallVectorImpl<ISD::OutputArg> &Outs,
1818 LLVMContext &Context) const {
1819 SmallVector<CCValAssign, 16> RVLocs;
1820 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1822 return CCInfo.CheckReturn(Outs, RetCC_X86);
1825 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1826 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1831 X86TargetLowering::LowerReturn(SDValue Chain,
1832 CallingConv::ID CallConv, bool isVarArg,
1833 const SmallVectorImpl<ISD::OutputArg> &Outs,
1834 const SmallVectorImpl<SDValue> &OutVals,
1835 SDLoc dl, SelectionDAG &DAG) const {
1836 MachineFunction &MF = DAG.getMachineFunction();
1837 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1839 SmallVector<CCValAssign, 16> RVLocs;
1840 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1841 RVLocs, *DAG.getContext());
1842 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1845 SmallVector<SDValue, 6> RetOps;
1846 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1847 // Operand #1 = Bytes To Pop
1848 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1851 // Copy the result values into the output registers.
1852 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1853 CCValAssign &VA = RVLocs[i];
1854 assert(VA.isRegLoc() && "Can only return in registers!");
1855 SDValue ValToCopy = OutVals[i];
1856 EVT ValVT = ValToCopy.getValueType();
1858 // Promote values to the appropriate types
1859 if (VA.getLocInfo() == CCValAssign::SExt)
1860 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1861 else if (VA.getLocInfo() == CCValAssign::ZExt)
1862 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1863 else if (VA.getLocInfo() == CCValAssign::AExt)
1864 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1865 else if (VA.getLocInfo() == CCValAssign::BCvt)
1866 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1868 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1869 "Unexpected FP-extend for return value.");
1871 // If this is x86-64, and we disabled SSE, we can't return FP values,
1872 // or SSE or MMX vectors.
1873 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1874 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1875 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1876 report_fatal_error("SSE register return with SSE disabled");
1878 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1879 // llvm-gcc has never done it right and no one has noticed, so this
1880 // should be OK for now.
1881 if (ValVT == MVT::f64 &&
1882 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1883 report_fatal_error("SSE2 register return with SSE2 disabled");
1885 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1886 // the RET instruction and handled by the FP Stackifier.
1887 if (VA.getLocReg() == X86::ST0 ||
1888 VA.getLocReg() == X86::ST1) {
1889 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1890 // change the value to the FP stack register class.
1891 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1892 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1893 RetOps.push_back(ValToCopy);
1894 // Don't emit a copytoreg.
1898 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1899 // which is returned in RAX / RDX.
1900 if (Subtarget->is64Bit()) {
1901 if (ValVT == MVT::x86mmx) {
1902 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1903 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1904 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1906 // If we don't have SSE2 available, convert to v4f32 so the generated
1907 // register is legal.
1908 if (!Subtarget->hasSSE2())
1909 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1914 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1915 Flag = Chain.getValue(1);
1916 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1919 // The x86-64 ABIs require that for returning structs by value we copy
1920 // the sret argument into %rax/%eax (depending on ABI) for the return.
1921 // Win32 requires us to put the sret argument to %eax as well.
1922 // We saved the argument into a virtual register in the entry block,
1923 // so now we copy the value out and into %rax/%eax.
1924 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1925 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1926 MachineFunction &MF = DAG.getMachineFunction();
1927 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1928 unsigned Reg = FuncInfo->getSRetReturnReg();
1930 "SRetReturnReg should have been set in LowerFormalArguments().");
1931 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1934 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1935 X86::RAX : X86::EAX;
1936 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1937 Flag = Chain.getValue(1);
1939 // RAX/EAX now acts like a return value.
1940 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1943 RetOps[0] = Chain; // Update chain.
1945 // Add the flag if we have it.
1947 RetOps.push_back(Flag);
1949 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1952 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1953 if (N->getNumValues() != 1)
1955 if (!N->hasNUsesOfValue(1, 0))
1958 SDValue TCChain = Chain;
1959 SDNode *Copy = *N->use_begin();
1960 if (Copy->getOpcode() == ISD::CopyToReg) {
1961 // If the copy has a glue operand, we conservatively assume it isn't safe to
1962 // perform a tail call.
1963 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1965 TCChain = Copy->getOperand(0);
1966 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1969 bool HasRet = false;
1970 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1972 if (UI->getOpcode() != X86ISD::RET_FLAG)
1985 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1986 ISD::NodeType ExtendKind) const {
1988 // TODO: Is this also valid on 32-bit?
1989 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1990 ReturnMVT = MVT::i8;
1992 ReturnMVT = MVT::i32;
1994 MVT MinVT = getRegisterType(ReturnMVT);
1995 return VT.bitsLT(MinVT) ? MinVT : VT;
1998 /// LowerCallResult - Lower the result values of a call into the
1999 /// appropriate copies out of appropriate physical registers.
2002 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2003 CallingConv::ID CallConv, bool isVarArg,
2004 const SmallVectorImpl<ISD::InputArg> &Ins,
2005 SDLoc dl, SelectionDAG &DAG,
2006 SmallVectorImpl<SDValue> &InVals) const {
2008 // Assign locations to each value returned by this call.
2009 SmallVector<CCValAssign, 16> RVLocs;
2010 bool Is64Bit = Subtarget->is64Bit();
2011 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2012 getTargetMachine(), RVLocs, *DAG.getContext());
2013 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2015 // Copy all of the result registers out of their specified physreg.
2016 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2017 CCValAssign &VA = RVLocs[i];
2018 EVT CopyVT = VA.getValVT();
2020 // If this is x86-64, and we disabled SSE, we can't return FP values
2021 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2022 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2023 report_fatal_error("SSE register return with SSE disabled");
2028 // If this is a call to a function that returns an fp value on the floating
2029 // point stack, we must guarantee the value is popped from the stack, so
2030 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2031 // if the return value is not used. We use the FpPOP_RETVAL instruction
2033 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2034 // If we prefer to use the value in xmm registers, copy it out as f80 and
2035 // use a truncate to move it from fp stack reg to xmm reg.
2036 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2037 SDValue Ops[] = { Chain, InFlag };
2038 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2039 MVT::Other, MVT::Glue, Ops), 1);
2040 Val = Chain.getValue(0);
2042 // Round the f80 to the right size, which also moves it to the appropriate
2044 if (CopyVT != VA.getValVT())
2045 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2046 // This truncation won't change the value.
2047 DAG.getIntPtrConstant(1));
2049 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2050 CopyVT, InFlag).getValue(1);
2051 Val = Chain.getValue(0);
2053 InFlag = Chain.getValue(2);
2054 InVals.push_back(Val);
2060 //===----------------------------------------------------------------------===//
2061 // C & StdCall & Fast Calling Convention implementation
2062 //===----------------------------------------------------------------------===//
2063 // StdCall calling convention seems to be standard for many Windows' API
2064 // routines and around. It differs from C calling convention just a little:
2065 // callee should clean up the stack, not caller. Symbols should be also
2066 // decorated in some fancy way :) It doesn't support any vector arguments.
2067 // For info on fast calling convention see Fast Calling Convention (tail call)
2068 // implementation LowerX86_32FastCCCallTo.
2070 /// CallIsStructReturn - Determines whether a call uses struct return
2072 enum StructReturnType {
2077 static StructReturnType
2078 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2080 return NotStructReturn;
2082 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2083 if (!Flags.isSRet())
2084 return NotStructReturn;
2085 if (Flags.isInReg())
2086 return RegStructReturn;
2087 return StackStructReturn;
2090 /// ArgsAreStructReturn - Determines whether a function uses struct
2091 /// return semantics.
2092 static StructReturnType
2093 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2095 return NotStructReturn;
2097 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2098 if (!Flags.isSRet())
2099 return NotStructReturn;
2100 if (Flags.isInReg())
2101 return RegStructReturn;
2102 return StackStructReturn;
2105 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2106 /// by "Src" to address "Dst" with size and alignment information specified by
2107 /// the specific parameter attribute. The copy will be passed as a byval
2108 /// function parameter.
2110 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2111 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2113 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2115 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2116 /*isVolatile*/false, /*AlwaysInline=*/true,
2117 MachinePointerInfo(), MachinePointerInfo());
2120 /// IsTailCallConvention - Return true if the calling convention is one that
2121 /// supports tail call optimization.
2122 static bool IsTailCallConvention(CallingConv::ID CC) {
2123 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2124 CC == CallingConv::HiPE);
2127 /// \brief Return true if the calling convention is a C calling convention.
2128 static bool IsCCallConvention(CallingConv::ID CC) {
2129 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2130 CC == CallingConv::X86_64_SysV);
2133 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2134 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2138 CallingConv::ID CalleeCC = CS.getCallingConv();
2139 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2145 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2146 /// a tailcall target by changing its ABI.
2147 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2148 bool GuaranteedTailCallOpt) {
2149 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2153 X86TargetLowering::LowerMemArgument(SDValue Chain,
2154 CallingConv::ID CallConv,
2155 const SmallVectorImpl<ISD::InputArg> &Ins,
2156 SDLoc dl, SelectionDAG &DAG,
2157 const CCValAssign &VA,
2158 MachineFrameInfo *MFI,
2160 // Create the nodes corresponding to a load from this parameter slot.
2161 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2162 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2163 getTargetMachine().Options.GuaranteedTailCallOpt);
2164 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2167 // If value is passed by pointer we have address passed instead of the value
2169 if (VA.getLocInfo() == CCValAssign::Indirect)
2170 ValVT = VA.getLocVT();
2172 ValVT = VA.getValVT();
2174 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2175 // changed with more analysis.
2176 // In case of tail call optimization mark all arguments mutable. Since they
2177 // could be overwritten by lowering of arguments in case of a tail call.
2178 if (Flags.isByVal()) {
2179 unsigned Bytes = Flags.getByValSize();
2180 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2181 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2182 return DAG.getFrameIndex(FI, getPointerTy());
2184 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2185 VA.getLocMemOffset(), isImmutable);
2186 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2187 return DAG.getLoad(ValVT, dl, Chain, FIN,
2188 MachinePointerInfo::getFixedStack(FI),
2189 false, false, false, 0);
2194 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2195 CallingConv::ID CallConv,
2197 const SmallVectorImpl<ISD::InputArg> &Ins,
2200 SmallVectorImpl<SDValue> &InVals)
2202 MachineFunction &MF = DAG.getMachineFunction();
2203 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2205 const Function* Fn = MF.getFunction();
2206 if (Fn->hasExternalLinkage() &&
2207 Subtarget->isTargetCygMing() &&
2208 Fn->getName() == "main")
2209 FuncInfo->setForceFramePointer(true);
2211 MachineFrameInfo *MFI = MF.getFrameInfo();
2212 bool Is64Bit = Subtarget->is64Bit();
2213 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2215 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2216 "Var args not supported with calling convention fastcc, ghc or hipe");
2218 // Assign locations to all of the incoming arguments.
2219 SmallVector<CCValAssign, 16> ArgLocs;
2220 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2221 ArgLocs, *DAG.getContext());
2223 // Allocate shadow area for Win64
2225 CCInfo.AllocateStack(32, 8);
2227 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2229 unsigned LastVal = ~0U;
2231 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2232 CCValAssign &VA = ArgLocs[i];
2233 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2235 assert(VA.getValNo() != LastVal &&
2236 "Don't support value assigned to multiple locs yet");
2238 LastVal = VA.getValNo();
2240 if (VA.isRegLoc()) {
2241 EVT RegVT = VA.getLocVT();
2242 const TargetRegisterClass *RC;
2243 if (RegVT == MVT::i32)
2244 RC = &X86::GR32RegClass;
2245 else if (Is64Bit && RegVT == MVT::i64)
2246 RC = &X86::GR64RegClass;
2247 else if (RegVT == MVT::f32)
2248 RC = &X86::FR32RegClass;
2249 else if (RegVT == MVT::f64)
2250 RC = &X86::FR64RegClass;
2251 else if (RegVT.is512BitVector())
2252 RC = &X86::VR512RegClass;
2253 else if (RegVT.is256BitVector())
2254 RC = &X86::VR256RegClass;
2255 else if (RegVT.is128BitVector())
2256 RC = &X86::VR128RegClass;
2257 else if (RegVT == MVT::x86mmx)
2258 RC = &X86::VR64RegClass;
2259 else if (RegVT == MVT::i1)
2260 RC = &X86::VK1RegClass;
2261 else if (RegVT == MVT::v8i1)
2262 RC = &X86::VK8RegClass;
2263 else if (RegVT == MVT::v16i1)
2264 RC = &X86::VK16RegClass;
2266 llvm_unreachable("Unknown argument type!");
2268 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2269 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2271 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2272 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2274 if (VA.getLocInfo() == CCValAssign::SExt)
2275 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2276 DAG.getValueType(VA.getValVT()));
2277 else if (VA.getLocInfo() == CCValAssign::ZExt)
2278 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2279 DAG.getValueType(VA.getValVT()));
2280 else if (VA.getLocInfo() == CCValAssign::BCvt)
2281 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2283 if (VA.isExtInLoc()) {
2284 // Handle MMX values passed in XMM regs.
2285 if (RegVT.isVector())
2286 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2288 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2291 assert(VA.isMemLoc());
2292 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2295 // If value is passed via pointer - do a load.
2296 if (VA.getLocInfo() == CCValAssign::Indirect)
2297 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2298 MachinePointerInfo(), false, false, false, 0);
2300 InVals.push_back(ArgValue);
2303 // The x86-64 ABIs require that for returning structs by value we copy
2304 // the sret argument into %rax/%eax (depending on ABI) for the return.
2305 // Win32 requires us to put the sret argument to %eax as well.
2306 // Save the argument into a virtual register so that we can access it
2307 // from the return points.
2308 if (MF.getFunction()->hasStructRetAttr() &&
2309 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2310 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2311 unsigned Reg = FuncInfo->getSRetReturnReg();
2313 MVT PtrTy = getPointerTy();
2314 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2315 FuncInfo->setSRetReturnReg(Reg);
2317 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2318 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2321 unsigned StackSize = CCInfo.getNextStackOffset();
2322 // Align stack specially for tail calls.
2323 if (FuncIsMadeTailCallSafe(CallConv,
2324 MF.getTarget().Options.GuaranteedTailCallOpt))
2325 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2327 // If the function takes variable number of arguments, make a frame index for
2328 // the start of the first vararg value... for expansion of llvm.va_start.
2330 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2331 CallConv != CallingConv::X86_ThisCall)) {
2332 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2335 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2337 // FIXME: We should really autogenerate these arrays
2338 static const MCPhysReg GPR64ArgRegsWin64[] = {
2339 X86::RCX, X86::RDX, X86::R8, X86::R9
2341 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2342 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2344 static const MCPhysReg XMMArgRegs64Bit[] = {
2345 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2346 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2348 const MCPhysReg *GPR64ArgRegs;
2349 unsigned NumXMMRegs = 0;
2352 // The XMM registers which might contain var arg parameters are shadowed
2353 // in their paired GPR. So we only need to save the GPR to their home
2355 TotalNumIntRegs = 4;
2356 GPR64ArgRegs = GPR64ArgRegsWin64;
2358 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2359 GPR64ArgRegs = GPR64ArgRegs64Bit;
2361 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2364 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2367 bool NoImplicitFloatOps = Fn->getAttributes().
2368 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2369 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2370 "SSE register cannot be used when SSE is disabled!");
2371 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2372 NoImplicitFloatOps) &&
2373 "SSE register cannot be used when SSE is disabled!");
2374 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2375 !Subtarget->hasSSE1())
2376 // Kernel mode asks for SSE to be disabled, so don't push them
2378 TotalNumXMMRegs = 0;
2381 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2382 // Get to the caller-allocated home save location. Add 8 to account
2383 // for the return address.
2384 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2385 FuncInfo->setRegSaveFrameIndex(
2386 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2387 // Fixup to set vararg frame on shadow area (4 x i64).
2389 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2391 // For X86-64, if there are vararg parameters that are passed via
2392 // registers, then we must store them to their spots on the stack so
2393 // they may be loaded by deferencing the result of va_next.
2394 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2395 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2396 FuncInfo->setRegSaveFrameIndex(
2397 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2401 // Store the integer parameter registers.
2402 SmallVector<SDValue, 8> MemOps;
2403 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2405 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2406 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2407 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2408 DAG.getIntPtrConstant(Offset));
2409 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2410 &X86::GR64RegClass);
2411 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2413 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2414 MachinePointerInfo::getFixedStack(
2415 FuncInfo->getRegSaveFrameIndex(), Offset),
2417 MemOps.push_back(Store);
2421 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2422 // Now store the XMM (fp + vector) parameter registers.
2423 SmallVector<SDValue, 11> SaveXMMOps;
2424 SaveXMMOps.push_back(Chain);
2426 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2427 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2428 SaveXMMOps.push_back(ALVal);
2430 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2431 FuncInfo->getRegSaveFrameIndex()));
2432 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2433 FuncInfo->getVarArgsFPOffset()));
2435 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2436 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2437 &X86::VR128RegClass);
2438 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2439 SaveXMMOps.push_back(Val);
2441 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2442 MVT::Other, SaveXMMOps));
2445 if (!MemOps.empty())
2446 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2450 // Some CCs need callee pop.
2451 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2452 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2453 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2455 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2456 // If this is an sret function, the return should pop the hidden pointer.
2457 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2458 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2459 argsAreStructReturn(Ins) == StackStructReturn)
2460 FuncInfo->setBytesToPopOnReturn(4);
2464 // RegSaveFrameIndex is X86-64 only.
2465 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2466 if (CallConv == CallingConv::X86_FastCall ||
2467 CallConv == CallingConv::X86_ThisCall)
2468 // fastcc functions can't have varargs.
2469 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2472 FuncInfo->setArgumentStackSize(StackSize);
2478 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2479 SDValue StackPtr, SDValue Arg,
2480 SDLoc dl, SelectionDAG &DAG,
2481 const CCValAssign &VA,
2482 ISD::ArgFlagsTy Flags) const {
2483 unsigned LocMemOffset = VA.getLocMemOffset();
2484 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2485 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2486 if (Flags.isByVal())
2487 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2489 return DAG.getStore(Chain, dl, Arg, PtrOff,
2490 MachinePointerInfo::getStack(LocMemOffset),
2494 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2495 /// optimization is performed and it is required.
2497 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2498 SDValue &OutRetAddr, SDValue Chain,
2499 bool IsTailCall, bool Is64Bit,
2500 int FPDiff, SDLoc dl) const {
2501 // Adjust the Return address stack slot.
2502 EVT VT = getPointerTy();
2503 OutRetAddr = getReturnAddressFrameIndex(DAG);
2505 // Load the "old" Return address.
2506 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2507 false, false, false, 0);
2508 return SDValue(OutRetAddr.getNode(), 1);
2511 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2512 /// optimization is performed and it is required (FPDiff!=0).
2513 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2514 SDValue Chain, SDValue RetAddrFrIdx,
2515 EVT PtrVT, unsigned SlotSize,
2516 int FPDiff, SDLoc dl) {
2517 // Store the return address to the appropriate stack slot.
2518 if (!FPDiff) return Chain;
2519 // Calculate the new stack slot for the return address.
2520 int NewReturnAddrFI =
2521 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2523 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2524 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2525 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2531 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2532 SmallVectorImpl<SDValue> &InVals) const {
2533 SelectionDAG &DAG = CLI.DAG;
2535 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2536 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2537 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2538 SDValue Chain = CLI.Chain;
2539 SDValue Callee = CLI.Callee;
2540 CallingConv::ID CallConv = CLI.CallConv;
2541 bool &isTailCall = CLI.IsTailCall;
2542 bool isVarArg = CLI.IsVarArg;
2544 MachineFunction &MF = DAG.getMachineFunction();
2545 bool Is64Bit = Subtarget->is64Bit();
2546 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2547 StructReturnType SR = callIsStructReturn(Outs);
2548 bool IsSibcall = false;
2550 if (MF.getTarget().Options.DisableTailCalls)
2553 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2555 // Force this to be a tail call. The verifier rules are enough to ensure
2556 // that we can lower this successfully without moving the return address
2559 } else if (isTailCall) {
2560 // Check if it's really possible to do a tail call.
2561 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2562 isVarArg, SR != NotStructReturn,
2563 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2564 Outs, OutVals, Ins, DAG);
2566 // Sibcalls are automatically detected tailcalls which do not require
2568 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2575 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2576 "Var args not supported with calling convention fastcc, ghc or hipe");
2578 // Analyze operands of the call, assigning locations to each operand.
2579 SmallVector<CCValAssign, 16> ArgLocs;
2580 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2581 ArgLocs, *DAG.getContext());
2583 // Allocate shadow area for Win64
2585 CCInfo.AllocateStack(32, 8);
2587 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2589 // Get a count of how many bytes are to be pushed on the stack.
2590 unsigned NumBytes = CCInfo.getNextStackOffset();
2592 // This is a sibcall. The memory operands are available in caller's
2593 // own caller's stack.
2595 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2596 IsTailCallConvention(CallConv))
2597 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2600 if (isTailCall && !IsSibcall && !IsMustTail) {
2601 // Lower arguments at fp - stackoffset + fpdiff.
2602 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2603 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2605 FPDiff = NumBytesCallerPushed - NumBytes;
2607 // Set the delta of movement of the returnaddr stackslot.
2608 // But only set if delta is greater than previous delta.
2609 if (FPDiff < X86Info->getTCReturnAddrDelta())
2610 X86Info->setTCReturnAddrDelta(FPDiff);
2613 unsigned NumBytesToPush = NumBytes;
2614 unsigned NumBytesToPop = NumBytes;
2616 // If we have an inalloca argument, all stack space has already been allocated
2617 // for us and be right at the top of the stack. We don't support multiple
2618 // arguments passed in memory when using inalloca.
2619 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2621 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2622 "an inalloca argument must be the only memory argument");
2626 Chain = DAG.getCALLSEQ_START(
2627 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2629 SDValue RetAddrFrIdx;
2630 // Load return address for tail calls.
2631 if (isTailCall && FPDiff)
2632 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2633 Is64Bit, FPDiff, dl);
2635 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2636 SmallVector<SDValue, 8> MemOpChains;
2639 // Walk the register/memloc assignments, inserting copies/loads. In the case
2640 // of tail call optimization arguments are handle later.
2641 const X86RegisterInfo *RegInfo =
2642 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2643 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2644 // Skip inalloca arguments, they have already been written.
2645 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2646 if (Flags.isInAlloca())
2649 CCValAssign &VA = ArgLocs[i];
2650 EVT RegVT = VA.getLocVT();
2651 SDValue Arg = OutVals[i];
2652 bool isByVal = Flags.isByVal();
2654 // Promote the value if needed.
2655 switch (VA.getLocInfo()) {
2656 default: llvm_unreachable("Unknown loc info!");
2657 case CCValAssign::Full: break;
2658 case CCValAssign::SExt:
2659 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2661 case CCValAssign::ZExt:
2662 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2664 case CCValAssign::AExt:
2665 if (RegVT.is128BitVector()) {
2666 // Special case: passing MMX values in XMM registers.
2667 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2668 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2669 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2671 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2673 case CCValAssign::BCvt:
2674 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2676 case CCValAssign::Indirect: {
2677 // Store the argument.
2678 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2679 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2680 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2681 MachinePointerInfo::getFixedStack(FI),
2688 if (VA.isRegLoc()) {
2689 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2690 if (isVarArg && IsWin64) {
2691 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2692 // shadow reg if callee is a varargs function.
2693 unsigned ShadowReg = 0;
2694 switch (VA.getLocReg()) {
2695 case X86::XMM0: ShadowReg = X86::RCX; break;
2696 case X86::XMM1: ShadowReg = X86::RDX; break;
2697 case X86::XMM2: ShadowReg = X86::R8; break;
2698 case X86::XMM3: ShadowReg = X86::R9; break;
2701 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2703 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2704 assert(VA.isMemLoc());
2705 if (!StackPtr.getNode())
2706 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2708 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2709 dl, DAG, VA, Flags));
2713 if (!MemOpChains.empty())
2714 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2716 if (Subtarget->isPICStyleGOT()) {
2717 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2720 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2721 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2723 // If we are tail calling and generating PIC/GOT style code load the
2724 // address of the callee into ECX. The value in ecx is used as target of
2725 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2726 // for tail calls on PIC/GOT architectures. Normally we would just put the
2727 // address of GOT into ebx and then call target@PLT. But for tail calls
2728 // ebx would be restored (since ebx is callee saved) before jumping to the
2731 // Note: The actual moving to ECX is done further down.
2732 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2733 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2734 !G->getGlobal()->hasProtectedVisibility())
2735 Callee = LowerGlobalAddress(Callee, DAG);
2736 else if (isa<ExternalSymbolSDNode>(Callee))
2737 Callee = LowerExternalSymbol(Callee, DAG);
2741 if (Is64Bit && isVarArg && !IsWin64) {
2742 // From AMD64 ABI document:
2743 // For calls that may call functions that use varargs or stdargs
2744 // (prototype-less calls or calls to functions containing ellipsis (...) in
2745 // the declaration) %al is used as hidden argument to specify the number
2746 // of SSE registers used. The contents of %al do not need to match exactly
2747 // the number of registers, but must be an ubound on the number of SSE
2748 // registers used and is in the range 0 - 8 inclusive.
2750 // Count the number of XMM registers allocated.
2751 static const MCPhysReg XMMArgRegs[] = {
2752 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2753 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2755 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2756 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2757 && "SSE registers cannot be used when SSE is disabled");
2759 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2760 DAG.getConstant(NumXMMRegs, MVT::i8)));
2763 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2764 // don't need this because the eligibility check rejects calls that require
2765 // shuffling arguments passed in memory.
2766 if (!IsSibcall && isTailCall) {
2767 // Force all the incoming stack arguments to be loaded from the stack
2768 // before any new outgoing arguments are stored to the stack, because the
2769 // outgoing stack slots may alias the incoming argument stack slots, and
2770 // the alias isn't otherwise explicit. This is slightly more conservative
2771 // than necessary, because it means that each store effectively depends
2772 // on every argument instead of just those arguments it would clobber.
2773 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2775 SmallVector<SDValue, 8> MemOpChains2;
2778 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2779 CCValAssign &VA = ArgLocs[i];
2782 assert(VA.isMemLoc());
2783 SDValue Arg = OutVals[i];
2784 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2785 // Skip inalloca arguments. They don't require any work.
2786 if (Flags.isInAlloca())
2788 // Create frame index.
2789 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2790 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2791 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2792 FIN = DAG.getFrameIndex(FI, getPointerTy());
2794 if (Flags.isByVal()) {
2795 // Copy relative to framepointer.
2796 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2797 if (!StackPtr.getNode())
2798 StackPtr = DAG.getCopyFromReg(Chain, dl,
2799 RegInfo->getStackRegister(),
2801 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2803 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2807 // Store relative to framepointer.
2808 MemOpChains2.push_back(
2809 DAG.getStore(ArgChain, dl, Arg, FIN,
2810 MachinePointerInfo::getFixedStack(FI),
2815 if (!MemOpChains2.empty())
2816 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2818 // Store the return address to the appropriate stack slot.
2819 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2820 getPointerTy(), RegInfo->getSlotSize(),
2824 // Build a sequence of copy-to-reg nodes chained together with token chain
2825 // and flag operands which copy the outgoing args into registers.
2827 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2828 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2829 RegsToPass[i].second, InFlag);
2830 InFlag = Chain.getValue(1);
2833 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2834 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2835 // In the 64-bit large code model, we have to make all calls
2836 // through a register, since the call instruction's 32-bit
2837 // pc-relative offset may not be large enough to hold the whole
2839 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2840 // If the callee is a GlobalAddress node (quite common, every direct call
2841 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2844 // We should use extra load for direct calls to dllimported functions in
2846 const GlobalValue *GV = G->getGlobal();
2847 if (!GV->hasDLLImportStorageClass()) {
2848 unsigned char OpFlags = 0;
2849 bool ExtraLoad = false;
2850 unsigned WrapperKind = ISD::DELETED_NODE;
2852 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2853 // external symbols most go through the PLT in PIC mode. If the symbol
2854 // has hidden or protected visibility, or if it is static or local, then
2855 // we don't need to use the PLT - we can directly call it.
2856 if (Subtarget->isTargetELF() &&
2857 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2858 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2859 OpFlags = X86II::MO_PLT;
2860 } else if (Subtarget->isPICStyleStubAny() &&
2861 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2862 (!Subtarget->getTargetTriple().isMacOSX() ||
2863 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2864 // PC-relative references to external symbols should go through $stub,
2865 // unless we're building with the leopard linker or later, which
2866 // automatically synthesizes these stubs.
2867 OpFlags = X86II::MO_DARWIN_STUB;
2868 } else if (Subtarget->isPICStyleRIPRel() &&
2869 isa<Function>(GV) &&
2870 cast<Function>(GV)->getAttributes().
2871 hasAttribute(AttributeSet::FunctionIndex,
2872 Attribute::NonLazyBind)) {
2873 // If the function is marked as non-lazy, generate an indirect call
2874 // which loads from the GOT directly. This avoids runtime overhead
2875 // at the cost of eager binding (and one extra byte of encoding).
2876 OpFlags = X86II::MO_GOTPCREL;
2877 WrapperKind = X86ISD::WrapperRIP;
2881 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2882 G->getOffset(), OpFlags);
2884 // Add a wrapper if needed.
2885 if (WrapperKind != ISD::DELETED_NODE)
2886 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2887 // Add extra indirection if needed.
2889 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2890 MachinePointerInfo::getGOT(),
2891 false, false, false, 0);
2893 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2894 unsigned char OpFlags = 0;
2896 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2897 // external symbols should go through the PLT.
2898 if (Subtarget->isTargetELF() &&
2899 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2900 OpFlags = X86II::MO_PLT;
2901 } else if (Subtarget->isPICStyleStubAny() &&
2902 (!Subtarget->getTargetTriple().isMacOSX() ||
2903 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2904 // PC-relative references to external symbols should go through $stub,
2905 // unless we're building with the leopard linker or later, which
2906 // automatically synthesizes these stubs.
2907 OpFlags = X86II::MO_DARWIN_STUB;
2910 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2914 // Returns a chain & a flag for retval copy to use.
2915 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2916 SmallVector<SDValue, 8> Ops;
2918 if (!IsSibcall && isTailCall) {
2919 Chain = DAG.getCALLSEQ_END(Chain,
2920 DAG.getIntPtrConstant(NumBytesToPop, true),
2921 DAG.getIntPtrConstant(0, true), InFlag, dl);
2922 InFlag = Chain.getValue(1);
2925 Ops.push_back(Chain);
2926 Ops.push_back(Callee);
2929 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2931 // Add argument registers to the end of the list so that they are known live
2933 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2934 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2935 RegsToPass[i].second.getValueType()));
2937 // Add a register mask operand representing the call-preserved registers.
2938 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2939 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2940 assert(Mask && "Missing call preserved mask for calling convention");
2941 Ops.push_back(DAG.getRegisterMask(Mask));
2943 if (InFlag.getNode())
2944 Ops.push_back(InFlag);
2948 //// If this is the first return lowered for this function, add the regs
2949 //// to the liveout set for the function.
2950 // This isn't right, although it's probably harmless on x86; liveouts
2951 // should be computed from returns not tail calls. Consider a void
2952 // function making a tail call to a function returning int.
2953 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2956 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2957 InFlag = Chain.getValue(1);
2959 // Create the CALLSEQ_END node.
2960 unsigned NumBytesForCalleeToPop;
2961 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2962 getTargetMachine().Options.GuaranteedTailCallOpt))
2963 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2964 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2965 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2966 SR == StackStructReturn)
2967 // If this is a call to a struct-return function, the callee
2968 // pops the hidden struct pointer, so we have to push it back.
2969 // This is common for Darwin/X86, Linux & Mingw32 targets.
2970 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2971 NumBytesForCalleeToPop = 4;
2973 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2975 // Returns a flag for retval copy to use.
2977 Chain = DAG.getCALLSEQ_END(Chain,
2978 DAG.getIntPtrConstant(NumBytesToPop, true),
2979 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2982 InFlag = Chain.getValue(1);
2985 // Handle result values, copying them out of physregs into vregs that we
2987 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2988 Ins, dl, DAG, InVals);
2991 //===----------------------------------------------------------------------===//
2992 // Fast Calling Convention (tail call) implementation
2993 //===----------------------------------------------------------------------===//
2995 // Like std call, callee cleans arguments, convention except that ECX is
2996 // reserved for storing the tail called function address. Only 2 registers are
2997 // free for argument passing (inreg). Tail call optimization is performed
2999 // * tailcallopt is enabled
3000 // * caller/callee are fastcc
3001 // On X86_64 architecture with GOT-style position independent code only local
3002 // (within module) calls are supported at the moment.
3003 // To keep the stack aligned according to platform abi the function
3004 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3005 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3006 // If a tail called function callee has more arguments than the caller the
3007 // caller needs to make sure that there is room to move the RETADDR to. This is
3008 // achieved by reserving an area the size of the argument delta right after the
3009 // original REtADDR, but before the saved framepointer or the spilled registers
3010 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3022 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3023 /// for a 16 byte align requirement.
3025 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3026 SelectionDAG& DAG) const {
3027 MachineFunction &MF = DAG.getMachineFunction();
3028 const TargetMachine &TM = MF.getTarget();
3029 const X86RegisterInfo *RegInfo =
3030 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3031 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3032 unsigned StackAlignment = TFI.getStackAlignment();
3033 uint64_t AlignMask = StackAlignment - 1;
3034 int64_t Offset = StackSize;
3035 unsigned SlotSize = RegInfo->getSlotSize();
3036 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3037 // Number smaller than 12 so just add the difference.
3038 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3040 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3041 Offset = ((~AlignMask) & Offset) + StackAlignment +
3042 (StackAlignment-SlotSize);
3047 /// MatchingStackOffset - Return true if the given stack call argument is
3048 /// already available in the same position (relatively) of the caller's
3049 /// incoming argument stack.
3051 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3052 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3053 const X86InstrInfo *TII) {
3054 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3056 if (Arg.getOpcode() == ISD::CopyFromReg) {
3057 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3058 if (!TargetRegisterInfo::isVirtualRegister(VR))
3060 MachineInstr *Def = MRI->getVRegDef(VR);
3063 if (!Flags.isByVal()) {
3064 if (!TII->isLoadFromStackSlot(Def, FI))
3067 unsigned Opcode = Def->getOpcode();
3068 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3069 Def->getOperand(1).isFI()) {
3070 FI = Def->getOperand(1).getIndex();
3071 Bytes = Flags.getByValSize();
3075 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3076 if (Flags.isByVal())
3077 // ByVal argument is passed in as a pointer but it's now being
3078 // dereferenced. e.g.
3079 // define @foo(%struct.X* %A) {
3080 // tail call @bar(%struct.X* byval %A)
3083 SDValue Ptr = Ld->getBasePtr();
3084 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3087 FI = FINode->getIndex();
3088 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3089 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3090 FI = FINode->getIndex();
3091 Bytes = Flags.getByValSize();
3095 assert(FI != INT_MAX);
3096 if (!MFI->isFixedObjectIndex(FI))
3098 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3101 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3102 /// for tail call optimization. Targets which want to do tail call
3103 /// optimization should implement this function.
3105 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3106 CallingConv::ID CalleeCC,
3108 bool isCalleeStructRet,
3109 bool isCallerStructRet,
3111 const SmallVectorImpl<ISD::OutputArg> &Outs,
3112 const SmallVectorImpl<SDValue> &OutVals,
3113 const SmallVectorImpl<ISD::InputArg> &Ins,
3114 SelectionDAG &DAG) const {
3115 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3118 // If -tailcallopt is specified, make fastcc functions tail-callable.
3119 const MachineFunction &MF = DAG.getMachineFunction();
3120 const Function *CallerF = MF.getFunction();
3122 // If the function return type is x86_fp80 and the callee return type is not,
3123 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3124 // perform a tailcall optimization here.
3125 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3128 CallingConv::ID CallerCC = CallerF->getCallingConv();
3129 bool CCMatch = CallerCC == CalleeCC;
3130 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3131 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3133 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3134 if (IsTailCallConvention(CalleeCC) && CCMatch)
3139 // Look for obvious safe cases to perform tail call optimization that do not
3140 // require ABI changes. This is what gcc calls sibcall.
3142 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3143 // emit a special epilogue.
3144 const X86RegisterInfo *RegInfo =
3145 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3146 if (RegInfo->needsStackRealignment(MF))
3149 // Also avoid sibcall optimization if either caller or callee uses struct
3150 // return semantics.
3151 if (isCalleeStructRet || isCallerStructRet)
3154 // An stdcall/thiscall caller is expected to clean up its arguments; the
3155 // callee isn't going to do that.
3156 // FIXME: this is more restrictive than needed. We could produce a tailcall
3157 // when the stack adjustment matches. For example, with a thiscall that takes
3158 // only one argument.
3159 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3160 CallerCC == CallingConv::X86_ThisCall))
3163 // Do not sibcall optimize vararg calls unless all arguments are passed via
3165 if (isVarArg && !Outs.empty()) {
3167 // Optimizing for varargs on Win64 is unlikely to be safe without
3168 // additional testing.
3169 if (IsCalleeWin64 || IsCallerWin64)
3172 SmallVector<CCValAssign, 16> ArgLocs;
3173 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3174 getTargetMachine(), ArgLocs, *DAG.getContext());
3176 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3177 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3178 if (!ArgLocs[i].isRegLoc())
3182 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3183 // stack. Therefore, if it's not used by the call it is not safe to optimize
3184 // this into a sibcall.
3185 bool Unused = false;
3186 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3193 SmallVector<CCValAssign, 16> RVLocs;
3194 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3195 getTargetMachine(), RVLocs, *DAG.getContext());
3196 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3197 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3198 CCValAssign &VA = RVLocs[i];
3199 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3204 // If the calling conventions do not match, then we'd better make sure the
3205 // results are returned in the same way as what the caller expects.
3207 SmallVector<CCValAssign, 16> RVLocs1;
3208 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3209 getTargetMachine(), RVLocs1, *DAG.getContext());
3210 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3212 SmallVector<CCValAssign, 16> RVLocs2;
3213 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3214 getTargetMachine(), RVLocs2, *DAG.getContext());
3215 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3217 if (RVLocs1.size() != RVLocs2.size())
3219 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3220 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3222 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3224 if (RVLocs1[i].isRegLoc()) {
3225 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3228 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3234 // If the callee takes no arguments then go on to check the results of the
3236 if (!Outs.empty()) {
3237 // Check if stack adjustment is needed. For now, do not do this if any
3238 // argument is passed on the stack.
3239 SmallVector<CCValAssign, 16> ArgLocs;
3240 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3241 getTargetMachine(), ArgLocs, *DAG.getContext());
3243 // Allocate shadow area for Win64
3245 CCInfo.AllocateStack(32, 8);
3247 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3248 if (CCInfo.getNextStackOffset()) {
3249 MachineFunction &MF = DAG.getMachineFunction();
3250 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3253 // Check if the arguments are already laid out in the right way as
3254 // the caller's fixed stack objects.
3255 MachineFrameInfo *MFI = MF.getFrameInfo();
3256 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3257 const X86InstrInfo *TII =
3258 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3259 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3260 CCValAssign &VA = ArgLocs[i];
3261 SDValue Arg = OutVals[i];
3262 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3263 if (VA.getLocInfo() == CCValAssign::Indirect)
3265 if (!VA.isRegLoc()) {
3266 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3273 // If the tailcall address may be in a register, then make sure it's
3274 // possible to register allocate for it. In 32-bit, the call address can
3275 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3276 // callee-saved registers are restored. These happen to be the same
3277 // registers used to pass 'inreg' arguments so watch out for those.
3278 if (!Subtarget->is64Bit() &&
3279 ((!isa<GlobalAddressSDNode>(Callee) &&
3280 !isa<ExternalSymbolSDNode>(Callee)) ||
3281 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3282 unsigned NumInRegs = 0;
3283 // In PIC we need an extra register to formulate the address computation
3285 unsigned MaxInRegs =
3286 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3288 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3289 CCValAssign &VA = ArgLocs[i];
3292 unsigned Reg = VA.getLocReg();
3295 case X86::EAX: case X86::EDX: case X86::ECX:
3296 if (++NumInRegs == MaxInRegs)
3308 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3309 const TargetLibraryInfo *libInfo) const {
3310 return X86::createFastISel(funcInfo, libInfo);
3313 //===----------------------------------------------------------------------===//
3314 // Other Lowering Hooks
3315 //===----------------------------------------------------------------------===//
3317 static bool MayFoldLoad(SDValue Op) {
3318 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3321 static bool MayFoldIntoStore(SDValue Op) {
3322 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3325 static bool isTargetShuffle(unsigned Opcode) {
3327 default: return false;
3328 case X86ISD::PSHUFD:
3329 case X86ISD::PSHUFHW:
3330 case X86ISD::PSHUFLW:
3332 case X86ISD::PALIGNR:
3333 case X86ISD::MOVLHPS:
3334 case X86ISD::MOVLHPD:
3335 case X86ISD::MOVHLPS:
3336 case X86ISD::MOVLPS:
3337 case X86ISD::MOVLPD:
3338 case X86ISD::MOVSHDUP:
3339 case X86ISD::MOVSLDUP:
3340 case X86ISD::MOVDDUP:
3343 case X86ISD::UNPCKL:
3344 case X86ISD::UNPCKH:
3345 case X86ISD::VPERMILP:
3346 case X86ISD::VPERM2X128:
3347 case X86ISD::VPERMI:
3352 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3353 SDValue V1, SelectionDAG &DAG) {
3355 default: llvm_unreachable("Unknown x86 shuffle node");
3356 case X86ISD::MOVSHDUP:
3357 case X86ISD::MOVSLDUP:
3358 case X86ISD::MOVDDUP:
3359 return DAG.getNode(Opc, dl, VT, V1);
3363 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3364 SDValue V1, unsigned TargetMask,
3365 SelectionDAG &DAG) {
3367 default: llvm_unreachable("Unknown x86 shuffle node");
3368 case X86ISD::PSHUFD:
3369 case X86ISD::PSHUFHW:
3370 case X86ISD::PSHUFLW:
3371 case X86ISD::VPERMILP:
3372 case X86ISD::VPERMI:
3373 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3377 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3378 SDValue V1, SDValue V2, unsigned TargetMask,
3379 SelectionDAG &DAG) {
3381 default: llvm_unreachable("Unknown x86 shuffle node");
3382 case X86ISD::PALIGNR:
3384 case X86ISD::VPERM2X128:
3385 return DAG.getNode(Opc, dl, VT, V1, V2,
3386 DAG.getConstant(TargetMask, MVT::i8));
3390 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3391 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3393 default: llvm_unreachable("Unknown x86 shuffle node");
3394 case X86ISD::MOVLHPS:
3395 case X86ISD::MOVLHPD:
3396 case X86ISD::MOVHLPS:
3397 case X86ISD::MOVLPS:
3398 case X86ISD::MOVLPD:
3401 case X86ISD::UNPCKL:
3402 case X86ISD::UNPCKH:
3403 return DAG.getNode(Opc, dl, VT, V1, V2);
3407 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3408 MachineFunction &MF = DAG.getMachineFunction();
3409 const X86RegisterInfo *RegInfo =
3410 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3411 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3412 int ReturnAddrIndex = FuncInfo->getRAIndex();
3414 if (ReturnAddrIndex == 0) {
3415 // Set up a frame object for the return address.
3416 unsigned SlotSize = RegInfo->getSlotSize();
3417 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3420 FuncInfo->setRAIndex(ReturnAddrIndex);
3423 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3426 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3427 bool hasSymbolicDisplacement) {
3428 // Offset should fit into 32 bit immediate field.
3429 if (!isInt<32>(Offset))
3432 // If we don't have a symbolic displacement - we don't have any extra
3434 if (!hasSymbolicDisplacement)
3437 // FIXME: Some tweaks might be needed for medium code model.
3438 if (M != CodeModel::Small && M != CodeModel::Kernel)
3441 // For small code model we assume that latest object is 16MB before end of 31
3442 // bits boundary. We may also accept pretty large negative constants knowing
3443 // that all objects are in the positive half of address space.
3444 if (M == CodeModel::Small && Offset < 16*1024*1024)
3447 // For kernel code model we know that all object resist in the negative half
3448 // of 32bits address space. We may not accept negative offsets, since they may
3449 // be just off and we may accept pretty large positive ones.
3450 if (M == CodeModel::Kernel && Offset > 0)
3456 /// isCalleePop - Determines whether the callee is required to pop its
3457 /// own arguments. Callee pop is necessary to support tail calls.
3458 bool X86::isCalleePop(CallingConv::ID CallingConv,
3459 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3463 switch (CallingConv) {
3466 case CallingConv::X86_StdCall:
3468 case CallingConv::X86_FastCall:
3470 case CallingConv::X86_ThisCall:
3472 case CallingConv::Fast:
3474 case CallingConv::GHC:
3476 case CallingConv::HiPE:
3481 /// \brief Return true if the condition is an unsigned comparison operation.
3482 static bool isX86CCUnsigned(unsigned X86CC) {
3484 default: llvm_unreachable("Invalid integer condition!");
3485 case X86::COND_E: return true;
3486 case X86::COND_G: return false;
3487 case X86::COND_GE: return false;
3488 case X86::COND_L: return false;
3489 case X86::COND_LE: return false;
3490 case X86::COND_NE: return true;
3491 case X86::COND_B: return true;
3492 case X86::COND_A: return true;
3493 case X86::COND_BE: return true;
3494 case X86::COND_AE: return true;
3496 llvm_unreachable("covered switch fell through?!");
3499 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3500 /// specific condition code, returning the condition code and the LHS/RHS of the
3501 /// comparison to make.
3502 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3503 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3505 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3506 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3507 // X > -1 -> X == 0, jump !sign.
3508 RHS = DAG.getConstant(0, RHS.getValueType());
3509 return X86::COND_NS;
3511 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3512 // X < 0 -> X == 0, jump on sign.
3515 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3517 RHS = DAG.getConstant(0, RHS.getValueType());
3518 return X86::COND_LE;
3522 switch (SetCCOpcode) {
3523 default: llvm_unreachable("Invalid integer condition!");
3524 case ISD::SETEQ: return X86::COND_E;
3525 case ISD::SETGT: return X86::COND_G;
3526 case ISD::SETGE: return X86::COND_GE;
3527 case ISD::SETLT: return X86::COND_L;
3528 case ISD::SETLE: return X86::COND_LE;
3529 case ISD::SETNE: return X86::COND_NE;
3530 case ISD::SETULT: return X86::COND_B;
3531 case ISD::SETUGT: return X86::COND_A;
3532 case ISD::SETULE: return X86::COND_BE;
3533 case ISD::SETUGE: return X86::COND_AE;
3537 // First determine if it is required or is profitable to flip the operands.
3539 // If LHS is a foldable load, but RHS is not, flip the condition.
3540 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3541 !ISD::isNON_EXTLoad(RHS.getNode())) {
3542 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3543 std::swap(LHS, RHS);
3546 switch (SetCCOpcode) {
3552 std::swap(LHS, RHS);
3556 // On a floating point condition, the flags are set as follows:
3558 // 0 | 0 | 0 | X > Y
3559 // 0 | 0 | 1 | X < Y
3560 // 1 | 0 | 0 | X == Y
3561 // 1 | 1 | 1 | unordered
3562 switch (SetCCOpcode) {
3563 default: llvm_unreachable("Condcode should be pre-legalized away");
3565 case ISD::SETEQ: return X86::COND_E;
3566 case ISD::SETOLT: // flipped
3568 case ISD::SETGT: return X86::COND_A;
3569 case ISD::SETOLE: // flipped
3571 case ISD::SETGE: return X86::COND_AE;
3572 case ISD::SETUGT: // flipped
3574 case ISD::SETLT: return X86::COND_B;
3575 case ISD::SETUGE: // flipped
3577 case ISD::SETLE: return X86::COND_BE;
3579 case ISD::SETNE: return X86::COND_NE;
3580 case ISD::SETUO: return X86::COND_P;
3581 case ISD::SETO: return X86::COND_NP;
3583 case ISD::SETUNE: return X86::COND_INVALID;
3587 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3588 /// code. Current x86 isa includes the following FP cmov instructions:
3589 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3590 static bool hasFPCMov(unsigned X86CC) {
3606 /// isFPImmLegal - Returns true if the target can instruction select the
3607 /// specified FP immediate natively. If false, the legalizer will
3608 /// materialize the FP immediate as a load from a constant pool.
3609 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3610 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3611 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3617 /// \brief Returns true if it is beneficial to convert a load of a constant
3618 /// to just the constant itself.
3619 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3621 assert(Ty->isIntegerTy());
3623 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3624 if (BitSize == 0 || BitSize > 64)
3629 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3630 /// the specified range (L, H].
3631 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3632 return (Val < 0) || (Val >= Low && Val < Hi);
3635 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3636 /// specified value.
3637 static bool isUndefOrEqual(int Val, int CmpVal) {
3638 return (Val < 0 || Val == CmpVal);
3641 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3642 /// from position Pos and ending in Pos+Size, falls within the specified
3643 /// sequential range (L, L+Pos]. or is undef.
3644 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3645 unsigned Pos, unsigned Size, int Low) {
3646 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3647 if (!isUndefOrEqual(Mask[i], Low))
3652 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3653 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3654 /// the second operand.
3655 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3656 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3657 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3658 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3659 return (Mask[0] < 2 && Mask[1] < 2);
3663 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3664 /// is suitable for input to PSHUFHW.
3665 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3666 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3669 // Lower quadword copied in order or undef.
3670 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3673 // Upper quadword shuffled.
3674 for (unsigned i = 4; i != 8; ++i)
3675 if (!isUndefOrInRange(Mask[i], 4, 8))
3678 if (VT == MVT::v16i16) {
3679 // Lower quadword copied in order or undef.
3680 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3683 // Upper quadword shuffled.
3684 for (unsigned i = 12; i != 16; ++i)
3685 if (!isUndefOrInRange(Mask[i], 12, 16))
3692 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3693 /// is suitable for input to PSHUFLW.
3694 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3695 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3698 // Upper quadword copied in order.
3699 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3702 // Lower quadword shuffled.
3703 for (unsigned i = 0; i != 4; ++i)
3704 if (!isUndefOrInRange(Mask[i], 0, 4))
3707 if (VT == MVT::v16i16) {
3708 // Upper quadword copied in order.
3709 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3712 // Lower quadword shuffled.
3713 for (unsigned i = 8; i != 12; ++i)
3714 if (!isUndefOrInRange(Mask[i], 8, 12))
3721 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3722 /// is suitable for input to PALIGNR.
3723 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3724 const X86Subtarget *Subtarget) {
3725 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3726 (VT.is256BitVector() && !Subtarget->hasInt256()))
3729 unsigned NumElts = VT.getVectorNumElements();
3730 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3731 unsigned NumLaneElts = NumElts/NumLanes;
3733 // Do not handle 64-bit element shuffles with palignr.
3734 if (NumLaneElts == 2)
3737 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3739 for (i = 0; i != NumLaneElts; ++i) {
3744 // Lane is all undef, go to next lane
3745 if (i == NumLaneElts)
3748 int Start = Mask[i+l];
3750 // Make sure its in this lane in one of the sources
3751 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3752 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3755 // If not lane 0, then we must match lane 0
3756 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3759 // Correct second source to be contiguous with first source
3760 if (Start >= (int)NumElts)
3761 Start -= NumElts - NumLaneElts;
3763 // Make sure we're shifting in the right direction.
3764 if (Start <= (int)(i+l))
3769 // Check the rest of the elements to see if they are consecutive.
3770 for (++i; i != NumLaneElts; ++i) {
3771 int Idx = Mask[i+l];
3773 // Make sure its in this lane
3774 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3775 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3778 // If not lane 0, then we must match lane 0
3779 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3782 if (Idx >= (int)NumElts)
3783 Idx -= NumElts - NumLaneElts;
3785 if (!isUndefOrEqual(Idx, Start+i))
3794 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3795 /// the two vector operands have swapped position.
3796 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3797 unsigned NumElems) {
3798 for (unsigned i = 0; i != NumElems; ++i) {
3802 else if (idx < (int)NumElems)
3803 Mask[i] = idx + NumElems;
3805 Mask[i] = idx - NumElems;
3809 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3810 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3811 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3812 /// reverse of what x86 shuffles want.
3813 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3815 unsigned NumElems = VT.getVectorNumElements();
3816 unsigned NumLanes = VT.getSizeInBits()/128;
3817 unsigned NumLaneElems = NumElems/NumLanes;
3819 if (NumLaneElems != 2 && NumLaneElems != 4)
3822 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3823 bool symetricMaskRequired =
3824 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3826 // VSHUFPSY divides the resulting vector into 4 chunks.
3827 // The sources are also splitted into 4 chunks, and each destination
3828 // chunk must come from a different source chunk.
3830 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3831 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3833 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3834 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3836 // VSHUFPDY divides the resulting vector into 4 chunks.
3837 // The sources are also splitted into 4 chunks, and each destination
3838 // chunk must come from a different source chunk.
3840 // SRC1 => X3 X2 X1 X0
3841 // SRC2 => Y3 Y2 Y1 Y0
3843 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3845 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3846 unsigned HalfLaneElems = NumLaneElems/2;
3847 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3848 for (unsigned i = 0; i != NumLaneElems; ++i) {
3849 int Idx = Mask[i+l];
3850 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3851 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3853 // For VSHUFPSY, the mask of the second half must be the same as the
3854 // first but with the appropriate offsets. This works in the same way as
3855 // VPERMILPS works with masks.
3856 if (!symetricMaskRequired || Idx < 0)
3858 if (MaskVal[i] < 0) {
3859 MaskVal[i] = Idx - l;
3862 if ((signed)(Idx - l) != MaskVal[i])
3870 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3871 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3872 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3873 if (!VT.is128BitVector())
3876 unsigned NumElems = VT.getVectorNumElements();
3881 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3882 return isUndefOrEqual(Mask[0], 6) &&
3883 isUndefOrEqual(Mask[1], 7) &&
3884 isUndefOrEqual(Mask[2], 2) &&
3885 isUndefOrEqual(Mask[3], 3);
3888 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3889 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3891 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3892 if (!VT.is128BitVector())
3895 unsigned NumElems = VT.getVectorNumElements();
3900 return isUndefOrEqual(Mask[0], 2) &&
3901 isUndefOrEqual(Mask[1], 3) &&
3902 isUndefOrEqual(Mask[2], 2) &&
3903 isUndefOrEqual(Mask[3], 3);
3906 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3907 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3908 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3909 if (!VT.is128BitVector())
3912 unsigned NumElems = VT.getVectorNumElements();
3914 if (NumElems != 2 && NumElems != 4)
3917 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3918 if (!isUndefOrEqual(Mask[i], i + NumElems))
3921 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3922 if (!isUndefOrEqual(Mask[i], i))
3928 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3930 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3931 if (!VT.is128BitVector())
3934 unsigned NumElems = VT.getVectorNumElements();
3936 if (NumElems != 2 && NumElems != 4)
3939 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3940 if (!isUndefOrEqual(Mask[i], i))
3943 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3944 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3950 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3951 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3952 /// i. e: If all but one element come from the same vector.
3953 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3954 // TODO: Deal with AVX's VINSERTPS
3955 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3958 unsigned CorrectPosV1 = 0;
3959 unsigned CorrectPosV2 = 0;
3960 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3963 else if (Mask[i] == i + 4)
3966 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3967 // We have 3 elements from one vector, and one from another.
3974 // Some special combinations that can be optimized.
3977 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3978 SelectionDAG &DAG) {
3979 MVT VT = SVOp->getSimpleValueType(0);
3982 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3985 ArrayRef<int> Mask = SVOp->getMask();
3987 // These are the special masks that may be optimized.
3988 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3989 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3990 bool MatchEvenMask = true;
3991 bool MatchOddMask = true;
3992 for (int i=0; i<8; ++i) {
3993 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3994 MatchEvenMask = false;
3995 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3996 MatchOddMask = false;
3999 if (!MatchEvenMask && !MatchOddMask)
4002 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4004 SDValue Op0 = SVOp->getOperand(0);
4005 SDValue Op1 = SVOp->getOperand(1);
4007 if (MatchEvenMask) {
4008 // Shift the second operand right to 32 bits.
4009 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4010 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4012 // Shift the first operand left to 32 bits.
4013 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4014 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4016 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4017 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4020 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4021 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4022 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4023 bool HasInt256, bool V2IsSplat = false) {
4025 assert(VT.getSizeInBits() >= 128 &&
4026 "Unsupported vector type for unpckl");
4028 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4030 unsigned NumOf256BitLanes;
4031 unsigned NumElts = VT.getVectorNumElements();
4032 if (VT.is256BitVector()) {
4033 if (NumElts != 4 && NumElts != 8 &&
4034 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4037 NumOf256BitLanes = 1;
4038 } else if (VT.is512BitVector()) {
4039 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4040 "Unsupported vector type for unpckh");
4042 NumOf256BitLanes = 2;
4045 NumOf256BitLanes = 1;
4048 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4049 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4051 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4052 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4053 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4054 int BitI = Mask[l256*NumEltsInStride+l+i];
4055 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4056 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4058 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4060 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4068 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4069 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4070 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4071 bool HasInt256, bool V2IsSplat = false) {
4072 assert(VT.getSizeInBits() >= 128 &&
4073 "Unsupported vector type for unpckh");
4075 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4077 unsigned NumOf256BitLanes;
4078 unsigned NumElts = VT.getVectorNumElements();
4079 if (VT.is256BitVector()) {
4080 if (NumElts != 4 && NumElts != 8 &&
4081 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4084 NumOf256BitLanes = 1;
4085 } else if (VT.is512BitVector()) {
4086 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4087 "Unsupported vector type for unpckh");
4089 NumOf256BitLanes = 2;
4092 NumOf256BitLanes = 1;
4095 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4096 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4098 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4099 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4100 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4101 int BitI = Mask[l256*NumEltsInStride+l+i];
4102 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4103 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4105 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4107 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4115 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4116 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4118 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4119 unsigned NumElts = VT.getVectorNumElements();
4120 bool Is256BitVec = VT.is256BitVector();
4122 if (VT.is512BitVector())
4124 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4125 "Unsupported vector type for unpckh");
4127 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4128 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4131 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4132 // FIXME: Need a better way to get rid of this, there's no latency difference
4133 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4134 // the former later. We should also remove the "_undef" special mask.
4135 if (NumElts == 4 && Is256BitVec)
4138 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4139 // independently on 128-bit lanes.
4140 unsigned NumLanes = VT.getSizeInBits()/128;
4141 unsigned NumLaneElts = NumElts/NumLanes;
4143 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4144 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4145 int BitI = Mask[l+i];
4146 int BitI1 = Mask[l+i+1];
4148 if (!isUndefOrEqual(BitI, j))
4150 if (!isUndefOrEqual(BitI1, j))
4158 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4159 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4161 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4162 unsigned NumElts = VT.getVectorNumElements();
4164 if (VT.is512BitVector())
4167 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4168 "Unsupported vector type for unpckh");
4170 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4171 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4174 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4175 // independently on 128-bit lanes.
4176 unsigned NumLanes = VT.getSizeInBits()/128;
4177 unsigned NumLaneElts = NumElts/NumLanes;
4179 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4180 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4181 int BitI = Mask[l+i];
4182 int BitI1 = Mask[l+i+1];
4183 if (!isUndefOrEqual(BitI, j))
4185 if (!isUndefOrEqual(BitI1, j))
4192 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4193 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4194 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4195 if (!VT.is512BitVector())
4198 unsigned NumElts = VT.getVectorNumElements();
4199 unsigned HalfSize = NumElts/2;
4200 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4201 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4206 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4207 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4215 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4216 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4217 /// MOVSD, and MOVD, i.e. setting the lowest element.
4218 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4219 if (VT.getVectorElementType().getSizeInBits() < 32)
4221 if (!VT.is128BitVector())
4224 unsigned NumElts = VT.getVectorNumElements();
4226 if (!isUndefOrEqual(Mask[0], NumElts))
4229 for (unsigned i = 1; i != NumElts; ++i)
4230 if (!isUndefOrEqual(Mask[i], i))
4236 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4237 /// as permutations between 128-bit chunks or halves. As an example: this
4239 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4240 /// The first half comes from the second half of V1 and the second half from the
4241 /// the second half of V2.
4242 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4243 if (!HasFp256 || !VT.is256BitVector())
4246 // The shuffle result is divided into half A and half B. In total the two
4247 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4248 // B must come from C, D, E or F.
4249 unsigned HalfSize = VT.getVectorNumElements()/2;
4250 bool MatchA = false, MatchB = false;
4252 // Check if A comes from one of C, D, E, F.
4253 for (unsigned Half = 0; Half != 4; ++Half) {
4254 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4260 // Check if B comes from one of C, D, E, F.
4261 for (unsigned Half = 0; Half != 4; ++Half) {
4262 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4268 return MatchA && MatchB;
4271 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4272 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4273 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4274 MVT VT = SVOp->getSimpleValueType(0);
4276 unsigned HalfSize = VT.getVectorNumElements()/2;
4278 unsigned FstHalf = 0, SndHalf = 0;
4279 for (unsigned i = 0; i < HalfSize; ++i) {
4280 if (SVOp->getMaskElt(i) > 0) {
4281 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4285 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4286 if (SVOp->getMaskElt(i) > 0) {
4287 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4292 return (FstHalf | (SndHalf << 4));
4295 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4296 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4297 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4301 unsigned NumElts = VT.getVectorNumElements();
4303 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4304 for (unsigned i = 0; i != NumElts; ++i) {
4307 Imm8 |= Mask[i] << (i*2);
4312 unsigned LaneSize = 4;
4313 SmallVector<int, 4> MaskVal(LaneSize, -1);
4315 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4316 for (unsigned i = 0; i != LaneSize; ++i) {
4317 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4321 if (MaskVal[i] < 0) {
4322 MaskVal[i] = Mask[i+l] - l;
4323 Imm8 |= MaskVal[i] << (i*2);
4326 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4333 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4334 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4335 /// Note that VPERMIL mask matching is different depending whether theunderlying
4336 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4337 /// to the same elements of the low, but to the higher half of the source.
4338 /// In VPERMILPD the two lanes could be shuffled independently of each other
4339 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4340 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4341 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4342 if (VT.getSizeInBits() < 256 || EltSize < 32)
4344 bool symetricMaskRequired = (EltSize == 32);
4345 unsigned NumElts = VT.getVectorNumElements();
4347 unsigned NumLanes = VT.getSizeInBits()/128;
4348 unsigned LaneSize = NumElts/NumLanes;
4349 // 2 or 4 elements in one lane
4351 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4352 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4353 for (unsigned i = 0; i != LaneSize; ++i) {
4354 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4356 if (symetricMaskRequired) {
4357 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4358 ExpectedMaskVal[i] = Mask[i+l] - l;
4361 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4369 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4370 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4371 /// element of vector 2 and the other elements to come from vector 1 in order.
4372 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4373 bool V2IsSplat = false, bool V2IsUndef = false) {
4374 if (!VT.is128BitVector())
4377 unsigned NumOps = VT.getVectorNumElements();
4378 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4381 if (!isUndefOrEqual(Mask[0], 0))
4384 for (unsigned i = 1; i != NumOps; ++i)
4385 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4386 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4387 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4393 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4394 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4395 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4396 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4397 const X86Subtarget *Subtarget) {
4398 if (!Subtarget->hasSSE3())
4401 unsigned NumElems = VT.getVectorNumElements();
4403 if ((VT.is128BitVector() && NumElems != 4) ||
4404 (VT.is256BitVector() && NumElems != 8) ||
4405 (VT.is512BitVector() && NumElems != 16))
4408 // "i+1" is the value the indexed mask element must have
4409 for (unsigned i = 0; i != NumElems; i += 2)
4410 if (!isUndefOrEqual(Mask[i], i+1) ||
4411 !isUndefOrEqual(Mask[i+1], i+1))
4417 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4418 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4419 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4420 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4421 const X86Subtarget *Subtarget) {
4422 if (!Subtarget->hasSSE3())
4425 unsigned NumElems = VT.getVectorNumElements();
4427 if ((VT.is128BitVector() && NumElems != 4) ||
4428 (VT.is256BitVector() && NumElems != 8) ||
4429 (VT.is512BitVector() && NumElems != 16))
4432 // "i" is the value the indexed mask element must have
4433 for (unsigned i = 0; i != NumElems; i += 2)
4434 if (!isUndefOrEqual(Mask[i], i) ||
4435 !isUndefOrEqual(Mask[i+1], i))
4441 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4442 /// specifies a shuffle of elements that is suitable for input to 256-bit
4443 /// version of MOVDDUP.
4444 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4445 if (!HasFp256 || !VT.is256BitVector())
4448 unsigned NumElts = VT.getVectorNumElements();
4452 for (unsigned i = 0; i != NumElts/2; ++i)
4453 if (!isUndefOrEqual(Mask[i], 0))
4455 for (unsigned i = NumElts/2; i != NumElts; ++i)
4456 if (!isUndefOrEqual(Mask[i], NumElts/2))
4461 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4462 /// specifies a shuffle of elements that is suitable for input to 128-bit
4463 /// version of MOVDDUP.
4464 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4465 if (!VT.is128BitVector())
4468 unsigned e = VT.getVectorNumElements() / 2;
4469 for (unsigned i = 0; i != e; ++i)
4470 if (!isUndefOrEqual(Mask[i], i))
4472 for (unsigned i = 0; i != e; ++i)
4473 if (!isUndefOrEqual(Mask[e+i], i))
4478 /// isVEXTRACTIndex - Return true if the specified
4479 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4480 /// suitable for instruction that extract 128 or 256 bit vectors
4481 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4482 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4483 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4486 // The index should be aligned on a vecWidth-bit boundary.
4488 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4490 MVT VT = N->getSimpleValueType(0);
4491 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4492 bool Result = (Index * ElSize) % vecWidth == 0;
4497 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4498 /// operand specifies a subvector insert that is suitable for input to
4499 /// insertion of 128 or 256-bit subvectors
4500 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4501 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4502 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4504 // The index should be aligned on a vecWidth-bit boundary.
4506 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4508 MVT VT = N->getSimpleValueType(0);
4509 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4510 bool Result = (Index * ElSize) % vecWidth == 0;
4515 bool X86::isVINSERT128Index(SDNode *N) {
4516 return isVINSERTIndex(N, 128);
4519 bool X86::isVINSERT256Index(SDNode *N) {
4520 return isVINSERTIndex(N, 256);
4523 bool X86::isVEXTRACT128Index(SDNode *N) {
4524 return isVEXTRACTIndex(N, 128);
4527 bool X86::isVEXTRACT256Index(SDNode *N) {
4528 return isVEXTRACTIndex(N, 256);
4531 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4532 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4533 /// Handles 128-bit and 256-bit.
4534 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4535 MVT VT = N->getSimpleValueType(0);
4537 assert((VT.getSizeInBits() >= 128) &&
4538 "Unsupported vector type for PSHUF/SHUFP");
4540 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4541 // independently on 128-bit lanes.
4542 unsigned NumElts = VT.getVectorNumElements();
4543 unsigned NumLanes = VT.getSizeInBits()/128;
4544 unsigned NumLaneElts = NumElts/NumLanes;
4546 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4547 "Only supports 2, 4 or 8 elements per lane");
4549 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4551 for (unsigned i = 0; i != NumElts; ++i) {
4552 int Elt = N->getMaskElt(i);
4553 if (Elt < 0) continue;
4554 Elt &= NumLaneElts - 1;
4555 unsigned ShAmt = (i << Shift) % 8;
4556 Mask |= Elt << ShAmt;
4562 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4563 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4564 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4565 MVT VT = N->getSimpleValueType(0);
4567 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4568 "Unsupported vector type for PSHUFHW");
4570 unsigned NumElts = VT.getVectorNumElements();
4573 for (unsigned l = 0; l != NumElts; l += 8) {
4574 // 8 nodes per lane, but we only care about the last 4.
4575 for (unsigned i = 0; i < 4; ++i) {
4576 int Elt = N->getMaskElt(l+i+4);
4577 if (Elt < 0) continue;
4578 Elt &= 0x3; // only 2-bits.
4579 Mask |= Elt << (i * 2);
4586 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4587 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4588 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4589 MVT VT = N->getSimpleValueType(0);
4591 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4592 "Unsupported vector type for PSHUFHW");
4594 unsigned NumElts = VT.getVectorNumElements();
4597 for (unsigned l = 0; l != NumElts; l += 8) {
4598 // 8 nodes per lane, but we only care about the first 4.
4599 for (unsigned i = 0; i < 4; ++i) {
4600 int Elt = N->getMaskElt(l+i);
4601 if (Elt < 0) continue;
4602 Elt &= 0x3; // only 2-bits
4603 Mask |= Elt << (i * 2);
4610 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4611 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4612 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4613 MVT VT = SVOp->getSimpleValueType(0);
4614 unsigned EltSize = VT.is512BitVector() ? 1 :
4615 VT.getVectorElementType().getSizeInBits() >> 3;
4617 unsigned NumElts = VT.getVectorNumElements();
4618 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4619 unsigned NumLaneElts = NumElts/NumLanes;
4623 for (i = 0; i != NumElts; ++i) {
4624 Val = SVOp->getMaskElt(i);
4628 if (Val >= (int)NumElts)
4629 Val -= NumElts - NumLaneElts;
4631 assert(Val - i > 0 && "PALIGNR imm should be positive");
4632 return (Val - i) * EltSize;
4635 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4636 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4637 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4638 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4641 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4643 MVT VecVT = N->getOperand(0).getSimpleValueType();
4644 MVT ElVT = VecVT.getVectorElementType();
4646 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4647 return Index / NumElemsPerChunk;
4650 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4651 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4652 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4653 llvm_unreachable("Illegal insert subvector for VINSERT");
4656 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4658 MVT VecVT = N->getSimpleValueType(0);
4659 MVT ElVT = VecVT.getVectorElementType();
4661 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4662 return Index / NumElemsPerChunk;
4665 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4666 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4667 /// and VINSERTI128 instructions.
4668 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4669 return getExtractVEXTRACTImmediate(N, 128);
4672 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4673 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4674 /// and VINSERTI64x4 instructions.
4675 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4676 return getExtractVEXTRACTImmediate(N, 256);
4679 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4680 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4681 /// and VINSERTI128 instructions.
4682 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4683 return getInsertVINSERTImmediate(N, 128);
4686 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4687 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4688 /// and VINSERTI64x4 instructions.
4689 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4690 return getInsertVINSERTImmediate(N, 256);
4693 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4695 bool X86::isZeroNode(SDValue Elt) {
4696 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4697 return CN->isNullValue();
4698 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4699 return CFP->getValueAPF().isPosZero();
4703 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4704 /// their permute mask.
4705 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4706 SelectionDAG &DAG) {
4707 MVT VT = SVOp->getSimpleValueType(0);
4708 unsigned NumElems = VT.getVectorNumElements();
4709 SmallVector<int, 8> MaskVec;
4711 for (unsigned i = 0; i != NumElems; ++i) {
4712 int Idx = SVOp->getMaskElt(i);
4714 if (Idx < (int)NumElems)
4719 MaskVec.push_back(Idx);
4721 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4722 SVOp->getOperand(0), &MaskVec[0]);
4725 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4726 /// match movhlps. The lower half elements should come from upper half of
4727 /// V1 (and in order), and the upper half elements should come from the upper
4728 /// half of V2 (and in order).
4729 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4730 if (!VT.is128BitVector())
4732 if (VT.getVectorNumElements() != 4)
4734 for (unsigned i = 0, e = 2; i != e; ++i)
4735 if (!isUndefOrEqual(Mask[i], i+2))
4737 for (unsigned i = 2; i != 4; ++i)
4738 if (!isUndefOrEqual(Mask[i], i+4))
4743 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4744 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4746 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4747 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4749 N = N->getOperand(0).getNode();
4750 if (!ISD::isNON_EXTLoad(N))
4753 *LD = cast<LoadSDNode>(N);
4757 // Test whether the given value is a vector value which will be legalized
4759 static bool WillBeConstantPoolLoad(SDNode *N) {
4760 if (N->getOpcode() != ISD::BUILD_VECTOR)
4763 // Check for any non-constant elements.
4764 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4765 switch (N->getOperand(i).getNode()->getOpcode()) {
4767 case ISD::ConstantFP:
4774 // Vectors of all-zeros and all-ones are materialized with special
4775 // instructions rather than being loaded.
4776 return !ISD::isBuildVectorAllZeros(N) &&
4777 !ISD::isBuildVectorAllOnes(N);
4780 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4781 /// match movlp{s|d}. The lower half elements should come from lower half of
4782 /// V1 (and in order), and the upper half elements should come from the upper
4783 /// half of V2 (and in order). And since V1 will become the source of the
4784 /// MOVLP, it must be either a vector load or a scalar load to vector.
4785 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4786 ArrayRef<int> Mask, MVT VT) {
4787 if (!VT.is128BitVector())
4790 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4792 // Is V2 is a vector load, don't do this transformation. We will try to use
4793 // load folding shufps op.
4794 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4797 unsigned NumElems = VT.getVectorNumElements();
4799 if (NumElems != 2 && NumElems != 4)
4801 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4802 if (!isUndefOrEqual(Mask[i], i))
4804 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4805 if (!isUndefOrEqual(Mask[i], i+NumElems))
4810 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4812 static bool isSplatVector(SDNode *N) {
4813 if (N->getOpcode() != ISD::BUILD_VECTOR)
4816 SDValue SplatValue = N->getOperand(0);
4817 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4818 if (N->getOperand(i) != SplatValue)
4823 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4824 /// to an zero vector.
4825 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4826 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4827 SDValue V1 = N->getOperand(0);
4828 SDValue V2 = N->getOperand(1);
4829 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4830 for (unsigned i = 0; i != NumElems; ++i) {
4831 int Idx = N->getMaskElt(i);
4832 if (Idx >= (int)NumElems) {
4833 unsigned Opc = V2.getOpcode();
4834 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4836 if (Opc != ISD::BUILD_VECTOR ||
4837 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4839 } else if (Idx >= 0) {
4840 unsigned Opc = V1.getOpcode();
4841 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4843 if (Opc != ISD::BUILD_VECTOR ||
4844 !X86::isZeroNode(V1.getOperand(Idx)))
4851 /// getZeroVector - Returns a vector of specified type with all zero elements.
4853 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4854 SelectionDAG &DAG, SDLoc dl) {
4855 assert(VT.isVector() && "Expected a vector type");
4857 // Always build SSE zero vectors as <4 x i32> bitcasted
4858 // to their dest type. This ensures they get CSE'd.
4860 if (VT.is128BitVector()) { // SSE
4861 if (Subtarget->hasSSE2()) { // SSE2
4862 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4863 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4865 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4866 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4868 } else if (VT.is256BitVector()) { // AVX
4869 if (Subtarget->hasInt256()) { // AVX2
4870 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4871 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4872 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4874 // 256-bit logic and arithmetic instructions in AVX are all
4875 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4876 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4877 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4878 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4880 } else if (VT.is512BitVector()) { // AVX-512
4881 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4882 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4883 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4884 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4885 } else if (VT.getScalarType() == MVT::i1) {
4886 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4887 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4888 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4889 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4891 llvm_unreachable("Unexpected vector type");
4893 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4896 /// getOnesVector - Returns a vector of specified type with all bits set.
4897 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4898 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4899 /// Then bitcast to their original type, ensuring they get CSE'd.
4900 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4902 assert(VT.isVector() && "Expected a vector type");
4904 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4906 if (VT.is256BitVector()) {
4907 if (HasInt256) { // AVX2
4908 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4909 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4911 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4912 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4914 } else if (VT.is128BitVector()) {
4915 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4917 llvm_unreachable("Unexpected vector type");
4919 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4922 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4923 /// that point to V2 points to its first element.
4924 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4925 for (unsigned i = 0; i != NumElems; ++i) {
4926 if (Mask[i] > (int)NumElems) {
4932 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4933 /// operation of specified width.
4934 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4936 unsigned NumElems = VT.getVectorNumElements();
4937 SmallVector<int, 8> Mask;
4938 Mask.push_back(NumElems);
4939 for (unsigned i = 1; i != NumElems; ++i)
4941 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4944 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4945 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4947 unsigned NumElems = VT.getVectorNumElements();
4948 SmallVector<int, 8> Mask;
4949 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4951 Mask.push_back(i + NumElems);
4953 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4956 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4957 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4959 unsigned NumElems = VT.getVectorNumElements();
4960 SmallVector<int, 8> Mask;
4961 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4962 Mask.push_back(i + Half);
4963 Mask.push_back(i + NumElems + Half);
4965 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4968 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4969 // a generic shuffle instruction because the target has no such instructions.
4970 // Generate shuffles which repeat i16 and i8 several times until they can be
4971 // represented by v4f32 and then be manipulated by target suported shuffles.
4972 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4973 MVT VT = V.getSimpleValueType();
4974 int NumElems = VT.getVectorNumElements();
4977 while (NumElems > 4) {
4978 if (EltNo < NumElems/2) {
4979 V = getUnpackl(DAG, dl, VT, V, V);
4981 V = getUnpackh(DAG, dl, VT, V, V);
4982 EltNo -= NumElems/2;
4989 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4990 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4991 MVT VT = V.getSimpleValueType();
4994 if (VT.is128BitVector()) {
4995 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4996 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4997 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4999 } else if (VT.is256BitVector()) {
5000 // To use VPERMILPS to splat scalars, the second half of indicies must
5001 // refer to the higher part, which is a duplication of the lower one,
5002 // because VPERMILPS can only handle in-lane permutations.
5003 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5004 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5006 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5007 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5010 llvm_unreachable("Vector size not supported");
5012 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5015 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5016 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5017 MVT SrcVT = SV->getSimpleValueType(0);
5018 SDValue V1 = SV->getOperand(0);
5021 int EltNo = SV->getSplatIndex();
5022 int NumElems = SrcVT.getVectorNumElements();
5023 bool Is256BitVec = SrcVT.is256BitVector();
5025 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5026 "Unknown how to promote splat for type");
5028 // Extract the 128-bit part containing the splat element and update
5029 // the splat element index when it refers to the higher register.
5031 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5032 if (EltNo >= NumElems/2)
5033 EltNo -= NumElems/2;
5036 // All i16 and i8 vector types can't be used directly by a generic shuffle
5037 // instruction because the target has no such instruction. Generate shuffles
5038 // which repeat i16 and i8 several times until they fit in i32, and then can
5039 // be manipulated by target suported shuffles.
5040 MVT EltVT = SrcVT.getVectorElementType();
5041 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5042 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5044 // Recreate the 256-bit vector and place the same 128-bit vector
5045 // into the low and high part. This is necessary because we want
5046 // to use VPERM* to shuffle the vectors
5048 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5051 return getLegalSplat(DAG, V1, EltNo);
5054 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5055 /// vector of zero or undef vector. This produces a shuffle where the low
5056 /// element of V2 is swizzled into the zero/undef vector, landing at element
5057 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5058 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5060 const X86Subtarget *Subtarget,
5061 SelectionDAG &DAG) {
5062 MVT VT = V2.getSimpleValueType();
5064 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5065 unsigned NumElems = VT.getVectorNumElements();
5066 SmallVector<int, 16> MaskVec;
5067 for (unsigned i = 0; i != NumElems; ++i)
5068 // If this is the insertion idx, put the low elt of V2 here.
5069 MaskVec.push_back(i == Idx ? NumElems : i);
5070 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5073 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5074 /// target specific opcode. Returns true if the Mask could be calculated.
5075 /// Sets IsUnary to true if only uses one source.
5076 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5077 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5078 unsigned NumElems = VT.getVectorNumElements();
5082 switch(N->getOpcode()) {
5084 ImmN = N->getOperand(N->getNumOperands()-1);
5085 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5087 case X86ISD::UNPCKH:
5088 DecodeUNPCKHMask(VT, Mask);
5090 case X86ISD::UNPCKL:
5091 DecodeUNPCKLMask(VT, Mask);
5093 case X86ISD::MOVHLPS:
5094 DecodeMOVHLPSMask(NumElems, Mask);
5096 case X86ISD::MOVLHPS:
5097 DecodeMOVLHPSMask(NumElems, Mask);
5099 case X86ISD::PALIGNR:
5100 ImmN = N->getOperand(N->getNumOperands()-1);
5101 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5103 case X86ISD::PSHUFD:
5104 case X86ISD::VPERMILP:
5105 ImmN = N->getOperand(N->getNumOperands()-1);
5106 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5109 case X86ISD::PSHUFHW:
5110 ImmN = N->getOperand(N->getNumOperands()-1);
5111 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5114 case X86ISD::PSHUFLW:
5115 ImmN = N->getOperand(N->getNumOperands()-1);
5116 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5119 case X86ISD::VPERMI:
5120 ImmN = N->getOperand(N->getNumOperands()-1);
5121 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5125 case X86ISD::MOVSD: {
5126 // The index 0 always comes from the first element of the second source,
5127 // this is why MOVSS and MOVSD are used in the first place. The other
5128 // elements come from the other positions of the first source vector
5129 Mask.push_back(NumElems);
5130 for (unsigned i = 1; i != NumElems; ++i) {
5135 case X86ISD::VPERM2X128:
5136 ImmN = N->getOperand(N->getNumOperands()-1);
5137 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5138 if (Mask.empty()) return false;
5140 case X86ISD::MOVDDUP:
5141 case X86ISD::MOVLHPD:
5142 case X86ISD::MOVLPD:
5143 case X86ISD::MOVLPS:
5144 case X86ISD::MOVSHDUP:
5145 case X86ISD::MOVSLDUP:
5146 // Not yet implemented
5148 default: llvm_unreachable("unknown target shuffle node");
5154 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5155 /// element of the result of the vector shuffle.
5156 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5159 return SDValue(); // Limit search depth.
5161 SDValue V = SDValue(N, 0);
5162 EVT VT = V.getValueType();
5163 unsigned Opcode = V.getOpcode();
5165 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5166 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5167 int Elt = SV->getMaskElt(Index);
5170 return DAG.getUNDEF(VT.getVectorElementType());
5172 unsigned NumElems = VT.getVectorNumElements();
5173 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5174 : SV->getOperand(1);
5175 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5178 // Recurse into target specific vector shuffles to find scalars.
5179 if (isTargetShuffle(Opcode)) {
5180 MVT ShufVT = V.getSimpleValueType();
5181 unsigned NumElems = ShufVT.getVectorNumElements();
5182 SmallVector<int, 16> ShuffleMask;
5185 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5188 int Elt = ShuffleMask[Index];
5190 return DAG.getUNDEF(ShufVT.getVectorElementType());
5192 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5194 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5198 // Actual nodes that may contain scalar elements
5199 if (Opcode == ISD::BITCAST) {
5200 V = V.getOperand(0);
5201 EVT SrcVT = V.getValueType();
5202 unsigned NumElems = VT.getVectorNumElements();
5204 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5208 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5209 return (Index == 0) ? V.getOperand(0)
5210 : DAG.getUNDEF(VT.getVectorElementType());
5212 if (V.getOpcode() == ISD::BUILD_VECTOR)
5213 return V.getOperand(Index);
5218 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5219 /// shuffle operation which come from a consecutively from a zero. The
5220 /// search can start in two different directions, from left or right.
5221 /// We count undefs as zeros until PreferredNum is reached.
5222 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5223 unsigned NumElems, bool ZerosFromLeft,
5225 unsigned PreferredNum = -1U) {
5226 unsigned NumZeros = 0;
5227 for (unsigned i = 0; i != NumElems; ++i) {
5228 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5229 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5233 if (X86::isZeroNode(Elt))
5235 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5236 NumZeros = std::min(NumZeros + 1, PreferredNum);
5244 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5245 /// correspond consecutively to elements from one of the vector operands,
5246 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5248 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5249 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5250 unsigned NumElems, unsigned &OpNum) {
5251 bool SeenV1 = false;
5252 bool SeenV2 = false;
5254 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5255 int Idx = SVOp->getMaskElt(i);
5256 // Ignore undef indicies
5260 if (Idx < (int)NumElems)
5265 // Only accept consecutive elements from the same vector
5266 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5270 OpNum = SeenV1 ? 0 : 1;
5274 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5275 /// logical left shift of a vector.
5276 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5277 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5279 SVOp->getSimpleValueType(0).getVectorNumElements();
5280 unsigned NumZeros = getNumOfConsecutiveZeros(
5281 SVOp, NumElems, false /* check zeros from right */, DAG,
5282 SVOp->getMaskElt(0));
5288 // Considering the elements in the mask that are not consecutive zeros,
5289 // check if they consecutively come from only one of the source vectors.
5291 // V1 = {X, A, B, C} 0
5293 // vector_shuffle V1, V2 <1, 2, 3, X>
5295 if (!isShuffleMaskConsecutive(SVOp,
5296 0, // Mask Start Index
5297 NumElems-NumZeros, // Mask End Index(exclusive)
5298 NumZeros, // Where to start looking in the src vector
5299 NumElems, // Number of elements in vector
5300 OpSrc)) // Which source operand ?
5305 ShVal = SVOp->getOperand(OpSrc);
5309 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5310 /// logical left shift of a vector.
5311 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5312 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5314 SVOp->getSimpleValueType(0).getVectorNumElements();
5315 unsigned NumZeros = getNumOfConsecutiveZeros(
5316 SVOp, NumElems, true /* check zeros from left */, DAG,
5317 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5323 // Considering the elements in the mask that are not consecutive zeros,
5324 // check if they consecutively come from only one of the source vectors.
5326 // 0 { A, B, X, X } = V2
5328 // vector_shuffle V1, V2 <X, X, 4, 5>
5330 if (!isShuffleMaskConsecutive(SVOp,
5331 NumZeros, // Mask Start Index
5332 NumElems, // Mask End Index(exclusive)
5333 0, // Where to start looking in the src vector
5334 NumElems, // Number of elements in vector
5335 OpSrc)) // Which source operand ?
5340 ShVal = SVOp->getOperand(OpSrc);
5344 /// isVectorShift - Returns true if the shuffle can be implemented as a
5345 /// logical left or right shift of a vector.
5346 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5347 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5348 // Although the logic below support any bitwidth size, there are no
5349 // shift instructions which handle more than 128-bit vectors.
5350 if (!SVOp->getSimpleValueType(0).is128BitVector())
5353 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5354 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5360 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5362 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5363 unsigned NumNonZero, unsigned NumZero,
5365 const X86Subtarget* Subtarget,
5366 const TargetLowering &TLI) {
5373 for (unsigned i = 0; i < 16; ++i) {
5374 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5375 if (ThisIsNonZero && First) {
5377 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5379 V = DAG.getUNDEF(MVT::v8i16);
5384 SDValue ThisElt, LastElt;
5385 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5386 if (LastIsNonZero) {
5387 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5388 MVT::i16, Op.getOperand(i-1));
5390 if (ThisIsNonZero) {
5391 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5392 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5393 ThisElt, DAG.getConstant(8, MVT::i8));
5395 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5399 if (ThisElt.getNode())
5400 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5401 DAG.getIntPtrConstant(i/2));
5405 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5408 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5410 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5411 unsigned NumNonZero, unsigned NumZero,
5413 const X86Subtarget* Subtarget,
5414 const TargetLowering &TLI) {
5421 for (unsigned i = 0; i < 8; ++i) {
5422 bool isNonZero = (NonZeros & (1 << i)) != 0;
5426 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5428 V = DAG.getUNDEF(MVT::v8i16);
5431 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5432 MVT::v8i16, V, Op.getOperand(i),
5433 DAG.getIntPtrConstant(i));
5440 /// getVShift - Return a vector logical shift node.
5442 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5443 unsigned NumBits, SelectionDAG &DAG,
5444 const TargetLowering &TLI, SDLoc dl) {
5445 assert(VT.is128BitVector() && "Unknown type for VShift");
5446 EVT ShVT = MVT::v2i64;
5447 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5448 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5449 return DAG.getNode(ISD::BITCAST, dl, VT,
5450 DAG.getNode(Opc, dl, ShVT, SrcOp,
5451 DAG.getConstant(NumBits,
5452 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5456 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5458 // Check if the scalar load can be widened into a vector load. And if
5459 // the address is "base + cst" see if the cst can be "absorbed" into
5460 // the shuffle mask.
5461 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5462 SDValue Ptr = LD->getBasePtr();
5463 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5465 EVT PVT = LD->getValueType(0);
5466 if (PVT != MVT::i32 && PVT != MVT::f32)
5471 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5472 FI = FINode->getIndex();
5474 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5475 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5476 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5477 Offset = Ptr.getConstantOperandVal(1);
5478 Ptr = Ptr.getOperand(0);
5483 // FIXME: 256-bit vector instructions don't require a strict alignment,
5484 // improve this code to support it better.
5485 unsigned RequiredAlign = VT.getSizeInBits()/8;
5486 SDValue Chain = LD->getChain();
5487 // Make sure the stack object alignment is at least 16 or 32.
5488 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5489 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5490 if (MFI->isFixedObjectIndex(FI)) {
5491 // Can't change the alignment. FIXME: It's possible to compute
5492 // the exact stack offset and reference FI + adjust offset instead.
5493 // If someone *really* cares about this. That's the way to implement it.
5496 MFI->setObjectAlignment(FI, RequiredAlign);
5500 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5501 // Ptr + (Offset & ~15).
5504 if ((Offset % RequiredAlign) & 3)
5506 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5508 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5509 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5511 int EltNo = (Offset - StartOffset) >> 2;
5512 unsigned NumElems = VT.getVectorNumElements();
5514 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5515 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5516 LD->getPointerInfo().getWithOffset(StartOffset),
5517 false, false, false, 0);
5519 SmallVector<int, 8> Mask;
5520 for (unsigned i = 0; i != NumElems; ++i)
5521 Mask.push_back(EltNo);
5523 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5529 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5530 /// vector of type 'VT', see if the elements can be replaced by a single large
5531 /// load which has the same value as a build_vector whose operands are 'elts'.
5533 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5535 /// FIXME: we'd also like to handle the case where the last elements are zero
5536 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5537 /// There's even a handy isZeroNode for that purpose.
5538 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5539 SDLoc &DL, SelectionDAG &DAG,
5540 bool isAfterLegalize) {
5541 EVT EltVT = VT.getVectorElementType();
5542 unsigned NumElems = Elts.size();
5544 LoadSDNode *LDBase = nullptr;
5545 unsigned LastLoadedElt = -1U;
5547 // For each element in the initializer, see if we've found a load or an undef.
5548 // If we don't find an initial load element, or later load elements are
5549 // non-consecutive, bail out.
5550 for (unsigned i = 0; i < NumElems; ++i) {
5551 SDValue Elt = Elts[i];
5553 if (!Elt.getNode() ||
5554 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5557 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5559 LDBase = cast<LoadSDNode>(Elt.getNode());
5563 if (Elt.getOpcode() == ISD::UNDEF)
5566 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5567 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5572 // If we have found an entire vector of loads and undefs, then return a large
5573 // load of the entire vector width starting at the base pointer. If we found
5574 // consecutive loads for the low half, generate a vzext_load node.
5575 if (LastLoadedElt == NumElems - 1) {
5577 if (isAfterLegalize &&
5578 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5581 SDValue NewLd = SDValue();
5583 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5584 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5585 LDBase->getPointerInfo(),
5586 LDBase->isVolatile(), LDBase->isNonTemporal(),
5587 LDBase->isInvariant(), 0);
5588 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5589 LDBase->getPointerInfo(),
5590 LDBase->isVolatile(), LDBase->isNonTemporal(),
5591 LDBase->isInvariant(), LDBase->getAlignment());
5593 if (LDBase->hasAnyUseOfValue(1)) {
5594 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5596 SDValue(NewLd.getNode(), 1));
5597 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5598 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5599 SDValue(NewLd.getNode(), 1));
5604 if (NumElems == 4 && LastLoadedElt == 1 &&
5605 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5606 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5607 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5609 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5610 LDBase->getPointerInfo(),
5611 LDBase->getAlignment(),
5612 false/*isVolatile*/, true/*ReadMem*/,
5615 // Make sure the newly-created LOAD is in the same position as LDBase in
5616 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5617 // update uses of LDBase's output chain to use the TokenFactor.
5618 if (LDBase->hasAnyUseOfValue(1)) {
5619 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5620 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5621 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5622 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5623 SDValue(ResNode.getNode(), 1));
5626 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5631 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5632 /// to generate a splat value for the following cases:
5633 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5634 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5635 /// a scalar load, or a constant.
5636 /// The VBROADCAST node is returned when a pattern is found,
5637 /// or SDValue() otherwise.
5638 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5639 SelectionDAG &DAG) {
5640 if (!Subtarget->hasFp256())
5643 MVT VT = Op.getSimpleValueType();
5646 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5647 "Unsupported vector type for broadcast.");
5652 switch (Op.getOpcode()) {
5654 // Unknown pattern found.
5657 case ISD::BUILD_VECTOR: {
5658 // The BUILD_VECTOR node must be a splat.
5659 if (!isSplatVector(Op.getNode()))
5662 Ld = Op.getOperand(0);
5663 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5664 Ld.getOpcode() == ISD::ConstantFP);
5666 // The suspected load node has several users. Make sure that all
5667 // of its users are from the BUILD_VECTOR node.
5668 // Constants may have multiple users.
5669 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5674 case ISD::VECTOR_SHUFFLE: {
5675 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5677 // Shuffles must have a splat mask where the first element is
5679 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5682 SDValue Sc = Op.getOperand(0);
5683 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5684 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5686 if (!Subtarget->hasInt256())
5689 // Use the register form of the broadcast instruction available on AVX2.
5690 if (VT.getSizeInBits() >= 256)
5691 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5692 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5695 Ld = Sc.getOperand(0);
5696 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5697 Ld.getOpcode() == ISD::ConstantFP);
5699 // The scalar_to_vector node and the suspected
5700 // load node must have exactly one user.
5701 // Constants may have multiple users.
5703 // AVX-512 has register version of the broadcast
5704 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5705 Ld.getValueType().getSizeInBits() >= 32;
5706 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5713 bool IsGE256 = (VT.getSizeInBits() >= 256);
5715 // Handle the broadcasting a single constant scalar from the constant pool
5716 // into a vector. On Sandybridge it is still better to load a constant vector
5717 // from the constant pool and not to broadcast it from a scalar.
5718 if (ConstSplatVal && Subtarget->hasInt256()) {
5719 EVT CVT = Ld.getValueType();
5720 assert(!CVT.isVector() && "Must not broadcast a vector type");
5721 unsigned ScalarSize = CVT.getSizeInBits();
5723 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5724 const Constant *C = nullptr;
5725 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5726 C = CI->getConstantIntValue();
5727 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5728 C = CF->getConstantFPValue();
5730 assert(C && "Invalid constant type");
5732 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5733 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5734 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5735 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5736 MachinePointerInfo::getConstantPool(),
5737 false, false, false, Alignment);
5739 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5743 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5744 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5746 // Handle AVX2 in-register broadcasts.
5747 if (!IsLoad && Subtarget->hasInt256() &&
5748 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5749 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5751 // The scalar source must be a normal load.
5755 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5756 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5758 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5759 // double since there is no vbroadcastsd xmm
5760 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5761 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5762 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5765 // Unsupported broadcast.
5769 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5770 /// underlying vector and index.
5772 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5774 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5776 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5777 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5780 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5782 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5784 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5785 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5788 // In this case the vector is the extract_subvector expression and the index
5789 // is 2, as specified by the shuffle.
5790 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5791 SDValue ShuffleVec = SVOp->getOperand(0);
5792 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5793 assert(ShuffleVecVT.getVectorElementType() ==
5794 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5796 int ShuffleIdx = SVOp->getMaskElt(Idx);
5797 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5798 ExtractedFromVec = ShuffleVec;
5804 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5805 MVT VT = Op.getSimpleValueType();
5807 // Skip if insert_vec_elt is not supported.
5808 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5809 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5813 unsigned NumElems = Op.getNumOperands();
5817 SmallVector<unsigned, 4> InsertIndices;
5818 SmallVector<int, 8> Mask(NumElems, -1);
5820 for (unsigned i = 0; i != NumElems; ++i) {
5821 unsigned Opc = Op.getOperand(i).getOpcode();
5823 if (Opc == ISD::UNDEF)
5826 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5827 // Quit if more than 1 elements need inserting.
5828 if (InsertIndices.size() > 1)
5831 InsertIndices.push_back(i);
5835 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5836 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5837 // Quit if non-constant index.
5838 if (!isa<ConstantSDNode>(ExtIdx))
5840 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5842 // Quit if extracted from vector of different type.
5843 if (ExtractedFromVec.getValueType() != VT)
5846 if (!VecIn1.getNode())
5847 VecIn1 = ExtractedFromVec;
5848 else if (VecIn1 != ExtractedFromVec) {
5849 if (!VecIn2.getNode())
5850 VecIn2 = ExtractedFromVec;
5851 else if (VecIn2 != ExtractedFromVec)
5852 // Quit if more than 2 vectors to shuffle
5856 if (ExtractedFromVec == VecIn1)
5858 else if (ExtractedFromVec == VecIn2)
5859 Mask[i] = Idx + NumElems;
5862 if (!VecIn1.getNode())
5865 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5866 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5867 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5868 unsigned Idx = InsertIndices[i];
5869 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5870 DAG.getIntPtrConstant(Idx));
5876 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5878 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5880 MVT VT = Op.getSimpleValueType();
5881 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5882 "Unexpected type in LowerBUILD_VECTORvXi1!");
5885 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5886 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5887 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5888 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5891 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5892 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5893 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5894 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5897 bool AllContants = true;
5898 uint64_t Immediate = 0;
5899 int NonConstIdx = -1;
5900 bool IsSplat = true;
5901 unsigned NumNonConsts = 0;
5902 unsigned NumConsts = 0;
5903 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5904 SDValue In = Op.getOperand(idx);
5905 if (In.getOpcode() == ISD::UNDEF)
5907 if (!isa<ConstantSDNode>(In)) {
5908 AllContants = false;
5914 if (cast<ConstantSDNode>(In)->getZExtValue())
5915 Immediate |= (1ULL << idx);
5917 if (In != Op.getOperand(0))
5922 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5923 DAG.getConstant(Immediate, MVT::i16));
5924 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5925 DAG.getIntPtrConstant(0));
5928 if (NumNonConsts == 1 && NonConstIdx != 0) {
5931 SDValue VecAsImm = DAG.getConstant(Immediate,
5932 MVT::getIntegerVT(VT.getSizeInBits()));
5933 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5936 DstVec = DAG.getUNDEF(VT);
5937 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5938 Op.getOperand(NonConstIdx),
5939 DAG.getIntPtrConstant(NonConstIdx));
5941 if (!IsSplat && (NonConstIdx != 0))
5942 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5943 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5946 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5947 DAG.getConstant(-1, SelectVT),
5948 DAG.getConstant(0, SelectVT));
5950 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5951 DAG.getConstant((Immediate | 1), SelectVT),
5952 DAG.getConstant(Immediate, SelectVT));
5953 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5957 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5960 MVT VT = Op.getSimpleValueType();
5961 MVT ExtVT = VT.getVectorElementType();
5962 unsigned NumElems = Op.getNumOperands();
5964 // Generate vectors for predicate vectors.
5965 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5966 return LowerBUILD_VECTORvXi1(Op, DAG);
5968 // Vectors containing all zeros can be matched by pxor and xorps later
5969 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5970 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5971 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5972 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5975 return getZeroVector(VT, Subtarget, DAG, dl);
5978 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5979 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5980 // vpcmpeqd on 256-bit vectors.
5981 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5982 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5985 if (!VT.is512BitVector())
5986 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5989 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5990 if (Broadcast.getNode())
5993 unsigned EVTBits = ExtVT.getSizeInBits();
5995 unsigned NumZero = 0;
5996 unsigned NumNonZero = 0;
5997 unsigned NonZeros = 0;
5998 bool IsAllConstants = true;
5999 SmallSet<SDValue, 8> Values;
6000 for (unsigned i = 0; i < NumElems; ++i) {
6001 SDValue Elt = Op.getOperand(i);
6002 if (Elt.getOpcode() == ISD::UNDEF)
6005 if (Elt.getOpcode() != ISD::Constant &&
6006 Elt.getOpcode() != ISD::ConstantFP)
6007 IsAllConstants = false;
6008 if (X86::isZeroNode(Elt))
6011 NonZeros |= (1 << i);
6016 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6017 if (NumNonZero == 0)
6018 return DAG.getUNDEF(VT);
6020 // Special case for single non-zero, non-undef, element.
6021 if (NumNonZero == 1) {
6022 unsigned Idx = countTrailingZeros(NonZeros);
6023 SDValue Item = Op.getOperand(Idx);
6025 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6026 // the value are obviously zero, truncate the value to i32 and do the
6027 // insertion that way. Only do this if the value is non-constant or if the
6028 // value is a constant being inserted into element 0. It is cheaper to do
6029 // a constant pool load than it is to do a movd + shuffle.
6030 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6031 (!IsAllConstants || Idx == 0)) {
6032 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6034 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6035 EVT VecVT = MVT::v4i32;
6036 unsigned VecElts = 4;
6038 // Truncate the value (which may itself be a constant) to i32, and
6039 // convert it to a vector with movd (S2V+shuffle to zero extend).
6040 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6041 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6042 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6044 // Now we have our 32-bit value zero extended in the low element of
6045 // a vector. If Idx != 0, swizzle it into place.
6047 SmallVector<int, 4> Mask;
6048 Mask.push_back(Idx);
6049 for (unsigned i = 1; i != VecElts; ++i)
6051 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6054 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6058 // If we have a constant or non-constant insertion into the low element of
6059 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6060 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6061 // depending on what the source datatype is.
6064 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6066 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6067 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6068 if (VT.is256BitVector() || VT.is512BitVector()) {
6069 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6070 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6071 Item, DAG.getIntPtrConstant(0));
6073 assert(VT.is128BitVector() && "Expected an SSE value type!");
6074 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6075 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6076 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6079 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6080 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6081 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6082 if (VT.is256BitVector()) {
6083 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6084 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6086 assert(VT.is128BitVector() && "Expected an SSE value type!");
6087 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6089 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6093 // Is it a vector logical left shift?
6094 if (NumElems == 2 && Idx == 1 &&
6095 X86::isZeroNode(Op.getOperand(0)) &&
6096 !X86::isZeroNode(Op.getOperand(1))) {
6097 unsigned NumBits = VT.getSizeInBits();
6098 return getVShift(true, VT,
6099 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6100 VT, Op.getOperand(1)),
6101 NumBits/2, DAG, *this, dl);
6104 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6107 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6108 // is a non-constant being inserted into an element other than the low one,
6109 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6110 // movd/movss) to move this into the low element, then shuffle it into
6112 if (EVTBits == 32) {
6113 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6115 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6116 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6117 SmallVector<int, 8> MaskVec;
6118 for (unsigned i = 0; i != NumElems; ++i)
6119 MaskVec.push_back(i == Idx ? 0 : 1);
6120 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6124 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6125 if (Values.size() == 1) {
6126 if (EVTBits == 32) {
6127 // Instead of a shuffle like this:
6128 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6129 // Check if it's possible to issue this instead.
6130 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6131 unsigned Idx = countTrailingZeros(NonZeros);
6132 SDValue Item = Op.getOperand(Idx);
6133 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6134 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6139 // A vector full of immediates; various special cases are already
6140 // handled, so this is best done with a single constant-pool load.
6144 // For AVX-length vectors, build the individual 128-bit pieces and use
6145 // shuffles to put them in place.
6146 if (VT.is256BitVector() || VT.is512BitVector()) {
6147 SmallVector<SDValue, 64> V;
6148 for (unsigned i = 0; i != NumElems; ++i)
6149 V.push_back(Op.getOperand(i));
6151 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6153 // Build both the lower and upper subvector.
6154 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6155 makeArrayRef(&V[0], NumElems/2));
6156 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6157 makeArrayRef(&V[NumElems / 2], NumElems/2));
6159 // Recreate the wider vector with the lower and upper part.
6160 if (VT.is256BitVector())
6161 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6162 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6165 // Let legalizer expand 2-wide build_vectors.
6166 if (EVTBits == 64) {
6167 if (NumNonZero == 1) {
6168 // One half is zero or undef.
6169 unsigned Idx = countTrailingZeros(NonZeros);
6170 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6171 Op.getOperand(Idx));
6172 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6177 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6178 if (EVTBits == 8 && NumElems == 16) {
6179 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6181 if (V.getNode()) return V;
6184 if (EVTBits == 16 && NumElems == 8) {
6185 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6187 if (V.getNode()) return V;
6190 // If element VT is == 32 bits, turn it into a number of shuffles.
6191 SmallVector<SDValue, 8> V(NumElems);
6192 if (NumElems == 4 && NumZero > 0) {
6193 for (unsigned i = 0; i < 4; ++i) {
6194 bool isZero = !(NonZeros & (1 << i));
6196 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6198 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6201 for (unsigned i = 0; i < 2; ++i) {
6202 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6205 V[i] = V[i*2]; // Must be a zero vector.
6208 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6211 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6214 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6219 bool Reverse1 = (NonZeros & 0x3) == 2;
6220 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6224 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6225 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6227 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6230 if (Values.size() > 1 && VT.is128BitVector()) {
6231 // Check for a build vector of consecutive loads.
6232 for (unsigned i = 0; i < NumElems; ++i)
6233 V[i] = Op.getOperand(i);
6235 // Check for elements which are consecutive loads.
6236 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6240 // Check for a build vector from mostly shuffle plus few inserting.
6241 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6245 // For SSE 4.1, use insertps to put the high elements into the low element.
6246 if (getSubtarget()->hasSSE41()) {
6248 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6249 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6251 Result = DAG.getUNDEF(VT);
6253 for (unsigned i = 1; i < NumElems; ++i) {
6254 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6255 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6256 Op.getOperand(i), DAG.getIntPtrConstant(i));
6261 // Otherwise, expand into a number of unpckl*, start by extending each of
6262 // our (non-undef) elements to the full vector width with the element in the
6263 // bottom slot of the vector (which generates no code for SSE).
6264 for (unsigned i = 0; i < NumElems; ++i) {
6265 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6266 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6268 V[i] = DAG.getUNDEF(VT);
6271 // Next, we iteratively mix elements, e.g. for v4f32:
6272 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6273 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6274 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6275 unsigned EltStride = NumElems >> 1;
6276 while (EltStride != 0) {
6277 for (unsigned i = 0; i < EltStride; ++i) {
6278 // If V[i+EltStride] is undef and this is the first round of mixing,
6279 // then it is safe to just drop this shuffle: V[i] is already in the
6280 // right place, the one element (since it's the first round) being
6281 // inserted as undef can be dropped. This isn't safe for successive
6282 // rounds because they will permute elements within both vectors.
6283 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6284 EltStride == NumElems/2)
6287 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6296 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6297 // to create 256-bit vectors from two other 128-bit ones.
6298 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6300 MVT ResVT = Op.getSimpleValueType();
6302 assert((ResVT.is256BitVector() ||
6303 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6305 SDValue V1 = Op.getOperand(0);
6306 SDValue V2 = Op.getOperand(1);
6307 unsigned NumElems = ResVT.getVectorNumElements();
6308 if(ResVT.is256BitVector())
6309 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6311 if (Op.getNumOperands() == 4) {
6312 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6313 ResVT.getVectorNumElements()/2);
6314 SDValue V3 = Op.getOperand(2);
6315 SDValue V4 = Op.getOperand(3);
6316 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6317 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6319 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6322 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6323 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6324 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6325 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6326 Op.getNumOperands() == 4)));
6328 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6329 // from two other 128-bit ones.
6331 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6332 return LowerAVXCONCAT_VECTORS(Op, DAG);
6335 // Try to lower a shuffle node into a simple blend instruction.
6337 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6338 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6339 SDValue V1 = SVOp->getOperand(0);
6340 SDValue V2 = SVOp->getOperand(1);
6342 MVT VT = SVOp->getSimpleValueType(0);
6343 MVT EltVT = VT.getVectorElementType();
6344 unsigned NumElems = VT.getVectorNumElements();
6346 // There is no blend with immediate in AVX-512.
6347 if (VT.is512BitVector())
6350 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6352 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6355 // Check the mask for BLEND and build the value.
6356 unsigned MaskValue = 0;
6357 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6358 unsigned NumLanes = (NumElems-1)/8 + 1;
6359 unsigned NumElemsInLane = NumElems / NumLanes;
6361 // Blend for v16i16 should be symetric for the both lanes.
6362 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6364 int SndLaneEltIdx = (NumLanes == 2) ?
6365 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6366 int EltIdx = SVOp->getMaskElt(i);
6368 if ((EltIdx < 0 || EltIdx == (int)i) &&
6369 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6372 if (((unsigned)EltIdx == (i + NumElems)) &&
6373 (SndLaneEltIdx < 0 ||
6374 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6375 MaskValue |= (1<<i);
6380 // Convert i32 vectors to floating point if it is not AVX2.
6381 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6383 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6384 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6386 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6387 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6390 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6391 DAG.getConstant(MaskValue, MVT::i32));
6392 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6395 /// In vector type \p VT, return true if the element at index \p InputIdx
6396 /// falls on a different 128-bit lane than \p OutputIdx.
6397 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6398 unsigned OutputIdx) {
6399 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6400 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6403 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6404 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6405 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6406 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6408 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6409 SelectionDAG &DAG) {
6410 MVT VT = V1.getSimpleValueType();
6411 assert(VT.is128BitVector() || VT.is256BitVector());
6413 MVT EltVT = VT.getVectorElementType();
6414 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6415 unsigned NumElts = VT.getVectorNumElements();
6417 SmallVector<SDValue, 32> PshufbMask;
6418 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6419 int InputIdx = MaskVals[OutputIdx];
6420 unsigned InputByteIdx;
6422 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6423 InputByteIdx = 0x80;
6425 // Cross lane is not allowed.
6426 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6428 InputByteIdx = InputIdx * EltSizeInBytes;
6429 // Index is an byte offset within the 128-bit lane.
6430 InputByteIdx &= 0xf;
6433 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6434 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6435 if (InputByteIdx != 0x80)
6440 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6442 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6443 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6444 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6447 // v8i16 shuffles - Prefer shuffles in the following order:
6448 // 1. [all] pshuflw, pshufhw, optional move
6449 // 2. [ssse3] 1 x pshufb
6450 // 3. [ssse3] 2 x pshufb + 1 x por
6451 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6453 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6454 SelectionDAG &DAG) {
6455 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6456 SDValue V1 = SVOp->getOperand(0);
6457 SDValue V2 = SVOp->getOperand(1);
6459 SmallVector<int, 8> MaskVals;
6461 // Determine if more than 1 of the words in each of the low and high quadwords
6462 // of the result come from the same quadword of one of the two inputs. Undef
6463 // mask values count as coming from any quadword, for better codegen.
6465 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6466 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6467 unsigned LoQuad[] = { 0, 0, 0, 0 };
6468 unsigned HiQuad[] = { 0, 0, 0, 0 };
6469 // Indices of quads used.
6470 std::bitset<4> InputQuads;
6471 for (unsigned i = 0; i < 8; ++i) {
6472 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6473 int EltIdx = SVOp->getMaskElt(i);
6474 MaskVals.push_back(EltIdx);
6483 InputQuads.set(EltIdx / 4);
6486 int BestLoQuad = -1;
6487 unsigned MaxQuad = 1;
6488 for (unsigned i = 0; i < 4; ++i) {
6489 if (LoQuad[i] > MaxQuad) {
6491 MaxQuad = LoQuad[i];
6495 int BestHiQuad = -1;
6497 for (unsigned i = 0; i < 4; ++i) {
6498 if (HiQuad[i] > MaxQuad) {
6500 MaxQuad = HiQuad[i];
6504 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6505 // of the two input vectors, shuffle them into one input vector so only a
6506 // single pshufb instruction is necessary. If there are more than 2 input
6507 // quads, disable the next transformation since it does not help SSSE3.
6508 bool V1Used = InputQuads[0] || InputQuads[1];
6509 bool V2Used = InputQuads[2] || InputQuads[3];
6510 if (Subtarget->hasSSSE3()) {
6511 if (InputQuads.count() == 2 && V1Used && V2Used) {
6512 BestLoQuad = InputQuads[0] ? 0 : 1;
6513 BestHiQuad = InputQuads[2] ? 2 : 3;
6515 if (InputQuads.count() > 2) {
6521 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6522 // the shuffle mask. If a quad is scored as -1, that means that it contains
6523 // words from all 4 input quadwords.
6525 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6527 BestLoQuad < 0 ? 0 : BestLoQuad,
6528 BestHiQuad < 0 ? 1 : BestHiQuad
6530 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6531 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6532 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6533 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6535 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6536 // source words for the shuffle, to aid later transformations.
6537 bool AllWordsInNewV = true;
6538 bool InOrder[2] = { true, true };
6539 for (unsigned i = 0; i != 8; ++i) {
6540 int idx = MaskVals[i];
6542 InOrder[i/4] = false;
6543 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6545 AllWordsInNewV = false;
6549 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6550 if (AllWordsInNewV) {
6551 for (int i = 0; i != 8; ++i) {
6552 int idx = MaskVals[i];
6555 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6556 if ((idx != i) && idx < 4)
6558 if ((idx != i) && idx > 3)
6567 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6568 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6569 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6570 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6571 unsigned TargetMask = 0;
6572 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6573 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6574 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6575 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6576 getShufflePSHUFLWImmediate(SVOp);
6577 V1 = NewV.getOperand(0);
6578 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6582 // Promote splats to a larger type which usually leads to more efficient code.
6583 // FIXME: Is this true if pshufb is available?
6584 if (SVOp->isSplat())
6585 return PromoteSplat(SVOp, DAG);
6587 // If we have SSSE3, and all words of the result are from 1 input vector,
6588 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6589 // is present, fall back to case 4.
6590 if (Subtarget->hasSSSE3()) {
6591 SmallVector<SDValue,16> pshufbMask;
6593 // If we have elements from both input vectors, set the high bit of the
6594 // shuffle mask element to zero out elements that come from V2 in the V1
6595 // mask, and elements that come from V1 in the V2 mask, so that the two
6596 // results can be OR'd together.
6597 bool TwoInputs = V1Used && V2Used;
6598 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6600 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6602 // Calculate the shuffle mask for the second input, shuffle it, and
6603 // OR it with the first shuffled input.
6604 CommuteVectorShuffleMask(MaskVals, 8);
6605 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6606 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6607 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6610 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6611 // and update MaskVals with new element order.
6612 std::bitset<8> InOrder;
6613 if (BestLoQuad >= 0) {
6614 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6615 for (int i = 0; i != 4; ++i) {
6616 int idx = MaskVals[i];
6619 } else if ((idx / 4) == BestLoQuad) {
6624 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6627 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6628 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6629 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6631 getShufflePSHUFLWImmediate(SVOp), DAG);
6635 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6636 // and update MaskVals with the new element order.
6637 if (BestHiQuad >= 0) {
6638 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6639 for (unsigned i = 4; i != 8; ++i) {
6640 int idx = MaskVals[i];
6643 } else if ((idx / 4) == BestHiQuad) {
6644 MaskV[i] = (idx & 3) + 4;
6648 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6651 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6652 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6653 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6655 getShufflePSHUFHWImmediate(SVOp), DAG);
6659 // In case BestHi & BestLo were both -1, which means each quadword has a word
6660 // from each of the four input quadwords, calculate the InOrder bitvector now
6661 // before falling through to the insert/extract cleanup.
6662 if (BestLoQuad == -1 && BestHiQuad == -1) {
6664 for (int i = 0; i != 8; ++i)
6665 if (MaskVals[i] < 0 || MaskVals[i] == i)
6669 // The other elements are put in the right place using pextrw and pinsrw.
6670 for (unsigned i = 0; i != 8; ++i) {
6673 int EltIdx = MaskVals[i];
6676 SDValue ExtOp = (EltIdx < 8) ?
6677 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6678 DAG.getIntPtrConstant(EltIdx)) :
6679 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6680 DAG.getIntPtrConstant(EltIdx - 8));
6681 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6682 DAG.getIntPtrConstant(i));
6687 /// \brief v16i16 shuffles
6689 /// FIXME: We only support generation of a single pshufb currently. We can
6690 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6691 /// well (e.g 2 x pshufb + 1 x por).
6693 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6694 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6695 SDValue V1 = SVOp->getOperand(0);
6696 SDValue V2 = SVOp->getOperand(1);
6699 if (V2.getOpcode() != ISD::UNDEF)
6702 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6703 return getPSHUFB(MaskVals, V1, dl, DAG);
6706 // v16i8 shuffles - Prefer shuffles in the following order:
6707 // 1. [ssse3] 1 x pshufb
6708 // 2. [ssse3] 2 x pshufb + 1 x por
6709 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6710 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6711 const X86Subtarget* Subtarget,
6712 SelectionDAG &DAG) {
6713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6714 SDValue V1 = SVOp->getOperand(0);
6715 SDValue V2 = SVOp->getOperand(1);
6717 ArrayRef<int> MaskVals = SVOp->getMask();
6719 // Promote splats to a larger type which usually leads to more efficient code.
6720 // FIXME: Is this true if pshufb is available?
6721 if (SVOp->isSplat())
6722 return PromoteSplat(SVOp, DAG);
6724 // If we have SSSE3, case 1 is generated when all result bytes come from
6725 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6726 // present, fall back to case 3.
6728 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6729 if (Subtarget->hasSSSE3()) {
6730 SmallVector<SDValue,16> pshufbMask;
6732 // If all result elements are from one input vector, then only translate
6733 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6735 // Otherwise, we have elements from both input vectors, and must zero out
6736 // elements that come from V2 in the first mask, and V1 in the second mask
6737 // so that we can OR them together.
6738 for (unsigned i = 0; i != 16; ++i) {
6739 int EltIdx = MaskVals[i];
6740 if (EltIdx < 0 || EltIdx >= 16)
6742 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6744 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6745 DAG.getNode(ISD::BUILD_VECTOR, dl,
6746 MVT::v16i8, pshufbMask));
6748 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6749 // the 2nd operand if it's undefined or zero.
6750 if (V2.getOpcode() == ISD::UNDEF ||
6751 ISD::isBuildVectorAllZeros(V2.getNode()))
6754 // Calculate the shuffle mask for the second input, shuffle it, and
6755 // OR it with the first shuffled input.
6757 for (unsigned i = 0; i != 16; ++i) {
6758 int EltIdx = MaskVals[i];
6759 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6760 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6762 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6763 DAG.getNode(ISD::BUILD_VECTOR, dl,
6764 MVT::v16i8, pshufbMask));
6765 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6768 // No SSSE3 - Calculate in place words and then fix all out of place words
6769 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6770 // the 16 different words that comprise the two doublequadword input vectors.
6771 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6772 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6774 for (int i = 0; i != 8; ++i) {
6775 int Elt0 = MaskVals[i*2];
6776 int Elt1 = MaskVals[i*2+1];
6778 // This word of the result is all undef, skip it.
6779 if (Elt0 < 0 && Elt1 < 0)
6782 // This word of the result is already in the correct place, skip it.
6783 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6786 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6787 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6790 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6791 // using a single extract together, load it and store it.
6792 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6793 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6794 DAG.getIntPtrConstant(Elt1 / 2));
6795 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6796 DAG.getIntPtrConstant(i));
6800 // If Elt1 is defined, extract it from the appropriate source. If the
6801 // source byte is not also odd, shift the extracted word left 8 bits
6802 // otherwise clear the bottom 8 bits if we need to do an or.
6804 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6805 DAG.getIntPtrConstant(Elt1 / 2));
6806 if ((Elt1 & 1) == 0)
6807 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6809 TLI.getShiftAmountTy(InsElt.getValueType())));
6811 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6812 DAG.getConstant(0xFF00, MVT::i16));
6814 // If Elt0 is defined, extract it from the appropriate source. If the
6815 // source byte is not also even, shift the extracted word right 8 bits. If
6816 // Elt1 was also defined, OR the extracted values together before
6817 // inserting them in the result.
6819 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6820 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6821 if ((Elt0 & 1) != 0)
6822 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6824 TLI.getShiftAmountTy(InsElt0.getValueType())));
6826 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6827 DAG.getConstant(0x00FF, MVT::i16));
6828 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6831 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6832 DAG.getIntPtrConstant(i));
6834 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6837 // v32i8 shuffles - Translate to VPSHUFB if possible.
6839 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6840 const X86Subtarget *Subtarget,
6841 SelectionDAG &DAG) {
6842 MVT VT = SVOp->getSimpleValueType(0);
6843 SDValue V1 = SVOp->getOperand(0);
6844 SDValue V2 = SVOp->getOperand(1);
6846 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6848 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6849 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6850 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6852 // VPSHUFB may be generated if
6853 // (1) one of input vector is undefined or zeroinitializer.
6854 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6855 // And (2) the mask indexes don't cross the 128-bit lane.
6856 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6857 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6860 if (V1IsAllZero && !V2IsAllZero) {
6861 CommuteVectorShuffleMask(MaskVals, 32);
6864 return getPSHUFB(MaskVals, V1, dl, DAG);
6867 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6868 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6869 /// done when every pair / quad of shuffle mask elements point to elements in
6870 /// the right sequence. e.g.
6871 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6873 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6874 SelectionDAG &DAG) {
6875 MVT VT = SVOp->getSimpleValueType(0);
6877 unsigned NumElems = VT.getVectorNumElements();
6880 switch (VT.SimpleTy) {
6881 default: llvm_unreachable("Unexpected!");
6882 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6883 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6884 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6885 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6886 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6887 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6890 SmallVector<int, 8> MaskVec;
6891 for (unsigned i = 0; i != NumElems; i += Scale) {
6893 for (unsigned j = 0; j != Scale; ++j) {
6894 int EltIdx = SVOp->getMaskElt(i+j);
6898 StartIdx = (EltIdx / Scale);
6899 if (EltIdx != (int)(StartIdx*Scale + j))
6902 MaskVec.push_back(StartIdx);
6905 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6906 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6907 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6910 /// getVZextMovL - Return a zero-extending vector move low node.
6912 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6913 SDValue SrcOp, SelectionDAG &DAG,
6914 const X86Subtarget *Subtarget, SDLoc dl) {
6915 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6916 LoadSDNode *LD = nullptr;
6917 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6918 LD = dyn_cast<LoadSDNode>(SrcOp);
6920 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6922 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6923 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6924 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6925 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6926 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6928 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6929 return DAG.getNode(ISD::BITCAST, dl, VT,
6930 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6931 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6939 return DAG.getNode(ISD::BITCAST, dl, VT,
6940 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6941 DAG.getNode(ISD::BITCAST, dl,
6945 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6946 /// which could not be matched by any known target speficic shuffle
6948 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6950 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6951 if (NewOp.getNode())
6954 MVT VT = SVOp->getSimpleValueType(0);
6956 unsigned NumElems = VT.getVectorNumElements();
6957 unsigned NumLaneElems = NumElems / 2;
6960 MVT EltVT = VT.getVectorElementType();
6961 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6964 SmallVector<int, 16> Mask;
6965 for (unsigned l = 0; l < 2; ++l) {
6966 // Build a shuffle mask for the output, discovering on the fly which
6967 // input vectors to use as shuffle operands (recorded in InputUsed).
6968 // If building a suitable shuffle vector proves too hard, then bail
6969 // out with UseBuildVector set.
6970 bool UseBuildVector = false;
6971 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6972 unsigned LaneStart = l * NumLaneElems;
6973 for (unsigned i = 0; i != NumLaneElems; ++i) {
6974 // The mask element. This indexes into the input.
6975 int Idx = SVOp->getMaskElt(i+LaneStart);
6977 // the mask element does not index into any input vector.
6982 // The input vector this mask element indexes into.
6983 int Input = Idx / NumLaneElems;
6985 // Turn the index into an offset from the start of the input vector.
6986 Idx -= Input * NumLaneElems;
6988 // Find or create a shuffle vector operand to hold this input.
6990 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6991 if (InputUsed[OpNo] == Input)
6992 // This input vector is already an operand.
6994 if (InputUsed[OpNo] < 0) {
6995 // Create a new operand for this input vector.
6996 InputUsed[OpNo] = Input;
7001 if (OpNo >= array_lengthof(InputUsed)) {
7002 // More than two input vectors used! Give up on trying to create a
7003 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7004 UseBuildVector = true;
7008 // Add the mask index for the new shuffle vector.
7009 Mask.push_back(Idx + OpNo * NumLaneElems);
7012 if (UseBuildVector) {
7013 SmallVector<SDValue, 16> SVOps;
7014 for (unsigned i = 0; i != NumLaneElems; ++i) {
7015 // The mask element. This indexes into the input.
7016 int Idx = SVOp->getMaskElt(i+LaneStart);
7018 SVOps.push_back(DAG.getUNDEF(EltVT));
7022 // The input vector this mask element indexes into.
7023 int Input = Idx / NumElems;
7025 // Turn the index into an offset from the start of the input vector.
7026 Idx -= Input * NumElems;
7028 // Extract the vector element by hand.
7029 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7030 SVOp->getOperand(Input),
7031 DAG.getIntPtrConstant(Idx)));
7034 // Construct the output using a BUILD_VECTOR.
7035 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7036 } else if (InputUsed[0] < 0) {
7037 // No input vectors were used! The result is undefined.
7038 Output[l] = DAG.getUNDEF(NVT);
7040 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7041 (InputUsed[0] % 2) * NumLaneElems,
7043 // If only one input was used, use an undefined vector for the other.
7044 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7045 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7046 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7047 // At least one input vector was used. Create a new shuffle vector.
7048 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7054 // Concatenate the result back
7055 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7058 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7059 /// 4 elements, and match them with several different shuffle types.
7061 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7062 SDValue V1 = SVOp->getOperand(0);
7063 SDValue V2 = SVOp->getOperand(1);
7065 MVT VT = SVOp->getSimpleValueType(0);
7067 assert(VT.is128BitVector() && "Unsupported vector size");
7069 std::pair<int, int> Locs[4];
7070 int Mask1[] = { -1, -1, -1, -1 };
7071 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7075 for (unsigned i = 0; i != 4; ++i) {
7076 int Idx = PermMask[i];
7078 Locs[i] = std::make_pair(-1, -1);
7080 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7082 Locs[i] = std::make_pair(0, NumLo);
7086 Locs[i] = std::make_pair(1, NumHi);
7088 Mask1[2+NumHi] = Idx;
7094 if (NumLo <= 2 && NumHi <= 2) {
7095 // If no more than two elements come from either vector. This can be
7096 // implemented with two shuffles. First shuffle gather the elements.
7097 // The second shuffle, which takes the first shuffle as both of its
7098 // vector operands, put the elements into the right order.
7099 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7101 int Mask2[] = { -1, -1, -1, -1 };
7103 for (unsigned i = 0; i != 4; ++i)
7104 if (Locs[i].first != -1) {
7105 unsigned Idx = (i < 2) ? 0 : 4;
7106 Idx += Locs[i].first * 2 + Locs[i].second;
7110 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7113 if (NumLo == 3 || NumHi == 3) {
7114 // Otherwise, we must have three elements from one vector, call it X, and
7115 // one element from the other, call it Y. First, use a shufps to build an
7116 // intermediate vector with the one element from Y and the element from X
7117 // that will be in the same half in the final destination (the indexes don't
7118 // matter). Then, use a shufps to build the final vector, taking the half
7119 // containing the element from Y from the intermediate, and the other half
7122 // Normalize it so the 3 elements come from V1.
7123 CommuteVectorShuffleMask(PermMask, 4);
7127 // Find the element from V2.
7129 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7130 int Val = PermMask[HiIndex];
7137 Mask1[0] = PermMask[HiIndex];
7139 Mask1[2] = PermMask[HiIndex^1];
7141 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7144 Mask1[0] = PermMask[0];
7145 Mask1[1] = PermMask[1];
7146 Mask1[2] = HiIndex & 1 ? 6 : 4;
7147 Mask1[3] = HiIndex & 1 ? 4 : 6;
7148 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7151 Mask1[0] = HiIndex & 1 ? 2 : 0;
7152 Mask1[1] = HiIndex & 1 ? 0 : 2;
7153 Mask1[2] = PermMask[2];
7154 Mask1[3] = PermMask[3];
7159 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7162 // Break it into (shuffle shuffle_hi, shuffle_lo).
7163 int LoMask[] = { -1, -1, -1, -1 };
7164 int HiMask[] = { -1, -1, -1, -1 };
7166 int *MaskPtr = LoMask;
7167 unsigned MaskIdx = 0;
7170 for (unsigned i = 0; i != 4; ++i) {
7177 int Idx = PermMask[i];
7179 Locs[i] = std::make_pair(-1, -1);
7180 } else if (Idx < 4) {
7181 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7182 MaskPtr[LoIdx] = Idx;
7185 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7186 MaskPtr[HiIdx] = Idx;
7191 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7192 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7193 int MaskOps[] = { -1, -1, -1, -1 };
7194 for (unsigned i = 0; i != 4; ++i)
7195 if (Locs[i].first != -1)
7196 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7197 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7200 static bool MayFoldVectorLoad(SDValue V) {
7201 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7202 V = V.getOperand(0);
7204 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7205 V = V.getOperand(0);
7206 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7207 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7208 // BUILD_VECTOR (load), undef
7209 V = V.getOperand(0);
7211 return MayFoldLoad(V);
7215 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7216 MVT VT = Op.getSimpleValueType();
7218 // Canonizalize to v2f64.
7219 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7220 return DAG.getNode(ISD::BITCAST, dl, VT,
7221 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7226 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7228 SDValue V1 = Op.getOperand(0);
7229 SDValue V2 = Op.getOperand(1);
7230 MVT VT = Op.getSimpleValueType();
7232 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7234 if (HasSSE2 && VT == MVT::v2f64)
7235 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7237 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7238 return DAG.getNode(ISD::BITCAST, dl, VT,
7239 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7240 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7241 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7245 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7246 SDValue V1 = Op.getOperand(0);
7247 SDValue V2 = Op.getOperand(1);
7248 MVT VT = Op.getSimpleValueType();
7250 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7251 "unsupported shuffle type");
7253 if (V2.getOpcode() == ISD::UNDEF)
7257 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7261 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7262 SDValue V1 = Op.getOperand(0);
7263 SDValue V2 = Op.getOperand(1);
7264 MVT VT = Op.getSimpleValueType();
7265 unsigned NumElems = VT.getVectorNumElements();
7267 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7268 // operand of these instructions is only memory, so check if there's a
7269 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7271 bool CanFoldLoad = false;
7273 // Trivial case, when V2 comes from a load.
7274 if (MayFoldVectorLoad(V2))
7277 // When V1 is a load, it can be folded later into a store in isel, example:
7278 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7280 // (MOVLPSmr addr:$src1, VR128:$src2)
7281 // So, recognize this potential and also use MOVLPS or MOVLPD
7282 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7285 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7287 if (HasSSE2 && NumElems == 2)
7288 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7291 // If we don't care about the second element, proceed to use movss.
7292 if (SVOp->getMaskElt(1) != -1)
7293 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7296 // movl and movlp will both match v2i64, but v2i64 is never matched by
7297 // movl earlier because we make it strict to avoid messing with the movlp load
7298 // folding logic (see the code above getMOVLP call). Match it here then,
7299 // this is horrible, but will stay like this until we move all shuffle
7300 // matching to x86 specific nodes. Note that for the 1st condition all
7301 // types are matched with movsd.
7303 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7304 // as to remove this logic from here, as much as possible
7305 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7306 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7307 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7310 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7312 // Invert the operand order and use SHUFPS to match it.
7313 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7314 getShuffleSHUFImmediate(SVOp), DAG);
7317 // It is only safe to call this function if isINSERTPSMask is true for
7318 // this shufflevector mask.
7319 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7320 SelectionDAG &DAG) {
7321 // Generate an insertps instruction when inserting an f32 from memory onto a
7322 // v4f32 or when copying a member from one v4f32 to another.
7323 // We also use it for transferring i32 from one register to another,
7324 // since it simply copies the same bits.
7325 // If we're transfering an i32 from memory to a specific element in a
7326 // register, we output a generic DAG that will match the PINSRD
7328 // TODO: Optimize for AVX cases too (VINSERTPS)
7329 MVT VT = SVOp->getSimpleValueType(0);
7330 MVT EVT = VT.getVectorElementType();
7331 SDValue V1 = SVOp->getOperand(0);
7332 SDValue V2 = SVOp->getOperand(1);
7333 auto Mask = SVOp->getMask();
7334 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7335 "unsupported vector type for insertps/pinsrd");
7337 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7338 [](const int &i) { return i < 4; });
7346 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7347 [](const int &i) { return i < 4; }) -
7352 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7353 [](const int &i) { return i >= 4; }) -
7357 if (MayFoldLoad(From)) {
7358 // Trivial case, when From comes from a load and is only used by the
7359 // shuffle. Make it use insertps from the vector that we need from that
7361 SDValue Addr = From.getOperand(1);
7363 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7364 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7365 Addr.getSimpleValueType()));
7367 LoadSDNode *Load = cast<LoadSDNode>(From);
7369 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7370 DAG.getMachineFunction().getMachineMemOperand(
7371 Load->getMemOperand(), 0, EVT.getStoreSize()));
7373 if (EVT == MVT::f32) {
7374 // Create this as a scalar to vector to match the instruction pattern.
7375 SDValue LoadScalarToVector =
7376 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7377 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7378 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7380 } else { // EVT == MVT::i32
7381 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7382 // instruction, to match the PINSRD instruction, which loads an i32 to a
7383 // certain vector element.
7384 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7385 DAG.getConstant(DestIndex, MVT::i32));
7389 // Vector-element-to-vector
7390 unsigned SrcIndex = Mask[DestIndex] % 4;
7391 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7392 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7395 // Reduce a vector shuffle to zext.
7396 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7397 SelectionDAG &DAG) {
7398 // PMOVZX is only available from SSE41.
7399 if (!Subtarget->hasSSE41())
7402 MVT VT = Op.getSimpleValueType();
7404 // Only AVX2 support 256-bit vector integer extending.
7405 if (!Subtarget->hasInt256() && VT.is256BitVector())
7408 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7410 SDValue V1 = Op.getOperand(0);
7411 SDValue V2 = Op.getOperand(1);
7412 unsigned NumElems = VT.getVectorNumElements();
7414 // Extending is an unary operation and the element type of the source vector
7415 // won't be equal to or larger than i64.
7416 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7417 VT.getVectorElementType() == MVT::i64)
7420 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7421 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7422 while ((1U << Shift) < NumElems) {
7423 if (SVOp->getMaskElt(1U << Shift) == 1)
7426 // The maximal ratio is 8, i.e. from i8 to i64.
7431 // Check the shuffle mask.
7432 unsigned Mask = (1U << Shift) - 1;
7433 for (unsigned i = 0; i != NumElems; ++i) {
7434 int EltIdx = SVOp->getMaskElt(i);
7435 if ((i & Mask) != 0 && EltIdx != -1)
7437 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7441 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7442 MVT NeVT = MVT::getIntegerVT(NBits);
7443 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7445 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7448 // Simplify the operand as it's prepared to be fed into shuffle.
7449 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7450 if (V1.getOpcode() == ISD::BITCAST &&
7451 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7452 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7453 V1.getOperand(0).getOperand(0)
7454 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7455 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7456 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7457 ConstantSDNode *CIdx =
7458 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7459 // If it's foldable, i.e. normal load with single use, we will let code
7460 // selection to fold it. Otherwise, we will short the conversion sequence.
7461 if (CIdx && CIdx->getZExtValue() == 0 &&
7462 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7463 MVT FullVT = V.getSimpleValueType();
7464 MVT V1VT = V1.getSimpleValueType();
7465 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7466 // The "ext_vec_elt" node is wider than the result node.
7467 // In this case we should extract subvector from V.
7468 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7469 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7470 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7471 FullVT.getVectorNumElements()/Ratio);
7472 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7473 DAG.getIntPtrConstant(0));
7475 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7479 return DAG.getNode(ISD::BITCAST, DL, VT,
7480 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7484 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7485 SelectionDAG &DAG) {
7486 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7487 MVT VT = Op.getSimpleValueType();
7489 SDValue V1 = Op.getOperand(0);
7490 SDValue V2 = Op.getOperand(1);
7492 if (isZeroShuffle(SVOp))
7493 return getZeroVector(VT, Subtarget, DAG, dl);
7495 // Handle splat operations
7496 if (SVOp->isSplat()) {
7497 // Use vbroadcast whenever the splat comes from a foldable load
7498 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7499 if (Broadcast.getNode())
7503 // Check integer expanding shuffles.
7504 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7505 if (NewOp.getNode())
7508 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7510 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7511 VT == MVT::v16i16 || VT == MVT::v32i8) {
7512 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7513 if (NewOp.getNode())
7514 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7515 } else if ((VT == MVT::v4i32 ||
7516 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7517 // FIXME: Figure out a cleaner way to do this.
7518 // Try to make use of movq to zero out the top part.
7519 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7520 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7521 if (NewOp.getNode()) {
7522 MVT NewVT = NewOp.getSimpleValueType();
7523 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7524 NewVT, true, false))
7525 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7526 DAG, Subtarget, dl);
7528 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7529 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7530 if (NewOp.getNode()) {
7531 MVT NewVT = NewOp.getSimpleValueType();
7532 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7533 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7534 DAG, Subtarget, dl);
7542 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7543 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7544 SDValue V1 = Op.getOperand(0);
7545 SDValue V2 = Op.getOperand(1);
7546 MVT VT = Op.getSimpleValueType();
7548 unsigned NumElems = VT.getVectorNumElements();
7549 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7550 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7551 bool V1IsSplat = false;
7552 bool V2IsSplat = false;
7553 bool HasSSE2 = Subtarget->hasSSE2();
7554 bool HasFp256 = Subtarget->hasFp256();
7555 bool HasInt256 = Subtarget->hasInt256();
7556 MachineFunction &MF = DAG.getMachineFunction();
7557 bool OptForSize = MF.getFunction()->getAttributes().
7558 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7560 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7562 if (V1IsUndef && V2IsUndef)
7563 return DAG.getUNDEF(VT);
7565 // When we create a shuffle node we put the UNDEF node to second operand,
7566 // but in some cases the first operand may be transformed to UNDEF.
7567 // In this case we should just commute the node.
7569 return CommuteVectorShuffle(SVOp, DAG);
7571 // Vector shuffle lowering takes 3 steps:
7573 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7574 // narrowing and commutation of operands should be handled.
7575 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7577 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7578 // so the shuffle can be broken into other shuffles and the legalizer can
7579 // try the lowering again.
7581 // The general idea is that no vector_shuffle operation should be left to
7582 // be matched during isel, all of them must be converted to a target specific
7585 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7586 // narrowing and commutation of operands should be handled. The actual code
7587 // doesn't include all of those, work in progress...
7588 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7589 if (NewOp.getNode())
7592 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7594 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7595 // unpckh_undef). Only use pshufd if speed is more important than size.
7596 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7597 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7598 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7599 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7601 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7602 V2IsUndef && MayFoldVectorLoad(V1))
7603 return getMOVDDup(Op, dl, V1, DAG);
7605 if (isMOVHLPS_v_undef_Mask(M, VT))
7606 return getMOVHighToLow(Op, dl, DAG);
7608 // Use to match splats
7609 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7610 (VT == MVT::v2f64 || VT == MVT::v2i64))
7611 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7613 if (isPSHUFDMask(M, VT)) {
7614 // The actual implementation will match the mask in the if above and then
7615 // during isel it can match several different instructions, not only pshufd
7616 // as its name says, sad but true, emulate the behavior for now...
7617 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7618 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7620 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7622 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7623 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7625 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7626 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7629 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7633 if (isPALIGNRMask(M, VT, Subtarget))
7634 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7635 getShufflePALIGNRImmediate(SVOp),
7638 // Check if this can be converted into a logical shift.
7639 bool isLeft = false;
7642 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7643 if (isShift && ShVal.hasOneUse()) {
7644 // If the shifted value has multiple uses, it may be cheaper to use
7645 // v_set0 + movlhps or movhlps, etc.
7646 MVT EltVT = VT.getVectorElementType();
7647 ShAmt *= EltVT.getSizeInBits();
7648 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7651 if (isMOVLMask(M, VT)) {
7652 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7653 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7654 if (!isMOVLPMask(M, VT)) {
7655 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7656 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7658 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7659 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7663 // FIXME: fold these into legal mask.
7664 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7665 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7667 if (isMOVHLPSMask(M, VT))
7668 return getMOVHighToLow(Op, dl, DAG);
7670 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7671 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7673 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7674 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7676 if (isMOVLPMask(M, VT))
7677 return getMOVLP(Op, dl, DAG, HasSSE2);
7679 if (ShouldXformToMOVHLPS(M, VT) ||
7680 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7681 return CommuteVectorShuffle(SVOp, DAG);
7684 // No better options. Use a vshldq / vsrldq.
7685 MVT EltVT = VT.getVectorElementType();
7686 ShAmt *= EltVT.getSizeInBits();
7687 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7690 bool Commuted = false;
7691 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7692 // 1,1,1,1 -> v8i16 though.
7693 V1IsSplat = isSplatVector(V1.getNode());
7694 V2IsSplat = isSplatVector(V2.getNode());
7696 // Canonicalize the splat or undef, if present, to be on the RHS.
7697 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7698 CommuteVectorShuffleMask(M, NumElems);
7700 std::swap(V1IsSplat, V2IsSplat);
7704 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7705 // Shuffling low element of v1 into undef, just return v1.
7708 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7709 // the instruction selector will not match, so get a canonical MOVL with
7710 // swapped operands to undo the commute.
7711 return getMOVL(DAG, dl, VT, V2, V1);
7714 if (isUNPCKLMask(M, VT, HasInt256))
7715 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7717 if (isUNPCKHMask(M, VT, HasInt256))
7718 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7721 // Normalize mask so all entries that point to V2 points to its first
7722 // element then try to match unpck{h|l} again. If match, return a
7723 // new vector_shuffle with the corrected mask.p
7724 SmallVector<int, 8> NewMask(M.begin(), M.end());
7725 NormalizeMask(NewMask, NumElems);
7726 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7727 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7728 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7729 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7733 // Commute is back and try unpck* again.
7734 // FIXME: this seems wrong.
7735 CommuteVectorShuffleMask(M, NumElems);
7737 std::swap(V1IsSplat, V2IsSplat);
7739 if (isUNPCKLMask(M, VT, HasInt256))
7740 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7742 if (isUNPCKHMask(M, VT, HasInt256))
7743 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7746 // Normalize the node to match x86 shuffle ops if needed
7747 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7748 return CommuteVectorShuffle(SVOp, DAG);
7750 // The checks below are all present in isShuffleMaskLegal, but they are
7751 // inlined here right now to enable us to directly emit target specific
7752 // nodes, and remove one by one until they don't return Op anymore.
7754 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7755 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7756 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7757 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7760 if (isPSHUFHWMask(M, VT, HasInt256))
7761 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7762 getShufflePSHUFHWImmediate(SVOp),
7765 if (isPSHUFLWMask(M, VT, HasInt256))
7766 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7767 getShufflePSHUFLWImmediate(SVOp),
7770 if (isSHUFPMask(M, VT))
7771 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7772 getShuffleSHUFImmediate(SVOp), DAG);
7774 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7775 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7776 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7777 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7779 //===--------------------------------------------------------------------===//
7780 // Generate target specific nodes for 128 or 256-bit shuffles only
7781 // supported in the AVX instruction set.
7784 // Handle VMOVDDUPY permutations
7785 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7786 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7788 // Handle VPERMILPS/D* permutations
7789 if (isVPERMILPMask(M, VT)) {
7790 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7791 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7792 getShuffleSHUFImmediate(SVOp), DAG);
7793 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7794 getShuffleSHUFImmediate(SVOp), DAG);
7798 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7799 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7800 Idx*(NumElems/2), DAG, dl);
7802 // Handle VPERM2F128/VPERM2I128 permutations
7803 if (isVPERM2X128Mask(M, VT, HasFp256))
7804 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7805 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7807 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7808 if (BlendOp.getNode())
7811 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7812 return getINSERTPS(SVOp, dl, DAG);
7815 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7816 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7818 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7819 VT.is512BitVector()) {
7820 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7821 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7822 SmallVector<SDValue, 16> permclMask;
7823 for (unsigned i = 0; i != NumElems; ++i) {
7824 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7827 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7829 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7830 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7831 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7832 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7833 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7836 //===--------------------------------------------------------------------===//
7837 // Since no target specific shuffle was selected for this generic one,
7838 // lower it into other known shuffles. FIXME: this isn't true yet, but
7839 // this is the plan.
7842 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7843 if (VT == MVT::v8i16) {
7844 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7845 if (NewOp.getNode())
7849 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7850 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7851 if (NewOp.getNode())
7855 if (VT == MVT::v16i8) {
7856 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7857 if (NewOp.getNode())
7861 if (VT == MVT::v32i8) {
7862 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7863 if (NewOp.getNode())
7867 // Handle all 128-bit wide vectors with 4 elements, and match them with
7868 // several different shuffle types.
7869 if (NumElems == 4 && VT.is128BitVector())
7870 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7872 // Handle general 256-bit shuffles
7873 if (VT.is256BitVector())
7874 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7879 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7880 MVT VT = Op.getSimpleValueType();
7883 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7886 if (VT.getSizeInBits() == 8) {
7887 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7888 Op.getOperand(0), Op.getOperand(1));
7889 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7890 DAG.getValueType(VT));
7891 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7894 if (VT.getSizeInBits() == 16) {
7895 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7896 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7898 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7899 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7900 DAG.getNode(ISD::BITCAST, dl,
7904 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7905 Op.getOperand(0), Op.getOperand(1));
7906 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7907 DAG.getValueType(VT));
7908 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7911 if (VT == MVT::f32) {
7912 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7913 // the result back to FR32 register. It's only worth matching if the
7914 // result has a single use which is a store or a bitcast to i32. And in
7915 // the case of a store, it's not worth it if the index is a constant 0,
7916 // because a MOVSSmr can be used instead, which is smaller and faster.
7917 if (!Op.hasOneUse())
7919 SDNode *User = *Op.getNode()->use_begin();
7920 if ((User->getOpcode() != ISD::STORE ||
7921 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7922 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7923 (User->getOpcode() != ISD::BITCAST ||
7924 User->getValueType(0) != MVT::i32))
7926 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7927 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7930 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7933 if (VT == MVT::i32 || VT == MVT::i64) {
7934 // ExtractPS/pextrq works with constant index.
7935 if (isa<ConstantSDNode>(Op.getOperand(1)))
7941 /// Extract one bit from mask vector, like v16i1 or v8i1.
7942 /// AVX-512 feature.
7944 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7945 SDValue Vec = Op.getOperand(0);
7947 MVT VecVT = Vec.getSimpleValueType();
7948 SDValue Idx = Op.getOperand(1);
7949 MVT EltVT = Op.getSimpleValueType();
7951 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7953 // variable index can't be handled in mask registers,
7954 // extend vector to VR512
7955 if (!isa<ConstantSDNode>(Idx)) {
7956 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7957 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7958 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7959 ExtVT.getVectorElementType(), Ext, Idx);
7960 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7963 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7964 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7965 unsigned MaxSift = rc->getSize()*8 - 1;
7966 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7967 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7968 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7969 DAG.getConstant(MaxSift, MVT::i8));
7970 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7971 DAG.getIntPtrConstant(0));
7975 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7976 SelectionDAG &DAG) const {
7978 SDValue Vec = Op.getOperand(0);
7979 MVT VecVT = Vec.getSimpleValueType();
7980 SDValue Idx = Op.getOperand(1);
7982 if (Op.getSimpleValueType() == MVT::i1)
7983 return ExtractBitFromMaskVector(Op, DAG);
7985 if (!isa<ConstantSDNode>(Idx)) {
7986 if (VecVT.is512BitVector() ||
7987 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7988 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7991 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7992 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7993 MaskEltVT.getSizeInBits());
7995 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7996 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7997 getZeroVector(MaskVT, Subtarget, DAG, dl),
7998 Idx, DAG.getConstant(0, getPointerTy()));
7999 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8000 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8001 Perm, DAG.getConstant(0, getPointerTy()));
8006 // If this is a 256-bit vector result, first extract the 128-bit vector and
8007 // then extract the element from the 128-bit vector.
8008 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8010 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8011 // Get the 128-bit vector.
8012 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8013 MVT EltVT = VecVT.getVectorElementType();
8015 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8017 //if (IdxVal >= NumElems/2)
8018 // IdxVal -= NumElems/2;
8019 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8020 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8021 DAG.getConstant(IdxVal, MVT::i32));
8024 assert(VecVT.is128BitVector() && "Unexpected vector length");
8026 if (Subtarget->hasSSE41()) {
8027 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8032 MVT VT = Op.getSimpleValueType();
8033 // TODO: handle v16i8.
8034 if (VT.getSizeInBits() == 16) {
8035 SDValue Vec = Op.getOperand(0);
8036 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8038 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8039 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8040 DAG.getNode(ISD::BITCAST, dl,
8043 // Transform it so it match pextrw which produces a 32-bit result.
8044 MVT EltVT = MVT::i32;
8045 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8046 Op.getOperand(0), Op.getOperand(1));
8047 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8048 DAG.getValueType(VT));
8049 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8052 if (VT.getSizeInBits() == 32) {
8053 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8057 // SHUFPS the element to the lowest double word, then movss.
8058 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8059 MVT VVT = Op.getOperand(0).getSimpleValueType();
8060 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8061 DAG.getUNDEF(VVT), Mask);
8062 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8063 DAG.getIntPtrConstant(0));
8066 if (VT.getSizeInBits() == 64) {
8067 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8068 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8069 // to match extract_elt for f64.
8070 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8074 // UNPCKHPD the element to the lowest double word, then movsd.
8075 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8076 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8077 int Mask[2] = { 1, -1 };
8078 MVT VVT = Op.getOperand(0).getSimpleValueType();
8079 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8080 DAG.getUNDEF(VVT), Mask);
8081 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8082 DAG.getIntPtrConstant(0));
8088 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8089 MVT VT = Op.getSimpleValueType();
8090 MVT EltVT = VT.getVectorElementType();
8093 SDValue N0 = Op.getOperand(0);
8094 SDValue N1 = Op.getOperand(1);
8095 SDValue N2 = Op.getOperand(2);
8097 if (!VT.is128BitVector())
8100 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8101 isa<ConstantSDNode>(N2)) {
8103 if (VT == MVT::v8i16)
8104 Opc = X86ISD::PINSRW;
8105 else if (VT == MVT::v16i8)
8106 Opc = X86ISD::PINSRB;
8108 Opc = X86ISD::PINSRB;
8110 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8112 if (N1.getValueType() != MVT::i32)
8113 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8114 if (N2.getValueType() != MVT::i32)
8115 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8116 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8119 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8120 // Bits [7:6] of the constant are the source select. This will always be
8121 // zero here. The DAG Combiner may combine an extract_elt index into these
8122 // bits. For example (insert (extract, 3), 2) could be matched by putting
8123 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8124 // Bits [5:4] of the constant are the destination select. This is the
8125 // value of the incoming immediate.
8126 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8127 // combine either bitwise AND or insert of float 0.0 to set these bits.
8128 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8129 // Create this as a scalar to vector..
8130 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8131 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8134 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8135 // PINSR* works with constant index.
8141 /// Insert one bit to mask vector, like v16i1 or v8i1.
8142 /// AVX-512 feature.
8144 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8146 SDValue Vec = Op.getOperand(0);
8147 SDValue Elt = Op.getOperand(1);
8148 SDValue Idx = Op.getOperand(2);
8149 MVT VecVT = Vec.getSimpleValueType();
8151 if (!isa<ConstantSDNode>(Idx)) {
8152 // Non constant index. Extend source and destination,
8153 // insert element and then truncate the result.
8154 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8155 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8156 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8157 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8158 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8159 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8162 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8163 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8164 if (Vec.getOpcode() == ISD::UNDEF)
8165 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8166 DAG.getConstant(IdxVal, MVT::i8));
8167 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8168 unsigned MaxSift = rc->getSize()*8 - 1;
8169 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8170 DAG.getConstant(MaxSift, MVT::i8));
8171 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8172 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8173 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8176 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8177 MVT VT = Op.getSimpleValueType();
8178 MVT EltVT = VT.getVectorElementType();
8180 if (EltVT == MVT::i1)
8181 return InsertBitToMaskVector(Op, DAG);
8184 SDValue N0 = Op.getOperand(0);
8185 SDValue N1 = Op.getOperand(1);
8186 SDValue N2 = Op.getOperand(2);
8188 // If this is a 256-bit vector result, first extract the 128-bit vector,
8189 // insert the element into the extracted half and then place it back.
8190 if (VT.is256BitVector() || VT.is512BitVector()) {
8191 if (!isa<ConstantSDNode>(N2))
8194 // Get the desired 128-bit vector half.
8195 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8196 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8198 // Insert the element into the desired half.
8199 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8200 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8202 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8203 DAG.getConstant(IdxIn128, MVT::i32));
8205 // Insert the changed part back to the 256-bit vector
8206 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8209 if (Subtarget->hasSSE41())
8210 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8212 if (EltVT == MVT::i8)
8215 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8216 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8217 // as its second argument.
8218 if (N1.getValueType() != MVT::i32)
8219 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8220 if (N2.getValueType() != MVT::i32)
8221 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8222 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8227 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8229 MVT OpVT = Op.getSimpleValueType();
8231 // If this is a 256-bit vector result, first insert into a 128-bit
8232 // vector and then insert into the 256-bit vector.
8233 if (!OpVT.is128BitVector()) {
8234 // Insert into a 128-bit vector.
8235 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8236 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8237 OpVT.getVectorNumElements() / SizeFactor);
8239 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8241 // Insert the 128-bit vector.
8242 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8245 if (OpVT == MVT::v1i64 &&
8246 Op.getOperand(0).getValueType() == MVT::i64)
8247 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8249 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8250 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8251 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8252 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8255 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8256 // a simple subregister reference or explicit instructions to grab
8257 // upper bits of a vector.
8258 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8259 SelectionDAG &DAG) {
8261 SDValue In = Op.getOperand(0);
8262 SDValue Idx = Op.getOperand(1);
8263 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8264 MVT ResVT = Op.getSimpleValueType();
8265 MVT InVT = In.getSimpleValueType();
8267 if (Subtarget->hasFp256()) {
8268 if (ResVT.is128BitVector() &&
8269 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8270 isa<ConstantSDNode>(Idx)) {
8271 return Extract128BitVector(In, IdxVal, DAG, dl);
8273 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8274 isa<ConstantSDNode>(Idx)) {
8275 return Extract256BitVector(In, IdxVal, DAG, dl);
8281 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8282 // simple superregister reference or explicit instructions to insert
8283 // the upper bits of a vector.
8284 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8285 SelectionDAG &DAG) {
8286 if (Subtarget->hasFp256()) {
8287 SDLoc dl(Op.getNode());
8288 SDValue Vec = Op.getNode()->getOperand(0);
8289 SDValue SubVec = Op.getNode()->getOperand(1);
8290 SDValue Idx = Op.getNode()->getOperand(2);
8292 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8293 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8294 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8295 isa<ConstantSDNode>(Idx)) {
8296 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8297 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8300 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8301 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8302 isa<ConstantSDNode>(Idx)) {
8303 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8304 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8310 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8311 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8312 // one of the above mentioned nodes. It has to be wrapped because otherwise
8313 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8314 // be used to form addressing mode. These wrapped nodes will be selected
8317 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8318 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8320 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8322 unsigned char OpFlag = 0;
8323 unsigned WrapperKind = X86ISD::Wrapper;
8324 CodeModel::Model M = getTargetMachine().getCodeModel();
8326 if (Subtarget->isPICStyleRIPRel() &&
8327 (M == CodeModel::Small || M == CodeModel::Kernel))
8328 WrapperKind = X86ISD::WrapperRIP;
8329 else if (Subtarget->isPICStyleGOT())
8330 OpFlag = X86II::MO_GOTOFF;
8331 else if (Subtarget->isPICStyleStubPIC())
8332 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8334 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8336 CP->getOffset(), OpFlag);
8338 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8339 // With PIC, the address is actually $g + Offset.
8341 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8342 DAG.getNode(X86ISD::GlobalBaseReg,
8343 SDLoc(), getPointerTy()),
8350 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8351 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8353 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8355 unsigned char OpFlag = 0;
8356 unsigned WrapperKind = X86ISD::Wrapper;
8357 CodeModel::Model M = getTargetMachine().getCodeModel();
8359 if (Subtarget->isPICStyleRIPRel() &&
8360 (M == CodeModel::Small || M == CodeModel::Kernel))
8361 WrapperKind = X86ISD::WrapperRIP;
8362 else if (Subtarget->isPICStyleGOT())
8363 OpFlag = X86II::MO_GOTOFF;
8364 else if (Subtarget->isPICStyleStubPIC())
8365 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8367 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8370 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8372 // With PIC, the address is actually $g + Offset.
8374 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8375 DAG.getNode(X86ISD::GlobalBaseReg,
8376 SDLoc(), getPointerTy()),
8383 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8384 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8386 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8388 unsigned char OpFlag = 0;
8389 unsigned WrapperKind = X86ISD::Wrapper;
8390 CodeModel::Model M = getTargetMachine().getCodeModel();
8392 if (Subtarget->isPICStyleRIPRel() &&
8393 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8394 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8395 OpFlag = X86II::MO_GOTPCREL;
8396 WrapperKind = X86ISD::WrapperRIP;
8397 } else if (Subtarget->isPICStyleGOT()) {
8398 OpFlag = X86II::MO_GOT;
8399 } else if (Subtarget->isPICStyleStubPIC()) {
8400 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8401 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8402 OpFlag = X86II::MO_DARWIN_NONLAZY;
8405 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8408 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8410 // With PIC, the address is actually $g + Offset.
8411 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8412 !Subtarget->is64Bit()) {
8413 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8414 DAG.getNode(X86ISD::GlobalBaseReg,
8415 SDLoc(), getPointerTy()),
8419 // For symbols that require a load from a stub to get the address, emit the
8421 if (isGlobalStubReference(OpFlag))
8422 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8423 MachinePointerInfo::getGOT(), false, false, false, 0);
8429 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8430 // Create the TargetBlockAddressAddress node.
8431 unsigned char OpFlags =
8432 Subtarget->ClassifyBlockAddressReference();
8433 CodeModel::Model M = getTargetMachine().getCodeModel();
8434 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8435 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8437 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8440 if (Subtarget->isPICStyleRIPRel() &&
8441 (M == CodeModel::Small || M == CodeModel::Kernel))
8442 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8444 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8446 // With PIC, the address is actually $g + Offset.
8447 if (isGlobalRelativeToPICBase(OpFlags)) {
8448 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8449 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8457 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8458 int64_t Offset, SelectionDAG &DAG) const {
8459 // Create the TargetGlobalAddress node, folding in the constant
8460 // offset if it is legal.
8461 unsigned char OpFlags =
8462 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8463 CodeModel::Model M = getTargetMachine().getCodeModel();
8465 if (OpFlags == X86II::MO_NO_FLAG &&
8466 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8467 // A direct static reference to a global.
8468 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8471 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8474 if (Subtarget->isPICStyleRIPRel() &&
8475 (M == CodeModel::Small || M == CodeModel::Kernel))
8476 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8478 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8480 // With PIC, the address is actually $g + Offset.
8481 if (isGlobalRelativeToPICBase(OpFlags)) {
8482 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8483 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8487 // For globals that require a load from a stub to get the address, emit the
8489 if (isGlobalStubReference(OpFlags))
8490 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8491 MachinePointerInfo::getGOT(), false, false, false, 0);
8493 // If there was a non-zero offset that we didn't fold, create an explicit
8496 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8497 DAG.getConstant(Offset, getPointerTy()));
8503 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8504 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8505 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8506 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8510 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8511 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8512 unsigned char OperandFlags, bool LocalDynamic = false) {
8513 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8514 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8516 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8517 GA->getValueType(0),
8521 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8525 SDValue Ops[] = { Chain, TGA, *InFlag };
8526 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8528 SDValue Ops[] = { Chain, TGA };
8529 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8532 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8533 MFI->setAdjustsStack(true);
8535 SDValue Flag = Chain.getValue(1);
8536 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8539 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8541 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8544 SDLoc dl(GA); // ? function entry point might be better
8545 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8546 DAG.getNode(X86ISD::GlobalBaseReg,
8547 SDLoc(), PtrVT), InFlag);
8548 InFlag = Chain.getValue(1);
8550 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8553 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8555 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8557 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8558 X86::RAX, X86II::MO_TLSGD);
8561 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8567 // Get the start address of the TLS block for this module.
8568 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8569 .getInfo<X86MachineFunctionInfo>();
8570 MFI->incNumLocalDynamicTLSAccesses();
8574 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8575 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8578 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8579 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8580 InFlag = Chain.getValue(1);
8581 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8582 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8585 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8589 unsigned char OperandFlags = X86II::MO_DTPOFF;
8590 unsigned WrapperKind = X86ISD::Wrapper;
8591 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8592 GA->getValueType(0),
8593 GA->getOffset(), OperandFlags);
8594 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8596 // Add x@dtpoff with the base.
8597 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8600 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8601 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8602 const EVT PtrVT, TLSModel::Model model,
8603 bool is64Bit, bool isPIC) {
8606 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8607 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8608 is64Bit ? 257 : 256));
8610 SDValue ThreadPointer =
8611 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8612 MachinePointerInfo(Ptr), false, false, false, 0);
8614 unsigned char OperandFlags = 0;
8615 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8617 unsigned WrapperKind = X86ISD::Wrapper;
8618 if (model == TLSModel::LocalExec) {
8619 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8620 } else if (model == TLSModel::InitialExec) {
8622 OperandFlags = X86II::MO_GOTTPOFF;
8623 WrapperKind = X86ISD::WrapperRIP;
8625 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8628 llvm_unreachable("Unexpected model");
8631 // emit "addl x@ntpoff,%eax" (local exec)
8632 // or "addl x@indntpoff,%eax" (initial exec)
8633 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8635 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8636 GA->getOffset(), OperandFlags);
8637 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8639 if (model == TLSModel::InitialExec) {
8640 if (isPIC && !is64Bit) {
8641 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8642 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8646 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8647 MachinePointerInfo::getGOT(), false, false, false, 0);
8650 // The address of the thread local variable is the add of the thread
8651 // pointer with the offset of the variable.
8652 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8656 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8658 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8659 const GlobalValue *GV = GA->getGlobal();
8661 if (Subtarget->isTargetELF()) {
8662 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8665 case TLSModel::GeneralDynamic:
8666 if (Subtarget->is64Bit())
8667 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8668 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8669 case TLSModel::LocalDynamic:
8670 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8671 Subtarget->is64Bit());
8672 case TLSModel::InitialExec:
8673 case TLSModel::LocalExec:
8674 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8675 Subtarget->is64Bit(),
8676 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8678 llvm_unreachable("Unknown TLS model.");
8681 if (Subtarget->isTargetDarwin()) {
8682 // Darwin only has one model of TLS. Lower to that.
8683 unsigned char OpFlag = 0;
8684 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8685 X86ISD::WrapperRIP : X86ISD::Wrapper;
8687 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8689 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8690 !Subtarget->is64Bit();
8692 OpFlag = X86II::MO_TLVP_PIC_BASE;
8694 OpFlag = X86II::MO_TLVP;
8696 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8697 GA->getValueType(0),
8698 GA->getOffset(), OpFlag);
8699 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8701 // With PIC32, the address is actually $g + Offset.
8703 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8704 DAG.getNode(X86ISD::GlobalBaseReg,
8705 SDLoc(), getPointerTy()),
8708 // Lowering the machine isd will make sure everything is in the right
8710 SDValue Chain = DAG.getEntryNode();
8711 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8712 SDValue Args[] = { Chain, Offset };
8713 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8715 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8716 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8717 MFI->setAdjustsStack(true);
8719 // And our return value (tls address) is in the standard call return value
8721 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8722 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8726 if (Subtarget->isTargetKnownWindowsMSVC() ||
8727 Subtarget->isTargetWindowsGNU()) {
8728 // Just use the implicit TLS architecture
8729 // Need to generate someting similar to:
8730 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8732 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8733 // mov rcx, qword [rdx+rcx*8]
8734 // mov eax, .tls$:tlsvar
8735 // [rax+rcx] contains the address
8736 // Windows 64bit: gs:0x58
8737 // Windows 32bit: fs:__tls_array
8739 // If GV is an alias then use the aliasee for determining
8740 // thread-localness.
8741 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8742 GV = GA->getAliasedGlobal();
8744 SDValue Chain = DAG.getEntryNode();
8746 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8747 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8748 // use its literal value of 0x2C.
8749 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8750 ? Type::getInt8PtrTy(*DAG.getContext(),
8752 : Type::getInt32PtrTy(*DAG.getContext(),
8756 Subtarget->is64Bit()
8757 ? DAG.getIntPtrConstant(0x58)
8758 : (Subtarget->isTargetWindowsGNU()
8759 ? DAG.getIntPtrConstant(0x2C)
8760 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8762 SDValue ThreadPointer =
8763 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8764 MachinePointerInfo(Ptr), false, false, false, 0);
8766 // Load the _tls_index variable
8767 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8768 if (Subtarget->is64Bit())
8769 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8770 IDX, MachinePointerInfo(), MVT::i32,
8773 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8774 false, false, false, 0);
8776 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8778 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8780 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8781 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8782 false, false, false, 0);
8784 // Get the offset of start of .tls section
8785 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8786 GA->getValueType(0),
8787 GA->getOffset(), X86II::MO_SECREL);
8788 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8790 // The address of the thread local variable is the add of the thread
8791 // pointer with the offset of the variable.
8792 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8795 llvm_unreachable("TLS not implemented for this target.");
8798 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8799 /// and take a 2 x i32 value to shift plus a shift amount.
8800 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8801 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8802 MVT VT = Op.getSimpleValueType();
8803 unsigned VTBits = VT.getSizeInBits();
8805 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8806 SDValue ShOpLo = Op.getOperand(0);
8807 SDValue ShOpHi = Op.getOperand(1);
8808 SDValue ShAmt = Op.getOperand(2);
8809 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8810 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8812 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8813 DAG.getConstant(VTBits - 1, MVT::i8));
8814 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8815 DAG.getConstant(VTBits - 1, MVT::i8))
8816 : DAG.getConstant(0, VT);
8819 if (Op.getOpcode() == ISD::SHL_PARTS) {
8820 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8821 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8823 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8824 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8827 // If the shift amount is larger or equal than the width of a part we can't
8828 // rely on the results of shld/shrd. Insert a test and select the appropriate
8829 // values for large shift amounts.
8830 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8831 DAG.getConstant(VTBits, MVT::i8));
8832 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8833 AndNode, DAG.getConstant(0, MVT::i8));
8836 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8837 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8838 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8840 if (Op.getOpcode() == ISD::SHL_PARTS) {
8841 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8842 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8844 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8845 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8848 SDValue Ops[2] = { Lo, Hi };
8849 return DAG.getMergeValues(Ops, dl);
8852 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8853 SelectionDAG &DAG) const {
8854 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8856 if (SrcVT.isVector())
8859 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8860 "Unknown SINT_TO_FP to lower!");
8862 // These are really Legal; return the operand so the caller accepts it as
8864 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8866 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8867 Subtarget->is64Bit()) {
8872 unsigned Size = SrcVT.getSizeInBits()/8;
8873 MachineFunction &MF = DAG.getMachineFunction();
8874 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8875 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8876 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8878 MachinePointerInfo::getFixedStack(SSFI),
8880 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8883 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8885 SelectionDAG &DAG) const {
8889 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8891 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8893 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8895 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8897 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8898 MachineMemOperand *MMO;
8900 int SSFI = FI->getIndex();
8902 DAG.getMachineFunction()
8903 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8904 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8906 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8907 StackSlot = StackSlot.getOperand(1);
8909 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8910 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8912 Tys, Ops, SrcVT, MMO);
8915 Chain = Result.getValue(1);
8916 SDValue InFlag = Result.getValue(2);
8918 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8919 // shouldn't be necessary except that RFP cannot be live across
8920 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8921 MachineFunction &MF = DAG.getMachineFunction();
8922 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8923 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8924 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8925 Tys = DAG.getVTList(MVT::Other);
8927 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8929 MachineMemOperand *MMO =
8930 DAG.getMachineFunction()
8931 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8932 MachineMemOperand::MOStore, SSFISize, SSFISize);
8934 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8935 Ops, Op.getValueType(), MMO);
8936 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8937 MachinePointerInfo::getFixedStack(SSFI),
8938 false, false, false, 0);
8944 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8945 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8946 SelectionDAG &DAG) const {
8947 // This algorithm is not obvious. Here it is what we're trying to output:
8950 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8951 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8955 pshufd $0x4e, %xmm0, %xmm1
8961 LLVMContext *Context = DAG.getContext();
8963 // Build some magic constants.
8964 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8965 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8966 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8968 SmallVector<Constant*,2> CV1;
8970 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8971 APInt(64, 0x4330000000000000ULL))));
8973 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8974 APInt(64, 0x4530000000000000ULL))));
8975 Constant *C1 = ConstantVector::get(CV1);
8976 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8978 // Load the 64-bit value into an XMM register.
8979 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8981 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8982 MachinePointerInfo::getConstantPool(),
8983 false, false, false, 16);
8984 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8985 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8988 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8989 MachinePointerInfo::getConstantPool(),
8990 false, false, false, 16);
8991 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8992 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8995 if (Subtarget->hasSSE3()) {
8996 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8997 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8999 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9000 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9002 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9003 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9007 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9008 DAG.getIntPtrConstant(0));
9011 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9012 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9013 SelectionDAG &DAG) const {
9015 // FP constant to bias correct the final result.
9016 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9019 // Load the 32-bit value into an XMM register.
9020 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9023 // Zero out the upper parts of the register.
9024 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9026 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9027 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9028 DAG.getIntPtrConstant(0));
9030 // Or the load with the bias.
9031 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9032 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9033 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9035 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9036 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9037 MVT::v2f64, Bias)));
9038 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9039 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9040 DAG.getIntPtrConstant(0));
9042 // Subtract the bias.
9043 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9045 // Handle final rounding.
9046 EVT DestVT = Op.getValueType();
9048 if (DestVT.bitsLT(MVT::f64))
9049 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9050 DAG.getIntPtrConstant(0));
9051 if (DestVT.bitsGT(MVT::f64))
9052 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9054 // Handle final rounding.
9058 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9059 SelectionDAG &DAG) const {
9060 SDValue N0 = Op.getOperand(0);
9061 MVT SVT = N0.getSimpleValueType();
9064 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9065 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9066 "Custom UINT_TO_FP is not supported!");
9068 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9069 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9070 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9073 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9074 SelectionDAG &DAG) const {
9075 SDValue N0 = Op.getOperand(0);
9078 if (Op.getValueType().isVector())
9079 return lowerUINT_TO_FP_vec(Op, DAG);
9081 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9082 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9083 // the optimization here.
9084 if (DAG.SignBitIsZero(N0))
9085 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9087 MVT SrcVT = N0.getSimpleValueType();
9088 MVT DstVT = Op.getSimpleValueType();
9089 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9090 return LowerUINT_TO_FP_i64(Op, DAG);
9091 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9092 return LowerUINT_TO_FP_i32(Op, DAG);
9093 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9096 // Make a 64-bit buffer, and use it to build an FILD.
9097 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9098 if (SrcVT == MVT::i32) {
9099 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9100 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9101 getPointerTy(), StackSlot, WordOff);
9102 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9103 StackSlot, MachinePointerInfo(),
9105 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9106 OffsetSlot, MachinePointerInfo(),
9108 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9112 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9113 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9114 StackSlot, MachinePointerInfo(),
9116 // For i64 source, we need to add the appropriate power of 2 if the input
9117 // was negative. This is the same as the optimization in
9118 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9119 // we must be careful to do the computation in x87 extended precision, not
9120 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9121 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9122 MachineMemOperand *MMO =
9123 DAG.getMachineFunction()
9124 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9125 MachineMemOperand::MOLoad, 8, 8);
9127 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9128 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9129 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9132 APInt FF(32, 0x5F800000ULL);
9134 // Check whether the sign bit is set.
9135 SDValue SignSet = DAG.getSetCC(dl,
9136 getSetCCResultType(*DAG.getContext(), MVT::i64),
9137 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9140 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9141 SDValue FudgePtr = DAG.getConstantPool(
9142 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9145 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9146 SDValue Zero = DAG.getIntPtrConstant(0);
9147 SDValue Four = DAG.getIntPtrConstant(4);
9148 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9150 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9152 // Load the value out, extending it from f32 to f80.
9153 // FIXME: Avoid the extend by constructing the right constant pool?
9154 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9155 FudgePtr, MachinePointerInfo::getConstantPool(),
9156 MVT::f32, false, false, 4);
9157 // Extend everything to 80 bits to force it to be done on x87.
9158 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9159 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9162 std::pair<SDValue,SDValue>
9163 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9164 bool IsSigned, bool IsReplace) const {
9167 EVT DstTy = Op.getValueType();
9169 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9170 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9174 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9175 DstTy.getSimpleVT() >= MVT::i16 &&
9176 "Unknown FP_TO_INT to lower!");
9178 // These are really Legal.
9179 if (DstTy == MVT::i32 &&
9180 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9181 return std::make_pair(SDValue(), SDValue());
9182 if (Subtarget->is64Bit() &&
9183 DstTy == MVT::i64 &&
9184 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9185 return std::make_pair(SDValue(), SDValue());
9187 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9188 // stack slot, or into the FTOL runtime function.
9189 MachineFunction &MF = DAG.getMachineFunction();
9190 unsigned MemSize = DstTy.getSizeInBits()/8;
9191 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9192 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9195 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9196 Opc = X86ISD::WIN_FTOL;
9198 switch (DstTy.getSimpleVT().SimpleTy) {
9199 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9200 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9201 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9202 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9205 SDValue Chain = DAG.getEntryNode();
9206 SDValue Value = Op.getOperand(0);
9207 EVT TheVT = Op.getOperand(0).getValueType();
9208 // FIXME This causes a redundant load/store if the SSE-class value is already
9209 // in memory, such as if it is on the callstack.
9210 if (isScalarFPTypeInSSEReg(TheVT)) {
9211 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9212 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9213 MachinePointerInfo::getFixedStack(SSFI),
9215 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9217 Chain, StackSlot, DAG.getValueType(TheVT)
9220 MachineMemOperand *MMO =
9221 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9222 MachineMemOperand::MOLoad, MemSize, MemSize);
9223 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9224 Chain = Value.getValue(1);
9225 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9226 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9229 MachineMemOperand *MMO =
9230 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9231 MachineMemOperand::MOStore, MemSize, MemSize);
9233 if (Opc != X86ISD::WIN_FTOL) {
9234 // Build the FP_TO_INT*_IN_MEM
9235 SDValue Ops[] = { Chain, Value, StackSlot };
9236 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9238 return std::make_pair(FIST, StackSlot);
9240 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9241 DAG.getVTList(MVT::Other, MVT::Glue),
9243 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9244 MVT::i32, ftol.getValue(1));
9245 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9246 MVT::i32, eax.getValue(2));
9247 SDValue Ops[] = { eax, edx };
9248 SDValue pair = IsReplace
9249 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9250 : DAG.getMergeValues(Ops, DL);
9251 return std::make_pair(pair, SDValue());
9255 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9256 const X86Subtarget *Subtarget) {
9257 MVT VT = Op->getSimpleValueType(0);
9258 SDValue In = Op->getOperand(0);
9259 MVT InVT = In.getSimpleValueType();
9262 // Optimize vectors in AVX mode:
9265 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9266 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9267 // Concat upper and lower parts.
9270 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9271 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9272 // Concat upper and lower parts.
9275 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9276 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9277 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9280 if (Subtarget->hasInt256())
9281 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9283 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9284 SDValue Undef = DAG.getUNDEF(InVT);
9285 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9286 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9287 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9289 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9290 VT.getVectorNumElements()/2);
9292 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9293 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9295 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9298 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9299 SelectionDAG &DAG) {
9300 MVT VT = Op->getSimpleValueType(0);
9301 SDValue In = Op->getOperand(0);
9302 MVT InVT = In.getSimpleValueType();
9304 unsigned int NumElts = VT.getVectorNumElements();
9305 if (NumElts != 8 && NumElts != 16)
9308 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9309 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9311 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9313 // Now we have only mask extension
9314 assert(InVT.getVectorElementType() == MVT::i1);
9315 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9316 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9317 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9318 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9319 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9320 MachinePointerInfo::getConstantPool(),
9321 false, false, false, Alignment);
9323 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9324 if (VT.is512BitVector())
9326 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9329 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9330 SelectionDAG &DAG) {
9331 if (Subtarget->hasFp256()) {
9332 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9340 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9341 SelectionDAG &DAG) {
9343 MVT VT = Op.getSimpleValueType();
9344 SDValue In = Op.getOperand(0);
9345 MVT SVT = In.getSimpleValueType();
9347 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9348 return LowerZERO_EXTEND_AVX512(Op, DAG);
9350 if (Subtarget->hasFp256()) {
9351 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9356 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9357 VT.getVectorNumElements() != SVT.getVectorNumElements());
9361 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9363 MVT VT = Op.getSimpleValueType();
9364 SDValue In = Op.getOperand(0);
9365 MVT InVT = In.getSimpleValueType();
9367 if (VT == MVT::i1) {
9368 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9369 "Invalid scalar TRUNCATE operation");
9370 if (InVT == MVT::i32)
9372 if (InVT.getSizeInBits() == 64)
9373 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9374 else if (InVT.getSizeInBits() < 32)
9375 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9376 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9378 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9379 "Invalid TRUNCATE operation");
9381 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9382 if (VT.getVectorElementType().getSizeInBits() >=8)
9383 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9385 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9386 unsigned NumElts = InVT.getVectorNumElements();
9387 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9388 if (InVT.getSizeInBits() < 512) {
9389 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9390 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9394 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9395 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9396 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9397 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9398 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9399 MachinePointerInfo::getConstantPool(),
9400 false, false, false, Alignment);
9401 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9402 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9403 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9406 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9407 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9408 if (Subtarget->hasInt256()) {
9409 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9410 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9411 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9413 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9414 DAG.getIntPtrConstant(0));
9417 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9418 DAG.getIntPtrConstant(0));
9419 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9420 DAG.getIntPtrConstant(2));
9421 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9422 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9423 static const int ShufMask[] = {0, 2, 4, 6};
9424 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9427 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9428 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9429 if (Subtarget->hasInt256()) {
9430 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9432 SmallVector<SDValue,32> pshufbMask;
9433 for (unsigned i = 0; i < 2; ++i) {
9434 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9435 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9436 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9437 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9438 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9439 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9440 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9441 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9442 for (unsigned j = 0; j < 8; ++j)
9443 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9445 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9446 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9447 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9449 static const int ShufMask[] = {0, 2, -1, -1};
9450 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9452 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9453 DAG.getIntPtrConstant(0));
9454 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9457 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9458 DAG.getIntPtrConstant(0));
9460 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9461 DAG.getIntPtrConstant(4));
9463 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9464 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9467 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9468 -1, -1, -1, -1, -1, -1, -1, -1};
9470 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9471 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9472 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9474 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9475 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9477 // The MOVLHPS Mask:
9478 static const int ShufMask2[] = {0, 1, 4, 5};
9479 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9480 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9483 // Handle truncation of V256 to V128 using shuffles.
9484 if (!VT.is128BitVector() || !InVT.is256BitVector())
9487 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9489 unsigned NumElems = VT.getVectorNumElements();
9490 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9492 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9493 // Prepare truncation shuffle mask
9494 for (unsigned i = 0; i != NumElems; ++i)
9496 SDValue V = DAG.getVectorShuffle(NVT, DL,
9497 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9498 DAG.getUNDEF(NVT), &MaskVec[0]);
9499 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9500 DAG.getIntPtrConstant(0));
9503 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9504 SelectionDAG &DAG) const {
9505 assert(!Op.getSimpleValueType().isVector());
9507 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9508 /*IsSigned=*/ true, /*IsReplace=*/ false);
9509 SDValue FIST = Vals.first, StackSlot = Vals.second;
9510 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9511 if (!FIST.getNode()) return Op;
9513 if (StackSlot.getNode())
9515 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9516 FIST, StackSlot, MachinePointerInfo(),
9517 false, false, false, 0);
9519 // The node is the result.
9523 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9524 SelectionDAG &DAG) const {
9525 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9526 /*IsSigned=*/ false, /*IsReplace=*/ false);
9527 SDValue FIST = Vals.first, StackSlot = Vals.second;
9528 assert(FIST.getNode() && "Unexpected failure");
9530 if (StackSlot.getNode())
9532 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9533 FIST, StackSlot, MachinePointerInfo(),
9534 false, false, false, 0);
9536 // The node is the result.
9540 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9542 MVT VT = Op.getSimpleValueType();
9543 SDValue In = Op.getOperand(0);
9544 MVT SVT = In.getSimpleValueType();
9546 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9548 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9549 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9550 In, DAG.getUNDEF(SVT)));
9553 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9554 LLVMContext *Context = DAG.getContext();
9556 MVT VT = Op.getSimpleValueType();
9558 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9559 if (VT.isVector()) {
9560 EltVT = VT.getVectorElementType();
9561 NumElts = VT.getVectorNumElements();
9564 if (EltVT == MVT::f64)
9565 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9566 APInt(64, ~(1ULL << 63))));
9568 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9569 APInt(32, ~(1U << 31))));
9570 C = ConstantVector::getSplat(NumElts, C);
9571 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9572 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9573 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9574 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9575 MachinePointerInfo::getConstantPool(),
9576 false, false, false, Alignment);
9577 if (VT.isVector()) {
9578 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9579 return DAG.getNode(ISD::BITCAST, dl, VT,
9580 DAG.getNode(ISD::AND, dl, ANDVT,
9581 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9583 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9585 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9588 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9589 LLVMContext *Context = DAG.getContext();
9591 MVT VT = Op.getSimpleValueType();
9593 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9594 if (VT.isVector()) {
9595 EltVT = VT.getVectorElementType();
9596 NumElts = VT.getVectorNumElements();
9599 if (EltVT == MVT::f64)
9600 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9601 APInt(64, 1ULL << 63)));
9603 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9604 APInt(32, 1U << 31)));
9605 C = ConstantVector::getSplat(NumElts, C);
9606 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9607 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9608 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9609 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9610 MachinePointerInfo::getConstantPool(),
9611 false, false, false, Alignment);
9612 if (VT.isVector()) {
9613 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9614 return DAG.getNode(ISD::BITCAST, dl, VT,
9615 DAG.getNode(ISD::XOR, dl, XORVT,
9616 DAG.getNode(ISD::BITCAST, dl, XORVT,
9618 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9621 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9624 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9625 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9626 LLVMContext *Context = DAG.getContext();
9627 SDValue Op0 = Op.getOperand(0);
9628 SDValue Op1 = Op.getOperand(1);
9630 MVT VT = Op.getSimpleValueType();
9631 MVT SrcVT = Op1.getSimpleValueType();
9633 // If second operand is smaller, extend it first.
9634 if (SrcVT.bitsLT(VT)) {
9635 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9638 // And if it is bigger, shrink it first.
9639 if (SrcVT.bitsGT(VT)) {
9640 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9644 // At this point the operands and the result should have the same
9645 // type, and that won't be f80 since that is not custom lowered.
9647 // First get the sign bit of second operand.
9648 SmallVector<Constant*,4> CV;
9649 if (SrcVT == MVT::f64) {
9650 const fltSemantics &Sem = APFloat::IEEEdouble;
9651 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9652 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9654 const fltSemantics &Sem = APFloat::IEEEsingle;
9655 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9656 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9657 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9658 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9660 Constant *C = ConstantVector::get(CV);
9661 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9662 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9663 MachinePointerInfo::getConstantPool(),
9664 false, false, false, 16);
9665 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9667 // Shift sign bit right or left if the two operands have different types.
9668 if (SrcVT.bitsGT(VT)) {
9669 // Op0 is MVT::f32, Op1 is MVT::f64.
9670 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9671 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9672 DAG.getConstant(32, MVT::i32));
9673 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9674 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9675 DAG.getIntPtrConstant(0));
9678 // Clear first operand sign bit.
9680 if (VT == MVT::f64) {
9681 const fltSemantics &Sem = APFloat::IEEEdouble;
9682 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9683 APInt(64, ~(1ULL << 63)))));
9684 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9686 const fltSemantics &Sem = APFloat::IEEEsingle;
9687 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9688 APInt(32, ~(1U << 31)))));
9689 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9690 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9691 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9693 C = ConstantVector::get(CV);
9694 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9695 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9696 MachinePointerInfo::getConstantPool(),
9697 false, false, false, 16);
9698 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9700 // Or the value with the sign bit.
9701 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9704 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9705 SDValue N0 = Op.getOperand(0);
9707 MVT VT = Op.getSimpleValueType();
9709 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9710 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9711 DAG.getConstant(1, VT));
9712 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9715 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9717 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9718 SelectionDAG &DAG) {
9719 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9721 if (!Subtarget->hasSSE41())
9724 if (!Op->hasOneUse())
9727 SDNode *N = Op.getNode();
9730 SmallVector<SDValue, 8> Opnds;
9731 DenseMap<SDValue, unsigned> VecInMap;
9732 SmallVector<SDValue, 8> VecIns;
9733 EVT VT = MVT::Other;
9735 // Recognize a special case where a vector is casted into wide integer to
9737 Opnds.push_back(N->getOperand(0));
9738 Opnds.push_back(N->getOperand(1));
9740 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9741 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9742 // BFS traverse all OR'd operands.
9743 if (I->getOpcode() == ISD::OR) {
9744 Opnds.push_back(I->getOperand(0));
9745 Opnds.push_back(I->getOperand(1));
9746 // Re-evaluate the number of nodes to be traversed.
9747 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9751 // Quit if a non-EXTRACT_VECTOR_ELT
9752 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9755 // Quit if without a constant index.
9756 SDValue Idx = I->getOperand(1);
9757 if (!isa<ConstantSDNode>(Idx))
9760 SDValue ExtractedFromVec = I->getOperand(0);
9761 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9762 if (M == VecInMap.end()) {
9763 VT = ExtractedFromVec.getValueType();
9764 // Quit if not 128/256-bit vector.
9765 if (!VT.is128BitVector() && !VT.is256BitVector())
9767 // Quit if not the same type.
9768 if (VecInMap.begin() != VecInMap.end() &&
9769 VT != VecInMap.begin()->first.getValueType())
9771 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9772 VecIns.push_back(ExtractedFromVec);
9774 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9777 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9778 "Not extracted from 128-/256-bit vector.");
9780 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9782 for (DenseMap<SDValue, unsigned>::const_iterator
9783 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9784 // Quit if not all elements are used.
9785 if (I->second != FullMask)
9789 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9791 // Cast all vectors into TestVT for PTEST.
9792 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9793 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9795 // If more than one full vectors are evaluated, OR them first before PTEST.
9796 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9797 // Each iteration will OR 2 nodes and append the result until there is only
9798 // 1 node left, i.e. the final OR'd value of all vectors.
9799 SDValue LHS = VecIns[Slot];
9800 SDValue RHS = VecIns[Slot + 1];
9801 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9804 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9805 VecIns.back(), VecIns.back());
9808 /// \brief return true if \c Op has a use that doesn't just read flags.
9809 static bool hasNonFlagsUse(SDValue Op) {
9810 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9813 unsigned UOpNo = UI.getOperandNo();
9814 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9815 // Look pass truncate.
9816 UOpNo = User->use_begin().getOperandNo();
9817 User = *User->use_begin();
9820 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9821 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9827 /// Emit nodes that will be selected as "test Op0,Op0", or something
9829 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9830 SelectionDAG &DAG) const {
9831 if (Op.getValueType() == MVT::i1)
9832 // KORTEST instruction should be selected
9833 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9834 DAG.getConstant(0, Op.getValueType()));
9836 // CF and OF aren't always set the way we want. Determine which
9837 // of these we need.
9838 bool NeedCF = false;
9839 bool NeedOF = false;
9842 case X86::COND_A: case X86::COND_AE:
9843 case X86::COND_B: case X86::COND_BE:
9846 case X86::COND_G: case X86::COND_GE:
9847 case X86::COND_L: case X86::COND_LE:
9848 case X86::COND_O: case X86::COND_NO:
9852 // See if we can use the EFLAGS value from the operand instead of
9853 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9854 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9855 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9856 // Emit a CMP with 0, which is the TEST pattern.
9857 //if (Op.getValueType() == MVT::i1)
9858 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9859 // DAG.getConstant(0, MVT::i1));
9860 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9861 DAG.getConstant(0, Op.getValueType()));
9863 unsigned Opcode = 0;
9864 unsigned NumOperands = 0;
9866 // Truncate operations may prevent the merge of the SETCC instruction
9867 // and the arithmetic instruction before it. Attempt to truncate the operands
9868 // of the arithmetic instruction and use a reduced bit-width instruction.
9869 bool NeedTruncation = false;
9870 SDValue ArithOp = Op;
9871 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9872 SDValue Arith = Op->getOperand(0);
9873 // Both the trunc and the arithmetic op need to have one user each.
9874 if (Arith->hasOneUse())
9875 switch (Arith.getOpcode()) {
9882 NeedTruncation = true;
9888 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9889 // which may be the result of a CAST. We use the variable 'Op', which is the
9890 // non-casted variable when we check for possible users.
9891 switch (ArithOp.getOpcode()) {
9893 // Due to an isel shortcoming, be conservative if this add is likely to be
9894 // selected as part of a load-modify-store instruction. When the root node
9895 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9896 // uses of other nodes in the match, such as the ADD in this case. This
9897 // leads to the ADD being left around and reselected, with the result being
9898 // two adds in the output. Alas, even if none our users are stores, that
9899 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9900 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9901 // climbing the DAG back to the root, and it doesn't seem to be worth the
9903 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9904 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9905 if (UI->getOpcode() != ISD::CopyToReg &&
9906 UI->getOpcode() != ISD::SETCC &&
9907 UI->getOpcode() != ISD::STORE)
9910 if (ConstantSDNode *C =
9911 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9912 // An add of one will be selected as an INC.
9913 if (C->getAPIntValue() == 1) {
9914 Opcode = X86ISD::INC;
9919 // An add of negative one (subtract of one) will be selected as a DEC.
9920 if (C->getAPIntValue().isAllOnesValue()) {
9921 Opcode = X86ISD::DEC;
9927 // Otherwise use a regular EFLAGS-setting add.
9928 Opcode = X86ISD::ADD;
9933 // If we have a constant logical shift that's only used in a comparison
9934 // against zero turn it into an equivalent AND. This allows turning it into
9935 // a TEST instruction later.
9936 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9937 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9938 EVT VT = Op.getValueType();
9939 unsigned BitWidth = VT.getSizeInBits();
9940 unsigned ShAmt = Op->getConstantOperandVal(1);
9941 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9943 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9944 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9945 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9946 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9948 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9949 DAG.getConstant(Mask, VT));
9950 DAG.ReplaceAllUsesWith(Op, New);
9956 // If the primary and result isn't used, don't bother using X86ISD::AND,
9957 // because a TEST instruction will be better.
9958 if (!hasNonFlagsUse(Op))
9964 // Due to the ISEL shortcoming noted above, be conservative if this op is
9965 // likely to be selected as part of a load-modify-store instruction.
9966 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9967 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9968 if (UI->getOpcode() == ISD::STORE)
9971 // Otherwise use a regular EFLAGS-setting instruction.
9972 switch (ArithOp.getOpcode()) {
9973 default: llvm_unreachable("unexpected operator!");
9974 case ISD::SUB: Opcode = X86ISD::SUB; break;
9975 case ISD::XOR: Opcode = X86ISD::XOR; break;
9976 case ISD::AND: Opcode = X86ISD::AND; break;
9978 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9979 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9980 if (EFLAGS.getNode())
9983 Opcode = X86ISD::OR;
9997 return SDValue(Op.getNode(), 1);
10003 // If we found that truncation is beneficial, perform the truncation and
10005 if (NeedTruncation) {
10006 EVT VT = Op.getValueType();
10007 SDValue WideVal = Op->getOperand(0);
10008 EVT WideVT = WideVal.getValueType();
10009 unsigned ConvertedOp = 0;
10010 // Use a target machine opcode to prevent further DAGCombine
10011 // optimizations that may separate the arithmetic operations
10012 // from the setcc node.
10013 switch (WideVal.getOpcode()) {
10015 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10016 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10017 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10018 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10019 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10023 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10024 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10025 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10026 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10027 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10033 // Emit a CMP with 0, which is the TEST pattern.
10034 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10035 DAG.getConstant(0, Op.getValueType()));
10037 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10038 SmallVector<SDValue, 4> Ops;
10039 for (unsigned i = 0; i != NumOperands; ++i)
10040 Ops.push_back(Op.getOperand(i));
10042 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10043 DAG.ReplaceAllUsesWith(Op, New);
10044 return SDValue(New.getNode(), 1);
10047 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10049 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10050 SDLoc dl, SelectionDAG &DAG) const {
10051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10052 if (C->getAPIntValue() == 0)
10053 return EmitTest(Op0, X86CC, dl, DAG);
10055 if (Op0.getValueType() == MVT::i1)
10056 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10059 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10060 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10061 // Do the comparison at i32 if it's smaller, besides the Atom case.
10062 // This avoids subregister aliasing issues. Keep the smaller reference
10063 // if we're optimizing for size, however, as that'll allow better folding
10064 // of memory operations.
10065 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10066 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10067 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10068 !Subtarget->isAtom()) {
10069 unsigned ExtendOp =
10070 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10071 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10072 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10074 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10075 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10076 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10078 return SDValue(Sub.getNode(), 1);
10080 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10083 /// Convert a comparison if required by the subtarget.
10084 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10085 SelectionDAG &DAG) const {
10086 // If the subtarget does not support the FUCOMI instruction, floating-point
10087 // comparisons have to be converted.
10088 if (Subtarget->hasCMov() ||
10089 Cmp.getOpcode() != X86ISD::CMP ||
10090 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10091 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10094 // The instruction selector will select an FUCOM instruction instead of
10095 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10096 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10097 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10099 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10100 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10101 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10102 DAG.getConstant(8, MVT::i8));
10103 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10104 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10107 static bool isAllOnes(SDValue V) {
10108 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10109 return C && C->isAllOnesValue();
10112 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10113 /// if it's possible.
10114 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10115 SDLoc dl, SelectionDAG &DAG) const {
10116 SDValue Op0 = And.getOperand(0);
10117 SDValue Op1 = And.getOperand(1);
10118 if (Op0.getOpcode() == ISD::TRUNCATE)
10119 Op0 = Op0.getOperand(0);
10120 if (Op1.getOpcode() == ISD::TRUNCATE)
10121 Op1 = Op1.getOperand(0);
10124 if (Op1.getOpcode() == ISD::SHL)
10125 std::swap(Op0, Op1);
10126 if (Op0.getOpcode() == ISD::SHL) {
10127 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10128 if (And00C->getZExtValue() == 1) {
10129 // If we looked past a truncate, check that it's only truncating away
10131 unsigned BitWidth = Op0.getValueSizeInBits();
10132 unsigned AndBitWidth = And.getValueSizeInBits();
10133 if (BitWidth > AndBitWidth) {
10135 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10136 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10140 RHS = Op0.getOperand(1);
10142 } else if (Op1.getOpcode() == ISD::Constant) {
10143 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10144 uint64_t AndRHSVal = AndRHS->getZExtValue();
10145 SDValue AndLHS = Op0;
10147 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10148 LHS = AndLHS.getOperand(0);
10149 RHS = AndLHS.getOperand(1);
10152 // Use BT if the immediate can't be encoded in a TEST instruction.
10153 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10155 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10159 if (LHS.getNode()) {
10160 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10161 // instruction. Since the shift amount is in-range-or-undefined, we know
10162 // that doing a bittest on the i32 value is ok. We extend to i32 because
10163 // the encoding for the i16 version is larger than the i32 version.
10164 // Also promote i16 to i32 for performance / code size reason.
10165 if (LHS.getValueType() == MVT::i8 ||
10166 LHS.getValueType() == MVT::i16)
10167 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10169 // If the operand types disagree, extend the shift amount to match. Since
10170 // BT ignores high bits (like shifts) we can use anyextend.
10171 if (LHS.getValueType() != RHS.getValueType())
10172 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10174 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10175 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10176 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10177 DAG.getConstant(Cond, MVT::i8), BT);
10183 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10185 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10190 // SSE Condition code mapping:
10199 switch (SetCCOpcode) {
10200 default: llvm_unreachable("Unexpected SETCC condition");
10202 case ISD::SETEQ: SSECC = 0; break;
10204 case ISD::SETGT: Swap = true; // Fallthrough
10206 case ISD::SETOLT: SSECC = 1; break;
10208 case ISD::SETGE: Swap = true; // Fallthrough
10210 case ISD::SETOLE: SSECC = 2; break;
10211 case ISD::SETUO: SSECC = 3; break;
10213 case ISD::SETNE: SSECC = 4; break;
10214 case ISD::SETULE: Swap = true; // Fallthrough
10215 case ISD::SETUGE: SSECC = 5; break;
10216 case ISD::SETULT: Swap = true; // Fallthrough
10217 case ISD::SETUGT: SSECC = 6; break;
10218 case ISD::SETO: SSECC = 7; break;
10220 case ISD::SETONE: SSECC = 8; break;
10223 std::swap(Op0, Op1);
10228 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10229 // ones, and then concatenate the result back.
10230 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10231 MVT VT = Op.getSimpleValueType();
10233 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10234 "Unsupported value type for operation");
10236 unsigned NumElems = VT.getVectorNumElements();
10238 SDValue CC = Op.getOperand(2);
10240 // Extract the LHS vectors
10241 SDValue LHS = Op.getOperand(0);
10242 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10243 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10245 // Extract the RHS vectors
10246 SDValue RHS = Op.getOperand(1);
10247 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10248 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10250 // Issue the operation on the smaller types and concatenate the result back
10251 MVT EltVT = VT.getVectorElementType();
10252 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10253 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10254 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10255 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10258 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10259 const X86Subtarget *Subtarget) {
10260 SDValue Op0 = Op.getOperand(0);
10261 SDValue Op1 = Op.getOperand(1);
10262 SDValue CC = Op.getOperand(2);
10263 MVT VT = Op.getSimpleValueType();
10266 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10267 Op.getValueType().getScalarType() == MVT::i1 &&
10268 "Cannot set masked compare for this operation");
10270 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10272 bool Unsigned = false;
10275 switch (SetCCOpcode) {
10276 default: llvm_unreachable("Unexpected SETCC condition");
10277 case ISD::SETNE: SSECC = 4; break;
10278 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10279 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10280 case ISD::SETLT: Swap = true; //fall-through
10281 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10282 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10283 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10284 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10285 case ISD::SETULE: Unsigned = true; //fall-through
10286 case ISD::SETLE: SSECC = 2; break;
10290 std::swap(Op0, Op1);
10292 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10293 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10294 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10295 DAG.getConstant(SSECC, MVT::i8));
10298 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10299 /// operand \p Op1. If non-trivial (for example because it's not constant)
10300 /// return an empty value.
10301 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10303 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10307 MVT VT = Op1.getSimpleValueType();
10308 MVT EVT = VT.getVectorElementType();
10309 unsigned n = VT.getVectorNumElements();
10310 SmallVector<SDValue, 8> ULTOp1;
10312 for (unsigned i = 0; i < n; ++i) {
10313 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10314 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10317 // Avoid underflow.
10318 APInt Val = Elt->getAPIntValue();
10322 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10325 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10328 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10329 SelectionDAG &DAG) {
10330 SDValue Op0 = Op.getOperand(0);
10331 SDValue Op1 = Op.getOperand(1);
10332 SDValue CC = Op.getOperand(2);
10333 MVT VT = Op.getSimpleValueType();
10334 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10335 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10340 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10341 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10344 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10345 unsigned Opc = X86ISD::CMPP;
10346 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10347 assert(VT.getVectorNumElements() <= 16);
10348 Opc = X86ISD::CMPM;
10350 // In the two special cases we can't handle, emit two comparisons.
10353 unsigned CombineOpc;
10354 if (SetCCOpcode == ISD::SETUEQ) {
10355 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10357 assert(SetCCOpcode == ISD::SETONE);
10358 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10361 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10362 DAG.getConstant(CC0, MVT::i8));
10363 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10364 DAG.getConstant(CC1, MVT::i8));
10365 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10367 // Handle all other FP comparisons here.
10368 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10369 DAG.getConstant(SSECC, MVT::i8));
10372 // Break 256-bit integer vector compare into smaller ones.
10373 if (VT.is256BitVector() && !Subtarget->hasInt256())
10374 return Lower256IntVSETCC(Op, DAG);
10376 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10377 EVT OpVT = Op1.getValueType();
10378 if (Subtarget->hasAVX512()) {
10379 if (Op1.getValueType().is512BitVector() ||
10380 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10381 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10383 // In AVX-512 architecture setcc returns mask with i1 elements,
10384 // But there is no compare instruction for i8 and i16 elements.
10385 // We are not talking about 512-bit operands in this case, these
10386 // types are illegal.
10388 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10389 OpVT.getVectorElementType().getSizeInBits() >= 8))
10390 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10391 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10394 // We are handling one of the integer comparisons here. Since SSE only has
10395 // GT and EQ comparisons for integer, swapping operands and multiple
10396 // operations may be required for some comparisons.
10398 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10399 bool Subus = false;
10401 switch (SetCCOpcode) {
10402 default: llvm_unreachable("Unexpected SETCC condition");
10403 case ISD::SETNE: Invert = true;
10404 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10405 case ISD::SETLT: Swap = true;
10406 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10407 case ISD::SETGE: Swap = true;
10408 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10409 Invert = true; break;
10410 case ISD::SETULT: Swap = true;
10411 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10412 FlipSigns = true; break;
10413 case ISD::SETUGE: Swap = true;
10414 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10415 FlipSigns = true; Invert = true; break;
10418 // Special case: Use min/max operations for SETULE/SETUGE
10419 MVT VET = VT.getVectorElementType();
10421 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10422 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10425 switch (SetCCOpcode) {
10427 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10428 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10431 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10434 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10435 if (!MinMax && hasSubus) {
10436 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10438 // t = psubus Op0, Op1
10439 // pcmpeq t, <0..0>
10440 switch (SetCCOpcode) {
10442 case ISD::SETULT: {
10443 // If the comparison is against a constant we can turn this into a
10444 // setule. With psubus, setule does not require a swap. This is
10445 // beneficial because the constant in the register is no longer
10446 // destructed as the destination so it can be hoisted out of a loop.
10447 // Only do this pre-AVX since vpcmp* is no longer destructive.
10448 if (Subtarget->hasAVX())
10450 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10451 if (ULEOp1.getNode()) {
10453 Subus = true; Invert = false; Swap = false;
10457 // Psubus is better than flip-sign because it requires no inversion.
10458 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10459 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10463 Opc = X86ISD::SUBUS;
10469 std::swap(Op0, Op1);
10471 // Check that the operation in question is available (most are plain SSE2,
10472 // but PCMPGTQ and PCMPEQQ have different requirements).
10473 if (VT == MVT::v2i64) {
10474 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10475 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10477 // First cast everything to the right type.
10478 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10479 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10481 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10482 // bits of the inputs before performing those operations. The lower
10483 // compare is always unsigned.
10486 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10488 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10489 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10490 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10491 Sign, Zero, Sign, Zero);
10493 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10494 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10496 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10497 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10498 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10500 // Create masks for only the low parts/high parts of the 64 bit integers.
10501 static const int MaskHi[] = { 1, 1, 3, 3 };
10502 static const int MaskLo[] = { 0, 0, 2, 2 };
10503 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10504 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10505 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10507 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10508 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10511 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10513 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10516 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10517 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10518 // pcmpeqd + pshufd + pand.
10519 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10521 // First cast everything to the right type.
10522 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10523 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10526 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10528 // Make sure the lower and upper halves are both all-ones.
10529 static const int Mask[] = { 1, 0, 3, 2 };
10530 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10531 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10534 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10536 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10540 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10541 // bits of the inputs before performing those operations.
10543 EVT EltVT = VT.getVectorElementType();
10544 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10545 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10546 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10549 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10551 // If the logical-not of the result is required, perform that now.
10553 Result = DAG.getNOT(dl, Result, VT);
10556 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10559 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10560 getZeroVector(VT, Subtarget, DAG, dl));
10565 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10567 MVT VT = Op.getSimpleValueType();
10569 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10571 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10572 && "SetCC type must be 8-bit or 1-bit integer");
10573 SDValue Op0 = Op.getOperand(0);
10574 SDValue Op1 = Op.getOperand(1);
10576 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10578 // Optimize to BT if possible.
10579 // Lower (X & (1 << N)) == 0 to BT(X, N).
10580 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10581 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10582 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10583 Op1.getOpcode() == ISD::Constant &&
10584 cast<ConstantSDNode>(Op1)->isNullValue() &&
10585 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10586 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10587 if (NewSetCC.getNode())
10591 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10593 if (Op1.getOpcode() == ISD::Constant &&
10594 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10595 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10596 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10598 // If the input is a setcc, then reuse the input setcc or use a new one with
10599 // the inverted condition.
10600 if (Op0.getOpcode() == X86ISD::SETCC) {
10601 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10602 bool Invert = (CC == ISD::SETNE) ^
10603 cast<ConstantSDNode>(Op1)->isNullValue();
10607 CCode = X86::GetOppositeBranchCondition(CCode);
10608 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10609 DAG.getConstant(CCode, MVT::i8),
10610 Op0.getOperand(1));
10612 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10616 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10617 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10618 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10620 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10621 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10624 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10625 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10626 if (X86CC == X86::COND_INVALID)
10629 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10630 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10631 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10632 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10634 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10638 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10639 static bool isX86LogicalCmp(SDValue Op) {
10640 unsigned Opc = Op.getNode()->getOpcode();
10641 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10642 Opc == X86ISD::SAHF)
10644 if (Op.getResNo() == 1 &&
10645 (Opc == X86ISD::ADD ||
10646 Opc == X86ISD::SUB ||
10647 Opc == X86ISD::ADC ||
10648 Opc == X86ISD::SBB ||
10649 Opc == X86ISD::SMUL ||
10650 Opc == X86ISD::UMUL ||
10651 Opc == X86ISD::INC ||
10652 Opc == X86ISD::DEC ||
10653 Opc == X86ISD::OR ||
10654 Opc == X86ISD::XOR ||
10655 Opc == X86ISD::AND))
10658 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10664 static bool isZero(SDValue V) {
10665 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10666 return C && C->isNullValue();
10669 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10670 if (V.getOpcode() != ISD::TRUNCATE)
10673 SDValue VOp0 = V.getOperand(0);
10674 unsigned InBits = VOp0.getValueSizeInBits();
10675 unsigned Bits = V.getValueSizeInBits();
10676 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10679 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10680 bool addTest = true;
10681 SDValue Cond = Op.getOperand(0);
10682 SDValue Op1 = Op.getOperand(1);
10683 SDValue Op2 = Op.getOperand(2);
10685 EVT VT = Op1.getValueType();
10688 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10689 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10690 // sequence later on.
10691 if (Cond.getOpcode() == ISD::SETCC &&
10692 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10693 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10694 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10695 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10696 int SSECC = translateX86FSETCC(
10697 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10700 if (Subtarget->hasAVX512()) {
10701 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10702 DAG.getConstant(SSECC, MVT::i8));
10703 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10705 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10706 DAG.getConstant(SSECC, MVT::i8));
10707 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10708 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10709 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10713 if (Cond.getOpcode() == ISD::SETCC) {
10714 SDValue NewCond = LowerSETCC(Cond, DAG);
10715 if (NewCond.getNode())
10719 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10720 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10721 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10722 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10723 if (Cond.getOpcode() == X86ISD::SETCC &&
10724 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10725 isZero(Cond.getOperand(1).getOperand(1))) {
10726 SDValue Cmp = Cond.getOperand(1);
10728 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10730 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10731 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10732 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10734 SDValue CmpOp0 = Cmp.getOperand(0);
10735 // Apply further optimizations for special cases
10736 // (select (x != 0), -1, 0) -> neg & sbb
10737 // (select (x == 0), 0, -1) -> neg & sbb
10738 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10739 if (YC->isNullValue() &&
10740 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10741 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10742 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10743 DAG.getConstant(0, CmpOp0.getValueType()),
10745 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10746 DAG.getConstant(X86::COND_B, MVT::i8),
10747 SDValue(Neg.getNode(), 1));
10751 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10752 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10753 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10755 SDValue Res = // Res = 0 or -1.
10756 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10757 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10759 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10760 Res = DAG.getNOT(DL, Res, Res.getValueType());
10762 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10763 if (!N2C || !N2C->isNullValue())
10764 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10769 // Look past (and (setcc_carry (cmp ...)), 1).
10770 if (Cond.getOpcode() == ISD::AND &&
10771 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10772 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10773 if (C && C->getAPIntValue() == 1)
10774 Cond = Cond.getOperand(0);
10777 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10778 // setting operand in place of the X86ISD::SETCC.
10779 unsigned CondOpcode = Cond.getOpcode();
10780 if (CondOpcode == X86ISD::SETCC ||
10781 CondOpcode == X86ISD::SETCC_CARRY) {
10782 CC = Cond.getOperand(0);
10784 SDValue Cmp = Cond.getOperand(1);
10785 unsigned Opc = Cmp.getOpcode();
10786 MVT VT = Op.getSimpleValueType();
10788 bool IllegalFPCMov = false;
10789 if (VT.isFloatingPoint() && !VT.isVector() &&
10790 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10791 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10793 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10794 Opc == X86ISD::BT) { // FIXME
10798 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10799 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10800 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10801 Cond.getOperand(0).getValueType() != MVT::i8)) {
10802 SDValue LHS = Cond.getOperand(0);
10803 SDValue RHS = Cond.getOperand(1);
10804 unsigned X86Opcode;
10807 switch (CondOpcode) {
10808 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10809 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10810 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10811 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10812 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10813 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10814 default: llvm_unreachable("unexpected overflowing operator");
10816 if (CondOpcode == ISD::UMULO)
10817 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10820 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10822 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10824 if (CondOpcode == ISD::UMULO)
10825 Cond = X86Op.getValue(2);
10827 Cond = X86Op.getValue(1);
10829 CC = DAG.getConstant(X86Cond, MVT::i8);
10834 // Look pass the truncate if the high bits are known zero.
10835 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10836 Cond = Cond.getOperand(0);
10838 // We know the result of AND is compared against zero. Try to match
10840 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10841 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10842 if (NewSetCC.getNode()) {
10843 CC = NewSetCC.getOperand(0);
10844 Cond = NewSetCC.getOperand(1);
10851 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10852 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10855 // a < b ? -1 : 0 -> RES = ~setcc_carry
10856 // a < b ? 0 : -1 -> RES = setcc_carry
10857 // a >= b ? -1 : 0 -> RES = setcc_carry
10858 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10859 if (Cond.getOpcode() == X86ISD::SUB) {
10860 Cond = ConvertCmpIfNecessary(Cond, DAG);
10861 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10863 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10864 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10865 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10866 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10867 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10868 return DAG.getNOT(DL, Res, Res.getValueType());
10873 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10874 // widen the cmov and push the truncate through. This avoids introducing a new
10875 // branch during isel and doesn't add any extensions.
10876 if (Op.getValueType() == MVT::i8 &&
10877 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10878 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10879 if (T1.getValueType() == T2.getValueType() &&
10880 // Blacklist CopyFromReg to avoid partial register stalls.
10881 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10882 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10883 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10884 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10888 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10889 // condition is true.
10890 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10891 SDValue Ops[] = { Op2, Op1, CC, Cond };
10892 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10895 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10896 MVT VT = Op->getSimpleValueType(0);
10897 SDValue In = Op->getOperand(0);
10898 MVT InVT = In.getSimpleValueType();
10901 unsigned int NumElts = VT.getVectorNumElements();
10902 if (NumElts != 8 && NumElts != 16)
10905 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10906 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10909 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10911 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10912 Constant *C = ConstantInt::get(*DAG.getContext(),
10913 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10915 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10916 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10917 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10918 MachinePointerInfo::getConstantPool(),
10919 false, false, false, Alignment);
10920 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10921 if (VT.is512BitVector())
10923 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10926 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10927 SelectionDAG &DAG) {
10928 MVT VT = Op->getSimpleValueType(0);
10929 SDValue In = Op->getOperand(0);
10930 MVT InVT = In.getSimpleValueType();
10933 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10934 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10936 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10937 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10938 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10941 if (Subtarget->hasInt256())
10942 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10944 // Optimize vectors in AVX mode
10945 // Sign extend v8i16 to v8i32 and
10948 // Divide input vector into two parts
10949 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10950 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10951 // concat the vectors to original VT
10953 unsigned NumElems = InVT.getVectorNumElements();
10954 SDValue Undef = DAG.getUNDEF(InVT);
10956 SmallVector<int,8> ShufMask1(NumElems, -1);
10957 for (unsigned i = 0; i != NumElems/2; ++i)
10960 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10962 SmallVector<int,8> ShufMask2(NumElems, -1);
10963 for (unsigned i = 0; i != NumElems/2; ++i)
10964 ShufMask2[i] = i + NumElems/2;
10966 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10968 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10969 VT.getVectorNumElements()/2);
10971 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10972 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10974 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10977 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10978 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10979 // from the AND / OR.
10980 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10981 Opc = Op.getOpcode();
10982 if (Opc != ISD::OR && Opc != ISD::AND)
10984 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10985 Op.getOperand(0).hasOneUse() &&
10986 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10987 Op.getOperand(1).hasOneUse());
10990 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10991 // 1 and that the SETCC node has a single use.
10992 static bool isXor1OfSetCC(SDValue Op) {
10993 if (Op.getOpcode() != ISD::XOR)
10995 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10996 if (N1C && N1C->getAPIntValue() == 1) {
10997 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10998 Op.getOperand(0).hasOneUse();
11003 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11004 bool addTest = true;
11005 SDValue Chain = Op.getOperand(0);
11006 SDValue Cond = Op.getOperand(1);
11007 SDValue Dest = Op.getOperand(2);
11010 bool Inverted = false;
11012 if (Cond.getOpcode() == ISD::SETCC) {
11013 // Check for setcc([su]{add,sub,mul}o == 0).
11014 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11015 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11016 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11017 Cond.getOperand(0).getResNo() == 1 &&
11018 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11019 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11020 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11021 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11022 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11023 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11025 Cond = Cond.getOperand(0);
11027 SDValue NewCond = LowerSETCC(Cond, DAG);
11028 if (NewCond.getNode())
11033 // FIXME: LowerXALUO doesn't handle these!!
11034 else if (Cond.getOpcode() == X86ISD::ADD ||
11035 Cond.getOpcode() == X86ISD::SUB ||
11036 Cond.getOpcode() == X86ISD::SMUL ||
11037 Cond.getOpcode() == X86ISD::UMUL)
11038 Cond = LowerXALUO(Cond, DAG);
11041 // Look pass (and (setcc_carry (cmp ...)), 1).
11042 if (Cond.getOpcode() == ISD::AND &&
11043 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11044 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11045 if (C && C->getAPIntValue() == 1)
11046 Cond = Cond.getOperand(0);
11049 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11050 // setting operand in place of the X86ISD::SETCC.
11051 unsigned CondOpcode = Cond.getOpcode();
11052 if (CondOpcode == X86ISD::SETCC ||
11053 CondOpcode == X86ISD::SETCC_CARRY) {
11054 CC = Cond.getOperand(0);
11056 SDValue Cmp = Cond.getOperand(1);
11057 unsigned Opc = Cmp.getOpcode();
11058 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11059 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11063 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11067 // These can only come from an arithmetic instruction with overflow,
11068 // e.g. SADDO, UADDO.
11069 Cond = Cond.getNode()->getOperand(1);
11075 CondOpcode = Cond.getOpcode();
11076 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11077 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11078 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11079 Cond.getOperand(0).getValueType() != MVT::i8)) {
11080 SDValue LHS = Cond.getOperand(0);
11081 SDValue RHS = Cond.getOperand(1);
11082 unsigned X86Opcode;
11085 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11086 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11088 switch (CondOpcode) {
11089 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11091 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11093 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11096 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11097 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11099 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11101 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11104 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11105 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11106 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11107 default: llvm_unreachable("unexpected overflowing operator");
11110 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11111 if (CondOpcode == ISD::UMULO)
11112 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11115 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11117 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11119 if (CondOpcode == ISD::UMULO)
11120 Cond = X86Op.getValue(2);
11122 Cond = X86Op.getValue(1);
11124 CC = DAG.getConstant(X86Cond, MVT::i8);
11128 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11129 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11130 if (CondOpc == ISD::OR) {
11131 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11132 // two branches instead of an explicit OR instruction with a
11134 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11135 isX86LogicalCmp(Cmp)) {
11136 CC = Cond.getOperand(0).getOperand(0);
11137 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11138 Chain, Dest, CC, Cmp);
11139 CC = Cond.getOperand(1).getOperand(0);
11143 } else { // ISD::AND
11144 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11145 // two branches instead of an explicit AND instruction with a
11146 // separate test. However, we only do this if this block doesn't
11147 // have a fall-through edge, because this requires an explicit
11148 // jmp when the condition is false.
11149 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11150 isX86LogicalCmp(Cmp) &&
11151 Op.getNode()->hasOneUse()) {
11152 X86::CondCode CCode =
11153 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11154 CCode = X86::GetOppositeBranchCondition(CCode);
11155 CC = DAG.getConstant(CCode, MVT::i8);
11156 SDNode *User = *Op.getNode()->use_begin();
11157 // Look for an unconditional branch following this conditional branch.
11158 // We need this because we need to reverse the successors in order
11159 // to implement FCMP_OEQ.
11160 if (User->getOpcode() == ISD::BR) {
11161 SDValue FalseBB = User->getOperand(1);
11163 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11164 assert(NewBR == User);
11168 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11169 Chain, Dest, CC, Cmp);
11170 X86::CondCode CCode =
11171 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11172 CCode = X86::GetOppositeBranchCondition(CCode);
11173 CC = DAG.getConstant(CCode, MVT::i8);
11179 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11180 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11181 // It should be transformed during dag combiner except when the condition
11182 // is set by a arithmetics with overflow node.
11183 X86::CondCode CCode =
11184 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11185 CCode = X86::GetOppositeBranchCondition(CCode);
11186 CC = DAG.getConstant(CCode, MVT::i8);
11187 Cond = Cond.getOperand(0).getOperand(1);
11189 } else if (Cond.getOpcode() == ISD::SETCC &&
11190 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11191 // For FCMP_OEQ, we can emit
11192 // two branches instead of an explicit AND instruction with a
11193 // separate test. However, we only do this if this block doesn't
11194 // have a fall-through edge, because this requires an explicit
11195 // jmp when the condition is false.
11196 if (Op.getNode()->hasOneUse()) {
11197 SDNode *User = *Op.getNode()->use_begin();
11198 // Look for an unconditional branch following this conditional branch.
11199 // We need this because we need to reverse the successors in order
11200 // to implement FCMP_OEQ.
11201 if (User->getOpcode() == ISD::BR) {
11202 SDValue FalseBB = User->getOperand(1);
11204 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11205 assert(NewBR == User);
11209 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11210 Cond.getOperand(0), Cond.getOperand(1));
11211 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11212 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11213 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11214 Chain, Dest, CC, Cmp);
11215 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11220 } else if (Cond.getOpcode() == ISD::SETCC &&
11221 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11222 // For FCMP_UNE, we can emit
11223 // two branches instead of an explicit AND instruction with a
11224 // separate test. However, we only do this if this block doesn't
11225 // have a fall-through edge, because this requires an explicit
11226 // jmp when the condition is false.
11227 if (Op.getNode()->hasOneUse()) {
11228 SDNode *User = *Op.getNode()->use_begin();
11229 // Look for an unconditional branch following this conditional branch.
11230 // We need this because we need to reverse the successors in order
11231 // to implement FCMP_UNE.
11232 if (User->getOpcode() == ISD::BR) {
11233 SDValue FalseBB = User->getOperand(1);
11235 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11236 assert(NewBR == User);
11239 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11240 Cond.getOperand(0), Cond.getOperand(1));
11241 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11242 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11243 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11244 Chain, Dest, CC, Cmp);
11245 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11255 // Look pass the truncate if the high bits are known zero.
11256 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11257 Cond = Cond.getOperand(0);
11259 // We know the result of AND is compared against zero. Try to match
11261 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11262 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11263 if (NewSetCC.getNode()) {
11264 CC = NewSetCC.getOperand(0);
11265 Cond = NewSetCC.getOperand(1);
11272 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11273 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11275 Cond = ConvertCmpIfNecessary(Cond, DAG);
11276 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11277 Chain, Dest, CC, Cond);
11280 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11281 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11282 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11283 // that the guard pages used by the OS virtual memory manager are allocated in
11284 // correct sequence.
11286 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11287 SelectionDAG &DAG) const {
11288 MachineFunction &MF = DAG.getMachineFunction();
11289 bool SplitStack = MF.shouldSplitStack();
11290 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11296 SDNode* Node = Op.getNode();
11298 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11299 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11300 " not tell us which reg is the stack pointer!");
11301 EVT VT = Node->getValueType(0);
11302 SDValue Tmp1 = SDValue(Node, 0);
11303 SDValue Tmp2 = SDValue(Node, 1);
11304 SDValue Tmp3 = Node->getOperand(2);
11305 SDValue Chain = Tmp1.getOperand(0);
11307 // Chain the dynamic stack allocation so that it doesn't modify the stack
11308 // pointer when other instructions are using the stack.
11309 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11312 SDValue Size = Tmp2.getOperand(1);
11313 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11314 Chain = SP.getValue(1);
11315 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11316 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11317 unsigned StackAlign = TFI.getStackAlignment();
11318 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11319 if (Align > StackAlign)
11320 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11321 DAG.getConstant(-(uint64_t)Align, VT));
11322 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11324 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11325 DAG.getIntPtrConstant(0, true), SDValue(),
11328 SDValue Ops[2] = { Tmp1, Tmp2 };
11329 return DAG.getMergeValues(Ops, dl);
11333 SDValue Chain = Op.getOperand(0);
11334 SDValue Size = Op.getOperand(1);
11335 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11336 EVT VT = Op.getNode()->getValueType(0);
11338 bool Is64Bit = Subtarget->is64Bit();
11339 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11342 MachineRegisterInfo &MRI = MF.getRegInfo();
11345 // The 64 bit implementation of segmented stacks needs to clobber both r10
11346 // r11. This makes it impossible to use it along with nested parameters.
11347 const Function *F = MF.getFunction();
11349 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11351 if (I->hasNestAttr())
11352 report_fatal_error("Cannot use segmented stacks with functions that "
11353 "have nested arguments.");
11356 const TargetRegisterClass *AddrRegClass =
11357 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11358 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11359 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11360 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11361 DAG.getRegister(Vreg, SPTy));
11362 SDValue Ops1[2] = { Value, Chain };
11363 return DAG.getMergeValues(Ops1, dl);
11366 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11368 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11369 Flag = Chain.getValue(1);
11370 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11372 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11374 const X86RegisterInfo *RegInfo =
11375 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11376 unsigned SPReg = RegInfo->getStackRegister();
11377 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11378 Chain = SP.getValue(1);
11381 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11382 DAG.getConstant(-(uint64_t)Align, VT));
11383 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11386 SDValue Ops1[2] = { SP, Chain };
11387 return DAG.getMergeValues(Ops1, dl);
11391 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11392 MachineFunction &MF = DAG.getMachineFunction();
11393 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11395 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11398 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11399 // vastart just stores the address of the VarArgsFrameIndex slot into the
11400 // memory location argument.
11401 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11403 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11404 MachinePointerInfo(SV), false, false, 0);
11408 // gp_offset (0 - 6 * 8)
11409 // fp_offset (48 - 48 + 8 * 16)
11410 // overflow_arg_area (point to parameters coming in memory).
11412 SmallVector<SDValue, 8> MemOps;
11413 SDValue FIN = Op.getOperand(1);
11415 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11416 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11418 FIN, MachinePointerInfo(SV), false, false, 0);
11419 MemOps.push_back(Store);
11422 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11423 FIN, DAG.getIntPtrConstant(4));
11424 Store = DAG.getStore(Op.getOperand(0), DL,
11425 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11427 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11428 MemOps.push_back(Store);
11430 // Store ptr to overflow_arg_area
11431 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11432 FIN, DAG.getIntPtrConstant(4));
11433 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11435 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11436 MachinePointerInfo(SV, 8),
11438 MemOps.push_back(Store);
11440 // Store ptr to reg_save_area.
11441 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11442 FIN, DAG.getIntPtrConstant(8));
11443 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11445 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11446 MachinePointerInfo(SV, 16), false, false, 0);
11447 MemOps.push_back(Store);
11448 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11451 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11452 assert(Subtarget->is64Bit() &&
11453 "LowerVAARG only handles 64-bit va_arg!");
11454 assert((Subtarget->isTargetLinux() ||
11455 Subtarget->isTargetDarwin()) &&
11456 "Unhandled target in LowerVAARG");
11457 assert(Op.getNode()->getNumOperands() == 4);
11458 SDValue Chain = Op.getOperand(0);
11459 SDValue SrcPtr = Op.getOperand(1);
11460 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11461 unsigned Align = Op.getConstantOperandVal(3);
11464 EVT ArgVT = Op.getNode()->getValueType(0);
11465 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11466 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11469 // Decide which area this value should be read from.
11470 // TODO: Implement the AMD64 ABI in its entirety. This simple
11471 // selection mechanism works only for the basic types.
11472 if (ArgVT == MVT::f80) {
11473 llvm_unreachable("va_arg for f80 not yet implemented");
11474 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11475 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11476 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11477 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11479 llvm_unreachable("Unhandled argument type in LowerVAARG");
11482 if (ArgMode == 2) {
11483 // Sanity Check: Make sure using fp_offset makes sense.
11484 assert(!getTargetMachine().Options.UseSoftFloat &&
11485 !(DAG.getMachineFunction()
11486 .getFunction()->getAttributes()
11487 .hasAttribute(AttributeSet::FunctionIndex,
11488 Attribute::NoImplicitFloat)) &&
11489 Subtarget->hasSSE1());
11492 // Insert VAARG_64 node into the DAG
11493 // VAARG_64 returns two values: Variable Argument Address, Chain
11494 SmallVector<SDValue, 11> InstOps;
11495 InstOps.push_back(Chain);
11496 InstOps.push_back(SrcPtr);
11497 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11498 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11499 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11500 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11501 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11502 VTs, InstOps, MVT::i64,
11503 MachinePointerInfo(SV),
11505 /*Volatile=*/false,
11507 /*WriteMem=*/true);
11508 Chain = VAARG.getValue(1);
11510 // Load the next argument and return it
11511 return DAG.getLoad(ArgVT, dl,
11514 MachinePointerInfo(),
11515 false, false, false, 0);
11518 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11519 SelectionDAG &DAG) {
11520 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11521 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11522 SDValue Chain = Op.getOperand(0);
11523 SDValue DstPtr = Op.getOperand(1);
11524 SDValue SrcPtr = Op.getOperand(2);
11525 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11526 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11529 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11530 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11532 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11535 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11536 // amount is a constant. Takes immediate version of shift as input.
11537 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11538 SDValue SrcOp, uint64_t ShiftAmt,
11539 SelectionDAG &DAG) {
11540 MVT ElementType = VT.getVectorElementType();
11542 // Check for ShiftAmt >= element width
11543 if (ShiftAmt >= ElementType.getSizeInBits()) {
11544 if (Opc == X86ISD::VSRAI)
11545 ShiftAmt = ElementType.getSizeInBits() - 1;
11547 return DAG.getConstant(0, VT);
11550 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11551 && "Unknown target vector shift-by-constant node");
11553 // Fold this packed vector shift into a build vector if SrcOp is a
11554 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11555 if (VT == SrcOp.getSimpleValueType() &&
11556 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11557 SmallVector<SDValue, 8> Elts;
11558 unsigned NumElts = SrcOp->getNumOperands();
11559 ConstantSDNode *ND;
11562 default: llvm_unreachable(nullptr);
11563 case X86ISD::VSHLI:
11564 for (unsigned i=0; i!=NumElts; ++i) {
11565 SDValue CurrentOp = SrcOp->getOperand(i);
11566 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11567 Elts.push_back(CurrentOp);
11570 ND = cast<ConstantSDNode>(CurrentOp);
11571 const APInt &C = ND->getAPIntValue();
11572 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11575 case X86ISD::VSRLI:
11576 for (unsigned i=0; i!=NumElts; ++i) {
11577 SDValue CurrentOp = SrcOp->getOperand(i);
11578 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11579 Elts.push_back(CurrentOp);
11582 ND = cast<ConstantSDNode>(CurrentOp);
11583 const APInt &C = ND->getAPIntValue();
11584 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11587 case X86ISD::VSRAI:
11588 for (unsigned i=0; i!=NumElts; ++i) {
11589 SDValue CurrentOp = SrcOp->getOperand(i);
11590 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11591 Elts.push_back(CurrentOp);
11594 ND = cast<ConstantSDNode>(CurrentOp);
11595 const APInt &C = ND->getAPIntValue();
11596 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11601 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11604 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11607 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11608 // may or may not be a constant. Takes immediate version of shift as input.
11609 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11610 SDValue SrcOp, SDValue ShAmt,
11611 SelectionDAG &DAG) {
11612 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11614 // Catch shift-by-constant.
11615 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11616 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11617 CShAmt->getZExtValue(), DAG);
11619 // Change opcode to non-immediate version
11621 default: llvm_unreachable("Unknown target vector shift node");
11622 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11623 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11624 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11627 // Need to build a vector containing shift amount
11628 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11631 ShOps[1] = DAG.getConstant(0, MVT::i32);
11632 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11633 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11635 // The return type has to be a 128-bit type with the same element
11636 // type as the input type.
11637 MVT EltVT = VT.getVectorElementType();
11638 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11640 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11641 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11644 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11646 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11648 default: return SDValue(); // Don't custom lower most intrinsics.
11649 // Comparison intrinsics.
11650 case Intrinsic::x86_sse_comieq_ss:
11651 case Intrinsic::x86_sse_comilt_ss:
11652 case Intrinsic::x86_sse_comile_ss:
11653 case Intrinsic::x86_sse_comigt_ss:
11654 case Intrinsic::x86_sse_comige_ss:
11655 case Intrinsic::x86_sse_comineq_ss:
11656 case Intrinsic::x86_sse_ucomieq_ss:
11657 case Intrinsic::x86_sse_ucomilt_ss:
11658 case Intrinsic::x86_sse_ucomile_ss:
11659 case Intrinsic::x86_sse_ucomigt_ss:
11660 case Intrinsic::x86_sse_ucomige_ss:
11661 case Intrinsic::x86_sse_ucomineq_ss:
11662 case Intrinsic::x86_sse2_comieq_sd:
11663 case Intrinsic::x86_sse2_comilt_sd:
11664 case Intrinsic::x86_sse2_comile_sd:
11665 case Intrinsic::x86_sse2_comigt_sd:
11666 case Intrinsic::x86_sse2_comige_sd:
11667 case Intrinsic::x86_sse2_comineq_sd:
11668 case Intrinsic::x86_sse2_ucomieq_sd:
11669 case Intrinsic::x86_sse2_ucomilt_sd:
11670 case Intrinsic::x86_sse2_ucomile_sd:
11671 case Intrinsic::x86_sse2_ucomigt_sd:
11672 case Intrinsic::x86_sse2_ucomige_sd:
11673 case Intrinsic::x86_sse2_ucomineq_sd: {
11677 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11678 case Intrinsic::x86_sse_comieq_ss:
11679 case Intrinsic::x86_sse2_comieq_sd:
11680 Opc = X86ISD::COMI;
11683 case Intrinsic::x86_sse_comilt_ss:
11684 case Intrinsic::x86_sse2_comilt_sd:
11685 Opc = X86ISD::COMI;
11688 case Intrinsic::x86_sse_comile_ss:
11689 case Intrinsic::x86_sse2_comile_sd:
11690 Opc = X86ISD::COMI;
11693 case Intrinsic::x86_sse_comigt_ss:
11694 case Intrinsic::x86_sse2_comigt_sd:
11695 Opc = X86ISD::COMI;
11698 case Intrinsic::x86_sse_comige_ss:
11699 case Intrinsic::x86_sse2_comige_sd:
11700 Opc = X86ISD::COMI;
11703 case Intrinsic::x86_sse_comineq_ss:
11704 case Intrinsic::x86_sse2_comineq_sd:
11705 Opc = X86ISD::COMI;
11708 case Intrinsic::x86_sse_ucomieq_ss:
11709 case Intrinsic::x86_sse2_ucomieq_sd:
11710 Opc = X86ISD::UCOMI;
11713 case Intrinsic::x86_sse_ucomilt_ss:
11714 case Intrinsic::x86_sse2_ucomilt_sd:
11715 Opc = X86ISD::UCOMI;
11718 case Intrinsic::x86_sse_ucomile_ss:
11719 case Intrinsic::x86_sse2_ucomile_sd:
11720 Opc = X86ISD::UCOMI;
11723 case Intrinsic::x86_sse_ucomigt_ss:
11724 case Intrinsic::x86_sse2_ucomigt_sd:
11725 Opc = X86ISD::UCOMI;
11728 case Intrinsic::x86_sse_ucomige_ss:
11729 case Intrinsic::x86_sse2_ucomige_sd:
11730 Opc = X86ISD::UCOMI;
11733 case Intrinsic::x86_sse_ucomineq_ss:
11734 case Intrinsic::x86_sse2_ucomineq_sd:
11735 Opc = X86ISD::UCOMI;
11740 SDValue LHS = Op.getOperand(1);
11741 SDValue RHS = Op.getOperand(2);
11742 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11743 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11744 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11745 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11746 DAG.getConstant(X86CC, MVT::i8), Cond);
11747 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11750 // Arithmetic intrinsics.
11751 case Intrinsic::x86_sse2_pmulu_dq:
11752 case Intrinsic::x86_avx2_pmulu_dq:
11753 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11754 Op.getOperand(1), Op.getOperand(2));
11756 case Intrinsic::x86_sse41_pmuldq:
11757 case Intrinsic::x86_avx2_pmul_dq:
11758 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11759 Op.getOperand(1), Op.getOperand(2));
11761 case Intrinsic::x86_sse2_pmulhu_w:
11762 case Intrinsic::x86_avx2_pmulhu_w:
11763 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11764 Op.getOperand(1), Op.getOperand(2));
11766 case Intrinsic::x86_sse2_pmulh_w:
11767 case Intrinsic::x86_avx2_pmulh_w:
11768 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11769 Op.getOperand(1), Op.getOperand(2));
11771 // SSE2/AVX2 sub with unsigned saturation intrinsics
11772 case Intrinsic::x86_sse2_psubus_b:
11773 case Intrinsic::x86_sse2_psubus_w:
11774 case Intrinsic::x86_avx2_psubus_b:
11775 case Intrinsic::x86_avx2_psubus_w:
11776 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11777 Op.getOperand(1), Op.getOperand(2));
11779 // SSE3/AVX horizontal add/sub intrinsics
11780 case Intrinsic::x86_sse3_hadd_ps:
11781 case Intrinsic::x86_sse3_hadd_pd:
11782 case Intrinsic::x86_avx_hadd_ps_256:
11783 case Intrinsic::x86_avx_hadd_pd_256:
11784 case Intrinsic::x86_sse3_hsub_ps:
11785 case Intrinsic::x86_sse3_hsub_pd:
11786 case Intrinsic::x86_avx_hsub_ps_256:
11787 case Intrinsic::x86_avx_hsub_pd_256:
11788 case Intrinsic::x86_ssse3_phadd_w_128:
11789 case Intrinsic::x86_ssse3_phadd_d_128:
11790 case Intrinsic::x86_avx2_phadd_w:
11791 case Intrinsic::x86_avx2_phadd_d:
11792 case Intrinsic::x86_ssse3_phsub_w_128:
11793 case Intrinsic::x86_ssse3_phsub_d_128:
11794 case Intrinsic::x86_avx2_phsub_w:
11795 case Intrinsic::x86_avx2_phsub_d: {
11798 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11799 case Intrinsic::x86_sse3_hadd_ps:
11800 case Intrinsic::x86_sse3_hadd_pd:
11801 case Intrinsic::x86_avx_hadd_ps_256:
11802 case Intrinsic::x86_avx_hadd_pd_256:
11803 Opcode = X86ISD::FHADD;
11805 case Intrinsic::x86_sse3_hsub_ps:
11806 case Intrinsic::x86_sse3_hsub_pd:
11807 case Intrinsic::x86_avx_hsub_ps_256:
11808 case Intrinsic::x86_avx_hsub_pd_256:
11809 Opcode = X86ISD::FHSUB;
11811 case Intrinsic::x86_ssse3_phadd_w_128:
11812 case Intrinsic::x86_ssse3_phadd_d_128:
11813 case Intrinsic::x86_avx2_phadd_w:
11814 case Intrinsic::x86_avx2_phadd_d:
11815 Opcode = X86ISD::HADD;
11817 case Intrinsic::x86_ssse3_phsub_w_128:
11818 case Intrinsic::x86_ssse3_phsub_d_128:
11819 case Intrinsic::x86_avx2_phsub_w:
11820 case Intrinsic::x86_avx2_phsub_d:
11821 Opcode = X86ISD::HSUB;
11824 return DAG.getNode(Opcode, dl, Op.getValueType(),
11825 Op.getOperand(1), Op.getOperand(2));
11828 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11829 case Intrinsic::x86_sse2_pmaxu_b:
11830 case Intrinsic::x86_sse41_pmaxuw:
11831 case Intrinsic::x86_sse41_pmaxud:
11832 case Intrinsic::x86_avx2_pmaxu_b:
11833 case Intrinsic::x86_avx2_pmaxu_w:
11834 case Intrinsic::x86_avx2_pmaxu_d:
11835 case Intrinsic::x86_sse2_pminu_b:
11836 case Intrinsic::x86_sse41_pminuw:
11837 case Intrinsic::x86_sse41_pminud:
11838 case Intrinsic::x86_avx2_pminu_b:
11839 case Intrinsic::x86_avx2_pminu_w:
11840 case Intrinsic::x86_avx2_pminu_d:
11841 case Intrinsic::x86_sse41_pmaxsb:
11842 case Intrinsic::x86_sse2_pmaxs_w:
11843 case Intrinsic::x86_sse41_pmaxsd:
11844 case Intrinsic::x86_avx2_pmaxs_b:
11845 case Intrinsic::x86_avx2_pmaxs_w:
11846 case Intrinsic::x86_avx2_pmaxs_d:
11847 case Intrinsic::x86_sse41_pminsb:
11848 case Intrinsic::x86_sse2_pmins_w:
11849 case Intrinsic::x86_sse41_pminsd:
11850 case Intrinsic::x86_avx2_pmins_b:
11851 case Intrinsic::x86_avx2_pmins_w:
11852 case Intrinsic::x86_avx2_pmins_d: {
11855 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11856 case Intrinsic::x86_sse2_pmaxu_b:
11857 case Intrinsic::x86_sse41_pmaxuw:
11858 case Intrinsic::x86_sse41_pmaxud:
11859 case Intrinsic::x86_avx2_pmaxu_b:
11860 case Intrinsic::x86_avx2_pmaxu_w:
11861 case Intrinsic::x86_avx2_pmaxu_d:
11862 Opcode = X86ISD::UMAX;
11864 case Intrinsic::x86_sse2_pminu_b:
11865 case Intrinsic::x86_sse41_pminuw:
11866 case Intrinsic::x86_sse41_pminud:
11867 case Intrinsic::x86_avx2_pminu_b:
11868 case Intrinsic::x86_avx2_pminu_w:
11869 case Intrinsic::x86_avx2_pminu_d:
11870 Opcode = X86ISD::UMIN;
11872 case Intrinsic::x86_sse41_pmaxsb:
11873 case Intrinsic::x86_sse2_pmaxs_w:
11874 case Intrinsic::x86_sse41_pmaxsd:
11875 case Intrinsic::x86_avx2_pmaxs_b:
11876 case Intrinsic::x86_avx2_pmaxs_w:
11877 case Intrinsic::x86_avx2_pmaxs_d:
11878 Opcode = X86ISD::SMAX;
11880 case Intrinsic::x86_sse41_pminsb:
11881 case Intrinsic::x86_sse2_pmins_w:
11882 case Intrinsic::x86_sse41_pminsd:
11883 case Intrinsic::x86_avx2_pmins_b:
11884 case Intrinsic::x86_avx2_pmins_w:
11885 case Intrinsic::x86_avx2_pmins_d:
11886 Opcode = X86ISD::SMIN;
11889 return DAG.getNode(Opcode, dl, Op.getValueType(),
11890 Op.getOperand(1), Op.getOperand(2));
11893 // SSE/SSE2/AVX floating point max/min intrinsics.
11894 case Intrinsic::x86_sse_max_ps:
11895 case Intrinsic::x86_sse2_max_pd:
11896 case Intrinsic::x86_avx_max_ps_256:
11897 case Intrinsic::x86_avx_max_pd_256:
11898 case Intrinsic::x86_sse_min_ps:
11899 case Intrinsic::x86_sse2_min_pd:
11900 case Intrinsic::x86_avx_min_ps_256:
11901 case Intrinsic::x86_avx_min_pd_256: {
11904 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11905 case Intrinsic::x86_sse_max_ps:
11906 case Intrinsic::x86_sse2_max_pd:
11907 case Intrinsic::x86_avx_max_ps_256:
11908 case Intrinsic::x86_avx_max_pd_256:
11909 Opcode = X86ISD::FMAX;
11911 case Intrinsic::x86_sse_min_ps:
11912 case Intrinsic::x86_sse2_min_pd:
11913 case Intrinsic::x86_avx_min_ps_256:
11914 case Intrinsic::x86_avx_min_pd_256:
11915 Opcode = X86ISD::FMIN;
11918 return DAG.getNode(Opcode, dl, Op.getValueType(),
11919 Op.getOperand(1), Op.getOperand(2));
11922 // AVX2 variable shift intrinsics
11923 case Intrinsic::x86_avx2_psllv_d:
11924 case Intrinsic::x86_avx2_psllv_q:
11925 case Intrinsic::x86_avx2_psllv_d_256:
11926 case Intrinsic::x86_avx2_psllv_q_256:
11927 case Intrinsic::x86_avx2_psrlv_d:
11928 case Intrinsic::x86_avx2_psrlv_q:
11929 case Intrinsic::x86_avx2_psrlv_d_256:
11930 case Intrinsic::x86_avx2_psrlv_q_256:
11931 case Intrinsic::x86_avx2_psrav_d:
11932 case Intrinsic::x86_avx2_psrav_d_256: {
11935 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11936 case Intrinsic::x86_avx2_psllv_d:
11937 case Intrinsic::x86_avx2_psllv_q:
11938 case Intrinsic::x86_avx2_psllv_d_256:
11939 case Intrinsic::x86_avx2_psllv_q_256:
11942 case Intrinsic::x86_avx2_psrlv_d:
11943 case Intrinsic::x86_avx2_psrlv_q:
11944 case Intrinsic::x86_avx2_psrlv_d_256:
11945 case Intrinsic::x86_avx2_psrlv_q_256:
11948 case Intrinsic::x86_avx2_psrav_d:
11949 case Intrinsic::x86_avx2_psrav_d_256:
11953 return DAG.getNode(Opcode, dl, Op.getValueType(),
11954 Op.getOperand(1), Op.getOperand(2));
11957 case Intrinsic::x86_ssse3_pshuf_b_128:
11958 case Intrinsic::x86_avx2_pshuf_b:
11959 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11960 Op.getOperand(1), Op.getOperand(2));
11962 case Intrinsic::x86_ssse3_psign_b_128:
11963 case Intrinsic::x86_ssse3_psign_w_128:
11964 case Intrinsic::x86_ssse3_psign_d_128:
11965 case Intrinsic::x86_avx2_psign_b:
11966 case Intrinsic::x86_avx2_psign_w:
11967 case Intrinsic::x86_avx2_psign_d:
11968 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11969 Op.getOperand(1), Op.getOperand(2));
11971 case Intrinsic::x86_sse41_insertps:
11972 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11973 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11975 case Intrinsic::x86_avx_vperm2f128_ps_256:
11976 case Intrinsic::x86_avx_vperm2f128_pd_256:
11977 case Intrinsic::x86_avx_vperm2f128_si_256:
11978 case Intrinsic::x86_avx2_vperm2i128:
11979 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11980 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11982 case Intrinsic::x86_avx2_permd:
11983 case Intrinsic::x86_avx2_permps:
11984 // Operands intentionally swapped. Mask is last operand to intrinsic,
11985 // but second operand for node/instruction.
11986 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11987 Op.getOperand(2), Op.getOperand(1));
11989 case Intrinsic::x86_sse_sqrt_ps:
11990 case Intrinsic::x86_sse2_sqrt_pd:
11991 case Intrinsic::x86_avx_sqrt_ps_256:
11992 case Intrinsic::x86_avx_sqrt_pd_256:
11993 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11995 // ptest and testp intrinsics. The intrinsic these come from are designed to
11996 // return an integer value, not just an instruction so lower it to the ptest
11997 // or testp pattern and a setcc for the result.
11998 case Intrinsic::x86_sse41_ptestz:
11999 case Intrinsic::x86_sse41_ptestc:
12000 case Intrinsic::x86_sse41_ptestnzc:
12001 case Intrinsic::x86_avx_ptestz_256:
12002 case Intrinsic::x86_avx_ptestc_256:
12003 case Intrinsic::x86_avx_ptestnzc_256:
12004 case Intrinsic::x86_avx_vtestz_ps:
12005 case Intrinsic::x86_avx_vtestc_ps:
12006 case Intrinsic::x86_avx_vtestnzc_ps:
12007 case Intrinsic::x86_avx_vtestz_pd:
12008 case Intrinsic::x86_avx_vtestc_pd:
12009 case Intrinsic::x86_avx_vtestnzc_pd:
12010 case Intrinsic::x86_avx_vtestz_ps_256:
12011 case Intrinsic::x86_avx_vtestc_ps_256:
12012 case Intrinsic::x86_avx_vtestnzc_ps_256:
12013 case Intrinsic::x86_avx_vtestz_pd_256:
12014 case Intrinsic::x86_avx_vtestc_pd_256:
12015 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12016 bool IsTestPacked = false;
12019 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12020 case Intrinsic::x86_avx_vtestz_ps:
12021 case Intrinsic::x86_avx_vtestz_pd:
12022 case Intrinsic::x86_avx_vtestz_ps_256:
12023 case Intrinsic::x86_avx_vtestz_pd_256:
12024 IsTestPacked = true; // Fallthrough
12025 case Intrinsic::x86_sse41_ptestz:
12026 case Intrinsic::x86_avx_ptestz_256:
12028 X86CC = X86::COND_E;
12030 case Intrinsic::x86_avx_vtestc_ps:
12031 case Intrinsic::x86_avx_vtestc_pd:
12032 case Intrinsic::x86_avx_vtestc_ps_256:
12033 case Intrinsic::x86_avx_vtestc_pd_256:
12034 IsTestPacked = true; // Fallthrough
12035 case Intrinsic::x86_sse41_ptestc:
12036 case Intrinsic::x86_avx_ptestc_256:
12038 X86CC = X86::COND_B;
12040 case Intrinsic::x86_avx_vtestnzc_ps:
12041 case Intrinsic::x86_avx_vtestnzc_pd:
12042 case Intrinsic::x86_avx_vtestnzc_ps_256:
12043 case Intrinsic::x86_avx_vtestnzc_pd_256:
12044 IsTestPacked = true; // Fallthrough
12045 case Intrinsic::x86_sse41_ptestnzc:
12046 case Intrinsic::x86_avx_ptestnzc_256:
12048 X86CC = X86::COND_A;
12052 SDValue LHS = Op.getOperand(1);
12053 SDValue RHS = Op.getOperand(2);
12054 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12055 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12056 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12057 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12058 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12060 case Intrinsic::x86_avx512_kortestz_w:
12061 case Intrinsic::x86_avx512_kortestc_w: {
12062 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12063 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12064 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12065 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12066 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12067 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12068 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12071 // SSE/AVX shift intrinsics
12072 case Intrinsic::x86_sse2_psll_w:
12073 case Intrinsic::x86_sse2_psll_d:
12074 case Intrinsic::x86_sse2_psll_q:
12075 case Intrinsic::x86_avx2_psll_w:
12076 case Intrinsic::x86_avx2_psll_d:
12077 case Intrinsic::x86_avx2_psll_q:
12078 case Intrinsic::x86_sse2_psrl_w:
12079 case Intrinsic::x86_sse2_psrl_d:
12080 case Intrinsic::x86_sse2_psrl_q:
12081 case Intrinsic::x86_avx2_psrl_w:
12082 case Intrinsic::x86_avx2_psrl_d:
12083 case Intrinsic::x86_avx2_psrl_q:
12084 case Intrinsic::x86_sse2_psra_w:
12085 case Intrinsic::x86_sse2_psra_d:
12086 case Intrinsic::x86_avx2_psra_w:
12087 case Intrinsic::x86_avx2_psra_d: {
12090 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12091 case Intrinsic::x86_sse2_psll_w:
12092 case Intrinsic::x86_sse2_psll_d:
12093 case Intrinsic::x86_sse2_psll_q:
12094 case Intrinsic::x86_avx2_psll_w:
12095 case Intrinsic::x86_avx2_psll_d:
12096 case Intrinsic::x86_avx2_psll_q:
12097 Opcode = X86ISD::VSHL;
12099 case Intrinsic::x86_sse2_psrl_w:
12100 case Intrinsic::x86_sse2_psrl_d:
12101 case Intrinsic::x86_sse2_psrl_q:
12102 case Intrinsic::x86_avx2_psrl_w:
12103 case Intrinsic::x86_avx2_psrl_d:
12104 case Intrinsic::x86_avx2_psrl_q:
12105 Opcode = X86ISD::VSRL;
12107 case Intrinsic::x86_sse2_psra_w:
12108 case Intrinsic::x86_sse2_psra_d:
12109 case Intrinsic::x86_avx2_psra_w:
12110 case Intrinsic::x86_avx2_psra_d:
12111 Opcode = X86ISD::VSRA;
12114 return DAG.getNode(Opcode, dl, Op.getValueType(),
12115 Op.getOperand(1), Op.getOperand(2));
12118 // SSE/AVX immediate shift intrinsics
12119 case Intrinsic::x86_sse2_pslli_w:
12120 case Intrinsic::x86_sse2_pslli_d:
12121 case Intrinsic::x86_sse2_pslli_q:
12122 case Intrinsic::x86_avx2_pslli_w:
12123 case Intrinsic::x86_avx2_pslli_d:
12124 case Intrinsic::x86_avx2_pslli_q:
12125 case Intrinsic::x86_sse2_psrli_w:
12126 case Intrinsic::x86_sse2_psrli_d:
12127 case Intrinsic::x86_sse2_psrli_q:
12128 case Intrinsic::x86_avx2_psrli_w:
12129 case Intrinsic::x86_avx2_psrli_d:
12130 case Intrinsic::x86_avx2_psrli_q:
12131 case Intrinsic::x86_sse2_psrai_w:
12132 case Intrinsic::x86_sse2_psrai_d:
12133 case Intrinsic::x86_avx2_psrai_w:
12134 case Intrinsic::x86_avx2_psrai_d: {
12137 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12138 case Intrinsic::x86_sse2_pslli_w:
12139 case Intrinsic::x86_sse2_pslli_d:
12140 case Intrinsic::x86_sse2_pslli_q:
12141 case Intrinsic::x86_avx2_pslli_w:
12142 case Intrinsic::x86_avx2_pslli_d:
12143 case Intrinsic::x86_avx2_pslli_q:
12144 Opcode = X86ISD::VSHLI;
12146 case Intrinsic::x86_sse2_psrli_w:
12147 case Intrinsic::x86_sse2_psrli_d:
12148 case Intrinsic::x86_sse2_psrli_q:
12149 case Intrinsic::x86_avx2_psrli_w:
12150 case Intrinsic::x86_avx2_psrli_d:
12151 case Intrinsic::x86_avx2_psrli_q:
12152 Opcode = X86ISD::VSRLI;
12154 case Intrinsic::x86_sse2_psrai_w:
12155 case Intrinsic::x86_sse2_psrai_d:
12156 case Intrinsic::x86_avx2_psrai_w:
12157 case Intrinsic::x86_avx2_psrai_d:
12158 Opcode = X86ISD::VSRAI;
12161 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12162 Op.getOperand(1), Op.getOperand(2), DAG);
12165 case Intrinsic::x86_sse42_pcmpistria128:
12166 case Intrinsic::x86_sse42_pcmpestria128:
12167 case Intrinsic::x86_sse42_pcmpistric128:
12168 case Intrinsic::x86_sse42_pcmpestric128:
12169 case Intrinsic::x86_sse42_pcmpistrio128:
12170 case Intrinsic::x86_sse42_pcmpestrio128:
12171 case Intrinsic::x86_sse42_pcmpistris128:
12172 case Intrinsic::x86_sse42_pcmpestris128:
12173 case Intrinsic::x86_sse42_pcmpistriz128:
12174 case Intrinsic::x86_sse42_pcmpestriz128: {
12178 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12179 case Intrinsic::x86_sse42_pcmpistria128:
12180 Opcode = X86ISD::PCMPISTRI;
12181 X86CC = X86::COND_A;
12183 case Intrinsic::x86_sse42_pcmpestria128:
12184 Opcode = X86ISD::PCMPESTRI;
12185 X86CC = X86::COND_A;
12187 case Intrinsic::x86_sse42_pcmpistric128:
12188 Opcode = X86ISD::PCMPISTRI;
12189 X86CC = X86::COND_B;
12191 case Intrinsic::x86_sse42_pcmpestric128:
12192 Opcode = X86ISD::PCMPESTRI;
12193 X86CC = X86::COND_B;
12195 case Intrinsic::x86_sse42_pcmpistrio128:
12196 Opcode = X86ISD::PCMPISTRI;
12197 X86CC = X86::COND_O;
12199 case Intrinsic::x86_sse42_pcmpestrio128:
12200 Opcode = X86ISD::PCMPESTRI;
12201 X86CC = X86::COND_O;
12203 case Intrinsic::x86_sse42_pcmpistris128:
12204 Opcode = X86ISD::PCMPISTRI;
12205 X86CC = X86::COND_S;
12207 case Intrinsic::x86_sse42_pcmpestris128:
12208 Opcode = X86ISD::PCMPESTRI;
12209 X86CC = X86::COND_S;
12211 case Intrinsic::x86_sse42_pcmpistriz128:
12212 Opcode = X86ISD::PCMPISTRI;
12213 X86CC = X86::COND_E;
12215 case Intrinsic::x86_sse42_pcmpestriz128:
12216 Opcode = X86ISD::PCMPESTRI;
12217 X86CC = X86::COND_E;
12220 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12221 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12222 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12223 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12224 DAG.getConstant(X86CC, MVT::i8),
12225 SDValue(PCMP.getNode(), 1));
12226 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12229 case Intrinsic::x86_sse42_pcmpistri128:
12230 case Intrinsic::x86_sse42_pcmpestri128: {
12232 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12233 Opcode = X86ISD::PCMPISTRI;
12235 Opcode = X86ISD::PCMPESTRI;
12237 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12238 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12239 return DAG.getNode(Opcode, dl, VTs, NewOps);
12241 case Intrinsic::x86_fma_vfmadd_ps:
12242 case Intrinsic::x86_fma_vfmadd_pd:
12243 case Intrinsic::x86_fma_vfmsub_ps:
12244 case Intrinsic::x86_fma_vfmsub_pd:
12245 case Intrinsic::x86_fma_vfnmadd_ps:
12246 case Intrinsic::x86_fma_vfnmadd_pd:
12247 case Intrinsic::x86_fma_vfnmsub_ps:
12248 case Intrinsic::x86_fma_vfnmsub_pd:
12249 case Intrinsic::x86_fma_vfmaddsub_ps:
12250 case Intrinsic::x86_fma_vfmaddsub_pd:
12251 case Intrinsic::x86_fma_vfmsubadd_ps:
12252 case Intrinsic::x86_fma_vfmsubadd_pd:
12253 case Intrinsic::x86_fma_vfmadd_ps_256:
12254 case Intrinsic::x86_fma_vfmadd_pd_256:
12255 case Intrinsic::x86_fma_vfmsub_ps_256:
12256 case Intrinsic::x86_fma_vfmsub_pd_256:
12257 case Intrinsic::x86_fma_vfnmadd_ps_256:
12258 case Intrinsic::x86_fma_vfnmadd_pd_256:
12259 case Intrinsic::x86_fma_vfnmsub_ps_256:
12260 case Intrinsic::x86_fma_vfnmsub_pd_256:
12261 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12262 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12263 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12264 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12265 case Intrinsic::x86_fma_vfmadd_ps_512:
12266 case Intrinsic::x86_fma_vfmadd_pd_512:
12267 case Intrinsic::x86_fma_vfmsub_ps_512:
12268 case Intrinsic::x86_fma_vfmsub_pd_512:
12269 case Intrinsic::x86_fma_vfnmadd_ps_512:
12270 case Intrinsic::x86_fma_vfnmadd_pd_512:
12271 case Intrinsic::x86_fma_vfnmsub_ps_512:
12272 case Intrinsic::x86_fma_vfnmsub_pd_512:
12273 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12274 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12275 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12276 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12279 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12280 case Intrinsic::x86_fma_vfmadd_ps:
12281 case Intrinsic::x86_fma_vfmadd_pd:
12282 case Intrinsic::x86_fma_vfmadd_ps_256:
12283 case Intrinsic::x86_fma_vfmadd_pd_256:
12284 case Intrinsic::x86_fma_vfmadd_ps_512:
12285 case Intrinsic::x86_fma_vfmadd_pd_512:
12286 Opc = X86ISD::FMADD;
12288 case Intrinsic::x86_fma_vfmsub_ps:
12289 case Intrinsic::x86_fma_vfmsub_pd:
12290 case Intrinsic::x86_fma_vfmsub_ps_256:
12291 case Intrinsic::x86_fma_vfmsub_pd_256:
12292 case Intrinsic::x86_fma_vfmsub_ps_512:
12293 case Intrinsic::x86_fma_vfmsub_pd_512:
12294 Opc = X86ISD::FMSUB;
12296 case Intrinsic::x86_fma_vfnmadd_ps:
12297 case Intrinsic::x86_fma_vfnmadd_pd:
12298 case Intrinsic::x86_fma_vfnmadd_ps_256:
12299 case Intrinsic::x86_fma_vfnmadd_pd_256:
12300 case Intrinsic::x86_fma_vfnmadd_ps_512:
12301 case Intrinsic::x86_fma_vfnmadd_pd_512:
12302 Opc = X86ISD::FNMADD;
12304 case Intrinsic::x86_fma_vfnmsub_ps:
12305 case Intrinsic::x86_fma_vfnmsub_pd:
12306 case Intrinsic::x86_fma_vfnmsub_ps_256:
12307 case Intrinsic::x86_fma_vfnmsub_pd_256:
12308 case Intrinsic::x86_fma_vfnmsub_ps_512:
12309 case Intrinsic::x86_fma_vfnmsub_pd_512:
12310 Opc = X86ISD::FNMSUB;
12312 case Intrinsic::x86_fma_vfmaddsub_ps:
12313 case Intrinsic::x86_fma_vfmaddsub_pd:
12314 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12315 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12316 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12317 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12318 Opc = X86ISD::FMADDSUB;
12320 case Intrinsic::x86_fma_vfmsubadd_ps:
12321 case Intrinsic::x86_fma_vfmsubadd_pd:
12322 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12323 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12324 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12325 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12326 Opc = X86ISD::FMSUBADD;
12330 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12331 Op.getOperand(2), Op.getOperand(3));
12336 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12337 SDValue Base, SDValue Index,
12338 SDValue ScaleOp, SDValue Chain,
12339 const X86Subtarget * Subtarget) {
12341 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12342 assert(C && "Invalid scale type");
12343 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12344 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12345 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12346 Index.getSimpleValueType().getVectorNumElements());
12347 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12348 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12349 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12350 SDValue Segment = DAG.getRegister(0, MVT::i32);
12351 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12352 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12353 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12354 return DAG.getMergeValues(RetOps, dl);
12357 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12358 SDValue Src, SDValue Mask, SDValue Base,
12359 SDValue Index, SDValue ScaleOp, SDValue Chain,
12360 const X86Subtarget * Subtarget) {
12362 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12363 assert(C && "Invalid scale type");
12364 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12365 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12366 Index.getSimpleValueType().getVectorNumElements());
12367 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12368 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12369 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12370 SDValue Segment = DAG.getRegister(0, MVT::i32);
12371 if (Src.getOpcode() == ISD::UNDEF)
12372 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12373 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12374 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12375 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12376 return DAG.getMergeValues(RetOps, dl);
12379 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12380 SDValue Src, SDValue Base, SDValue Index,
12381 SDValue ScaleOp, SDValue Chain) {
12383 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12384 assert(C && "Invalid scale type");
12385 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12386 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12387 SDValue Segment = DAG.getRegister(0, MVT::i32);
12388 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12389 Index.getSimpleValueType().getVectorNumElements());
12390 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12391 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12392 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12393 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12394 return SDValue(Res, 1);
12397 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12398 SDValue Src, SDValue Mask, SDValue Base,
12399 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12401 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12402 assert(C && "Invalid scale type");
12403 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12404 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12405 SDValue Segment = DAG.getRegister(0, MVT::i32);
12406 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12407 Index.getSimpleValueType().getVectorNumElements());
12408 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12409 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12410 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12411 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12412 return SDValue(Res, 1);
12415 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12416 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12417 // also used to custom lower READCYCLECOUNTER nodes.
12418 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12419 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12420 SmallVectorImpl<SDValue> &Results) {
12421 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12422 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12425 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12426 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12427 // and the EAX register is loaded with the low-order 32 bits.
12428 if (Subtarget->is64Bit()) {
12429 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12430 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12433 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12434 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12437 SDValue Chain = HI.getValue(1);
12439 if (Opcode == X86ISD::RDTSCP_DAG) {
12440 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12442 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12443 // the ECX register. Add 'ecx' explicitly to the chain.
12444 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12446 // Explicitly store the content of ECX at the location passed in input
12447 // to the 'rdtscp' intrinsic.
12448 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12449 MachinePointerInfo(), false, false, 0);
12452 if (Subtarget->is64Bit()) {
12453 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12454 // the EAX register is loaded with the low-order 32 bits.
12455 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12456 DAG.getConstant(32, MVT::i8));
12457 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12458 Results.push_back(Chain);
12462 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12463 SDValue Ops[] = { LO, HI };
12464 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12465 Results.push_back(Pair);
12466 Results.push_back(Chain);
12469 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12470 SelectionDAG &DAG) {
12471 SmallVector<SDValue, 2> Results;
12473 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12475 return DAG.getMergeValues(Results, DL);
12478 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12479 SelectionDAG &DAG) {
12481 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12483 default: return SDValue(); // Don't custom lower most intrinsics.
12485 // RDRAND/RDSEED intrinsics.
12486 case Intrinsic::x86_rdrand_16:
12487 case Intrinsic::x86_rdrand_32:
12488 case Intrinsic::x86_rdrand_64:
12489 case Intrinsic::x86_rdseed_16:
12490 case Intrinsic::x86_rdseed_32:
12491 case Intrinsic::x86_rdseed_64: {
12492 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12493 IntNo == Intrinsic::x86_rdseed_32 ||
12494 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12496 // Emit the node with the right value type.
12497 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12498 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12500 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12501 // Otherwise return the value from Rand, which is always 0, casted to i32.
12502 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12503 DAG.getConstant(1, Op->getValueType(1)),
12504 DAG.getConstant(X86::COND_B, MVT::i32),
12505 SDValue(Result.getNode(), 1) };
12506 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12507 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12510 // Return { result, isValid, chain }.
12511 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12512 SDValue(Result.getNode(), 2));
12514 //int_gather(index, base, scale);
12515 case Intrinsic::x86_avx512_gather_qpd_512:
12516 case Intrinsic::x86_avx512_gather_qps_512:
12517 case Intrinsic::x86_avx512_gather_dpd_512:
12518 case Intrinsic::x86_avx512_gather_qpi_512:
12519 case Intrinsic::x86_avx512_gather_qpq_512:
12520 case Intrinsic::x86_avx512_gather_dpq_512:
12521 case Intrinsic::x86_avx512_gather_dps_512:
12522 case Intrinsic::x86_avx512_gather_dpi_512: {
12525 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12526 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12527 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12528 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12529 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12530 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12531 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12532 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12533 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12535 SDValue Chain = Op.getOperand(0);
12536 SDValue Index = Op.getOperand(2);
12537 SDValue Base = Op.getOperand(3);
12538 SDValue Scale = Op.getOperand(4);
12539 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12541 //int_gather_mask(v1, mask, index, base, scale);
12542 case Intrinsic::x86_avx512_gather_qps_mask_512:
12543 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12544 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12545 case Intrinsic::x86_avx512_gather_dps_mask_512:
12546 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12547 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12548 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12549 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12552 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12553 case Intrinsic::x86_avx512_gather_qps_mask_512:
12554 Opc = X86::VGATHERQPSZrm; break;
12555 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12556 Opc = X86::VGATHERQPDZrm; break;
12557 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12558 Opc = X86::VGATHERDPDZrm; break;
12559 case Intrinsic::x86_avx512_gather_dps_mask_512:
12560 Opc = X86::VGATHERDPSZrm; break;
12561 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12562 Opc = X86::VPGATHERQDZrm; break;
12563 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12564 Opc = X86::VPGATHERQQZrm; break;
12565 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12566 Opc = X86::VPGATHERDDZrm; break;
12567 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12568 Opc = X86::VPGATHERDQZrm; break;
12570 SDValue Chain = Op.getOperand(0);
12571 SDValue Src = Op.getOperand(2);
12572 SDValue Mask = Op.getOperand(3);
12573 SDValue Index = Op.getOperand(4);
12574 SDValue Base = Op.getOperand(5);
12575 SDValue Scale = Op.getOperand(6);
12576 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12579 //int_scatter(base, index, v1, scale);
12580 case Intrinsic::x86_avx512_scatter_qpd_512:
12581 case Intrinsic::x86_avx512_scatter_qps_512:
12582 case Intrinsic::x86_avx512_scatter_dpd_512:
12583 case Intrinsic::x86_avx512_scatter_qpi_512:
12584 case Intrinsic::x86_avx512_scatter_qpq_512:
12585 case Intrinsic::x86_avx512_scatter_dpq_512:
12586 case Intrinsic::x86_avx512_scatter_dps_512:
12587 case Intrinsic::x86_avx512_scatter_dpi_512: {
12590 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12591 case Intrinsic::x86_avx512_scatter_qpd_512:
12592 Opc = X86::VSCATTERQPDZmr; break;
12593 case Intrinsic::x86_avx512_scatter_qps_512:
12594 Opc = X86::VSCATTERQPSZmr; break;
12595 case Intrinsic::x86_avx512_scatter_dpd_512:
12596 Opc = X86::VSCATTERDPDZmr; break;
12597 case Intrinsic::x86_avx512_scatter_dps_512:
12598 Opc = X86::VSCATTERDPSZmr; break;
12599 case Intrinsic::x86_avx512_scatter_qpi_512:
12600 Opc = X86::VPSCATTERQDZmr; break;
12601 case Intrinsic::x86_avx512_scatter_qpq_512:
12602 Opc = X86::VPSCATTERQQZmr; break;
12603 case Intrinsic::x86_avx512_scatter_dpq_512:
12604 Opc = X86::VPSCATTERDQZmr; break;
12605 case Intrinsic::x86_avx512_scatter_dpi_512:
12606 Opc = X86::VPSCATTERDDZmr; break;
12608 SDValue Chain = Op.getOperand(0);
12609 SDValue Base = Op.getOperand(2);
12610 SDValue Index = Op.getOperand(3);
12611 SDValue Src = Op.getOperand(4);
12612 SDValue Scale = Op.getOperand(5);
12613 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12615 //int_scatter_mask(base, mask, index, v1, scale);
12616 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12617 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12618 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12619 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12620 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12621 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12622 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12623 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12626 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12627 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12628 Opc = X86::VSCATTERQPDZmr; break;
12629 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12630 Opc = X86::VSCATTERQPSZmr; break;
12631 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12632 Opc = X86::VSCATTERDPDZmr; break;
12633 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12634 Opc = X86::VSCATTERDPSZmr; break;
12635 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12636 Opc = X86::VPSCATTERQDZmr; break;
12637 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12638 Opc = X86::VPSCATTERQQZmr; break;
12639 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12640 Opc = X86::VPSCATTERDQZmr; break;
12641 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12642 Opc = X86::VPSCATTERDDZmr; break;
12644 SDValue Chain = Op.getOperand(0);
12645 SDValue Base = Op.getOperand(2);
12646 SDValue Mask = Op.getOperand(3);
12647 SDValue Index = Op.getOperand(4);
12648 SDValue Src = Op.getOperand(5);
12649 SDValue Scale = Op.getOperand(6);
12650 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12652 // Read Time Stamp Counter (RDTSC).
12653 case Intrinsic::x86_rdtsc:
12654 // Read Time Stamp Counter and Processor ID (RDTSCP).
12655 case Intrinsic::x86_rdtscp: {
12658 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12659 case Intrinsic::x86_rdtsc:
12660 Opc = X86ISD::RDTSC_DAG; break;
12661 case Intrinsic::x86_rdtscp:
12662 Opc = X86ISD::RDTSCP_DAG; break;
12664 SmallVector<SDValue, 2> Results;
12665 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12666 return DAG.getMergeValues(Results, dl);
12668 // XTEST intrinsics.
12669 case Intrinsic::x86_xtest: {
12670 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12671 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12672 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12673 DAG.getConstant(X86::COND_NE, MVT::i8),
12675 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12676 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12677 Ret, SDValue(InTrans.getNode(), 1));
12682 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12683 SelectionDAG &DAG) const {
12684 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12685 MFI->setReturnAddressIsTaken(true);
12687 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12690 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12692 EVT PtrVT = getPointerTy();
12695 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12696 const X86RegisterInfo *RegInfo =
12697 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12698 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12699 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12700 DAG.getNode(ISD::ADD, dl, PtrVT,
12701 FrameAddr, Offset),
12702 MachinePointerInfo(), false, false, false, 0);
12705 // Just load the return address.
12706 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12707 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12708 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12711 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12712 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12713 MFI->setFrameAddressIsTaken(true);
12715 EVT VT = Op.getValueType();
12716 SDLoc dl(Op); // FIXME probably not meaningful
12717 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12718 const X86RegisterInfo *RegInfo =
12719 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12720 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12721 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12722 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12723 "Invalid Frame Register!");
12724 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12726 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12727 MachinePointerInfo(),
12728 false, false, false, 0);
12732 // FIXME? Maybe this could be a TableGen attribute on some registers and
12733 // this table could be generated automatically from RegInfo.
12734 unsigned X86TargetLowering::getRegisterByName(const char* RegName) const {
12735 unsigned Reg = StringSwitch<unsigned>(RegName)
12736 .Case("esp", X86::ESP)
12737 .Case("rsp", X86::RSP)
12741 report_fatal_error("Invalid register name global variable");
12744 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12745 SelectionDAG &DAG) const {
12746 const X86RegisterInfo *RegInfo =
12747 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12748 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12751 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12752 SDValue Chain = Op.getOperand(0);
12753 SDValue Offset = Op.getOperand(1);
12754 SDValue Handler = Op.getOperand(2);
12757 EVT PtrVT = getPointerTy();
12758 const X86RegisterInfo *RegInfo =
12759 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12760 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12761 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12762 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12763 "Invalid Frame Register!");
12764 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12765 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12767 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12768 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12769 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12770 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12772 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12774 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12775 DAG.getRegister(StoreAddrReg, PtrVT));
12778 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12779 SelectionDAG &DAG) const {
12781 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12782 DAG.getVTList(MVT::i32, MVT::Other),
12783 Op.getOperand(0), Op.getOperand(1));
12786 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12787 SelectionDAG &DAG) const {
12789 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12790 Op.getOperand(0), Op.getOperand(1));
12793 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12794 return Op.getOperand(0);
12797 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12798 SelectionDAG &DAG) const {
12799 SDValue Root = Op.getOperand(0);
12800 SDValue Trmp = Op.getOperand(1); // trampoline
12801 SDValue FPtr = Op.getOperand(2); // nested function
12802 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12805 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12806 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12808 if (Subtarget->is64Bit()) {
12809 SDValue OutChains[6];
12811 // Large code-model.
12812 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12813 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12815 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12816 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12818 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12820 // Load the pointer to the nested function into R11.
12821 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12822 SDValue Addr = Trmp;
12823 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12824 Addr, MachinePointerInfo(TrmpAddr),
12827 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12828 DAG.getConstant(2, MVT::i64));
12829 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12830 MachinePointerInfo(TrmpAddr, 2),
12833 // Load the 'nest' parameter value into R10.
12834 // R10 is specified in X86CallingConv.td
12835 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12836 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12837 DAG.getConstant(10, MVT::i64));
12838 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12839 Addr, MachinePointerInfo(TrmpAddr, 10),
12842 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12843 DAG.getConstant(12, MVT::i64));
12844 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12845 MachinePointerInfo(TrmpAddr, 12),
12848 // Jump to the nested function.
12849 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12850 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12851 DAG.getConstant(20, MVT::i64));
12852 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12853 Addr, MachinePointerInfo(TrmpAddr, 20),
12856 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12857 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12858 DAG.getConstant(22, MVT::i64));
12859 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12860 MachinePointerInfo(TrmpAddr, 22),
12863 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12865 const Function *Func =
12866 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12867 CallingConv::ID CC = Func->getCallingConv();
12872 llvm_unreachable("Unsupported calling convention");
12873 case CallingConv::C:
12874 case CallingConv::X86_StdCall: {
12875 // Pass 'nest' parameter in ECX.
12876 // Must be kept in sync with X86CallingConv.td
12877 NestReg = X86::ECX;
12879 // Check that ECX wasn't needed by an 'inreg' parameter.
12880 FunctionType *FTy = Func->getFunctionType();
12881 const AttributeSet &Attrs = Func->getAttributes();
12883 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12884 unsigned InRegCount = 0;
12887 for (FunctionType::param_iterator I = FTy->param_begin(),
12888 E = FTy->param_end(); I != E; ++I, ++Idx)
12889 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12890 // FIXME: should only count parameters that are lowered to integers.
12891 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12893 if (InRegCount > 2) {
12894 report_fatal_error("Nest register in use - reduce number of inreg"
12900 case CallingConv::X86_FastCall:
12901 case CallingConv::X86_ThisCall:
12902 case CallingConv::Fast:
12903 // Pass 'nest' parameter in EAX.
12904 // Must be kept in sync with X86CallingConv.td
12905 NestReg = X86::EAX;
12909 SDValue OutChains[4];
12910 SDValue Addr, Disp;
12912 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12913 DAG.getConstant(10, MVT::i32));
12914 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12916 // This is storing the opcode for MOV32ri.
12917 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12918 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12919 OutChains[0] = DAG.getStore(Root, dl,
12920 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12921 Trmp, MachinePointerInfo(TrmpAddr),
12924 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12925 DAG.getConstant(1, MVT::i32));
12926 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12927 MachinePointerInfo(TrmpAddr, 1),
12930 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12931 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12932 DAG.getConstant(5, MVT::i32));
12933 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12934 MachinePointerInfo(TrmpAddr, 5),
12937 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12938 DAG.getConstant(6, MVT::i32));
12939 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12940 MachinePointerInfo(TrmpAddr, 6),
12943 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12947 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12948 SelectionDAG &DAG) const {
12950 The rounding mode is in bits 11:10 of FPSR, and has the following
12952 00 Round to nearest
12957 FLT_ROUNDS, on the other hand, expects the following:
12964 To perform the conversion, we do:
12965 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12968 MachineFunction &MF = DAG.getMachineFunction();
12969 const TargetMachine &TM = MF.getTarget();
12970 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12971 unsigned StackAlignment = TFI.getStackAlignment();
12972 MVT VT = Op.getSimpleValueType();
12975 // Save FP Control Word to stack slot
12976 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12977 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12979 MachineMemOperand *MMO =
12980 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12981 MachineMemOperand::MOStore, 2, 2);
12983 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12984 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12985 DAG.getVTList(MVT::Other),
12986 Ops, MVT::i16, MMO);
12988 // Load FP Control Word from stack slot
12989 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12990 MachinePointerInfo(), false, false, false, 0);
12992 // Transform as necessary
12994 DAG.getNode(ISD::SRL, DL, MVT::i16,
12995 DAG.getNode(ISD::AND, DL, MVT::i16,
12996 CWD, DAG.getConstant(0x800, MVT::i16)),
12997 DAG.getConstant(11, MVT::i8));
12999 DAG.getNode(ISD::SRL, DL, MVT::i16,
13000 DAG.getNode(ISD::AND, DL, MVT::i16,
13001 CWD, DAG.getConstant(0x400, MVT::i16)),
13002 DAG.getConstant(9, MVT::i8));
13005 DAG.getNode(ISD::AND, DL, MVT::i16,
13006 DAG.getNode(ISD::ADD, DL, MVT::i16,
13007 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13008 DAG.getConstant(1, MVT::i16)),
13009 DAG.getConstant(3, MVT::i16));
13011 return DAG.getNode((VT.getSizeInBits() < 16 ?
13012 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13015 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13016 MVT VT = Op.getSimpleValueType();
13018 unsigned NumBits = VT.getSizeInBits();
13021 Op = Op.getOperand(0);
13022 if (VT == MVT::i8) {
13023 // Zero extend to i32 since there is not an i8 bsr.
13025 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13028 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13029 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13030 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13032 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13035 DAG.getConstant(NumBits+NumBits-1, OpVT),
13036 DAG.getConstant(X86::COND_E, MVT::i8),
13039 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13041 // Finally xor with NumBits-1.
13042 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13045 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13049 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13050 MVT VT = Op.getSimpleValueType();
13052 unsigned NumBits = VT.getSizeInBits();
13055 Op = Op.getOperand(0);
13056 if (VT == MVT::i8) {
13057 // Zero extend to i32 since there is not an i8 bsr.
13059 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13062 // Issue a bsr (scan bits in reverse).
13063 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13064 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13066 // And xor with NumBits-1.
13067 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13070 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13074 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13075 MVT VT = Op.getSimpleValueType();
13076 unsigned NumBits = VT.getSizeInBits();
13078 Op = Op.getOperand(0);
13080 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13081 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13082 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13084 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13087 DAG.getConstant(NumBits, VT),
13088 DAG.getConstant(X86::COND_E, MVT::i8),
13091 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13094 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13095 // ones, and then concatenate the result back.
13096 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13097 MVT VT = Op.getSimpleValueType();
13099 assert(VT.is256BitVector() && VT.isInteger() &&
13100 "Unsupported value type for operation");
13102 unsigned NumElems = VT.getVectorNumElements();
13105 // Extract the LHS vectors
13106 SDValue LHS = Op.getOperand(0);
13107 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13108 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13110 // Extract the RHS vectors
13111 SDValue RHS = Op.getOperand(1);
13112 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13113 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13115 MVT EltVT = VT.getVectorElementType();
13116 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13118 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13119 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13120 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13123 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13124 assert(Op.getSimpleValueType().is256BitVector() &&
13125 Op.getSimpleValueType().isInteger() &&
13126 "Only handle AVX 256-bit vector integer operation");
13127 return Lower256IntArith(Op, DAG);
13130 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13131 assert(Op.getSimpleValueType().is256BitVector() &&
13132 Op.getSimpleValueType().isInteger() &&
13133 "Only handle AVX 256-bit vector integer operation");
13134 return Lower256IntArith(Op, DAG);
13137 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13138 SelectionDAG &DAG) {
13140 MVT VT = Op.getSimpleValueType();
13142 // Decompose 256-bit ops into smaller 128-bit ops.
13143 if (VT.is256BitVector() && !Subtarget->hasInt256())
13144 return Lower256IntArith(Op, DAG);
13146 SDValue A = Op.getOperand(0);
13147 SDValue B = Op.getOperand(1);
13149 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13150 if (VT == MVT::v4i32) {
13151 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13152 "Should not custom lower when pmuldq is available!");
13154 // Extract the odd parts.
13155 static const int UnpackMask[] = { 1, -1, 3, -1 };
13156 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13157 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13159 // Multiply the even parts.
13160 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13161 // Now multiply odd parts.
13162 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13164 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13165 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13167 // Merge the two vectors back together with a shuffle. This expands into 2
13169 static const int ShufMask[] = { 0, 4, 2, 6 };
13170 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13173 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13174 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13176 // Ahi = psrlqi(a, 32);
13177 // Bhi = psrlqi(b, 32);
13179 // AloBlo = pmuludq(a, b);
13180 // AloBhi = pmuludq(a, Bhi);
13181 // AhiBlo = pmuludq(Ahi, b);
13183 // AloBhi = psllqi(AloBhi, 32);
13184 // AhiBlo = psllqi(AhiBlo, 32);
13185 // return AloBlo + AloBhi + AhiBlo;
13187 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13188 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13190 // Bit cast to 32-bit vectors for MULUDQ
13191 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13192 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13193 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13194 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13195 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13196 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13198 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13199 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13200 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13202 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13203 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13205 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13206 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13209 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13210 assert(Subtarget->isTargetWin64() && "Unexpected target");
13211 EVT VT = Op.getValueType();
13212 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13213 "Unexpected return type for lowering");
13217 switch (Op->getOpcode()) {
13218 default: llvm_unreachable("Unexpected request for libcall!");
13219 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13220 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13221 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13222 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13223 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13224 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13228 SDValue InChain = DAG.getEntryNode();
13230 TargetLowering::ArgListTy Args;
13231 TargetLowering::ArgListEntry Entry;
13232 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13233 EVT ArgVT = Op->getOperand(i).getValueType();
13234 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13235 "Unexpected argument type for lowering");
13236 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13237 Entry.Node = StackPtr;
13238 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13240 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13241 Entry.Ty = PointerType::get(ArgTy,0);
13242 Entry.isSExt = false;
13243 Entry.isZExt = false;
13244 Args.push_back(Entry);
13247 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13250 TargetLowering::CallLoweringInfo CLI(
13251 InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13252 isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13253 /*isTailCall=*/false,
13254 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13256 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13258 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13261 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13262 SelectionDAG &DAG) {
13263 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13264 EVT VT = Op0.getValueType();
13267 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13268 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13270 // Get the high parts.
13271 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13272 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13273 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13275 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13277 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13278 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13280 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13281 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13282 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13283 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13284 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13286 // Shuffle it back into the right order.
13287 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13288 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13289 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13290 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13292 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13293 // unsigned multiply.
13294 if (IsSigned && !Subtarget->hasSSE41()) {
13296 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13297 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13298 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13299 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13300 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13302 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13303 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13306 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13309 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13310 const X86Subtarget *Subtarget) {
13311 MVT VT = Op.getSimpleValueType();
13313 SDValue R = Op.getOperand(0);
13314 SDValue Amt = Op.getOperand(1);
13316 // Optimize shl/srl/sra with constant shift amount.
13317 if (isSplatVector(Amt.getNode())) {
13318 SDValue SclrAmt = Amt->getOperand(0);
13319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13320 uint64_t ShiftAmt = C->getZExtValue();
13322 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13323 (Subtarget->hasInt256() &&
13324 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13325 (Subtarget->hasAVX512() &&
13326 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13327 if (Op.getOpcode() == ISD::SHL)
13328 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13330 if (Op.getOpcode() == ISD::SRL)
13331 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13333 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13334 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13338 if (VT == MVT::v16i8) {
13339 if (Op.getOpcode() == ISD::SHL) {
13340 // Make a large shift.
13341 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13342 MVT::v8i16, R, ShiftAmt,
13344 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13345 // Zero out the rightmost bits.
13346 SmallVector<SDValue, 16> V(16,
13347 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13349 return DAG.getNode(ISD::AND, dl, VT, SHL,
13350 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13352 if (Op.getOpcode() == ISD::SRL) {
13353 // Make a large shift.
13354 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13355 MVT::v8i16, R, ShiftAmt,
13357 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13358 // Zero out the leftmost bits.
13359 SmallVector<SDValue, 16> V(16,
13360 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13362 return DAG.getNode(ISD::AND, dl, VT, SRL,
13363 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13365 if (Op.getOpcode() == ISD::SRA) {
13366 if (ShiftAmt == 7) {
13367 // R s>> 7 === R s< 0
13368 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13369 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13372 // R s>> a === ((R u>> a) ^ m) - m
13373 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13374 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13376 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13377 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13378 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13381 llvm_unreachable("Unknown shift opcode.");
13384 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13385 if (Op.getOpcode() == ISD::SHL) {
13386 // Make a large shift.
13387 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13388 MVT::v16i16, R, ShiftAmt,
13390 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13391 // Zero out the rightmost bits.
13392 SmallVector<SDValue, 32> V(32,
13393 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13395 return DAG.getNode(ISD::AND, dl, VT, SHL,
13396 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13398 if (Op.getOpcode() == ISD::SRL) {
13399 // Make a large shift.
13400 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13401 MVT::v16i16, R, ShiftAmt,
13403 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13404 // Zero out the leftmost bits.
13405 SmallVector<SDValue, 32> V(32,
13406 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13408 return DAG.getNode(ISD::AND, dl, VT, SRL,
13409 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13411 if (Op.getOpcode() == ISD::SRA) {
13412 if (ShiftAmt == 7) {
13413 // R s>> 7 === R s< 0
13414 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13415 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13418 // R s>> a === ((R u>> a) ^ m) - m
13419 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13420 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13422 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13423 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13424 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13427 llvm_unreachable("Unknown shift opcode.");
13432 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13433 if (!Subtarget->is64Bit() &&
13434 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13435 Amt.getOpcode() == ISD::BITCAST &&
13436 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13437 Amt = Amt.getOperand(0);
13438 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13439 VT.getVectorNumElements();
13440 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13441 uint64_t ShiftAmt = 0;
13442 for (unsigned i = 0; i != Ratio; ++i) {
13443 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13447 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13449 // Check remaining shift amounts.
13450 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13451 uint64_t ShAmt = 0;
13452 for (unsigned j = 0; j != Ratio; ++j) {
13453 ConstantSDNode *C =
13454 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13458 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13460 if (ShAmt != ShiftAmt)
13463 switch (Op.getOpcode()) {
13465 llvm_unreachable("Unknown shift opcode!");
13467 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13470 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13473 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13481 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13482 const X86Subtarget* Subtarget) {
13483 MVT VT = Op.getSimpleValueType();
13485 SDValue R = Op.getOperand(0);
13486 SDValue Amt = Op.getOperand(1);
13488 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13489 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13490 (Subtarget->hasInt256() &&
13491 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13492 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13493 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13495 EVT EltVT = VT.getVectorElementType();
13497 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13498 unsigned NumElts = VT.getVectorNumElements();
13500 for (i = 0; i != NumElts; ++i) {
13501 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13505 for (j = i; j != NumElts; ++j) {
13506 SDValue Arg = Amt.getOperand(j);
13507 if (Arg.getOpcode() == ISD::UNDEF) continue;
13508 if (Arg != Amt.getOperand(i))
13511 if (i != NumElts && j == NumElts)
13512 BaseShAmt = Amt.getOperand(i);
13514 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13515 Amt = Amt.getOperand(0);
13516 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13517 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13518 SDValue InVec = Amt.getOperand(0);
13519 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13520 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13522 for (; i != NumElts; ++i) {
13523 SDValue Arg = InVec.getOperand(i);
13524 if (Arg.getOpcode() == ISD::UNDEF) continue;
13528 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13529 if (ConstantSDNode *C =
13530 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13531 unsigned SplatIdx =
13532 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13533 if (C->getZExtValue() == SplatIdx)
13534 BaseShAmt = InVec.getOperand(1);
13537 if (!BaseShAmt.getNode())
13538 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13539 DAG.getIntPtrConstant(0));
13543 if (BaseShAmt.getNode()) {
13544 if (EltVT.bitsGT(MVT::i32))
13545 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13546 else if (EltVT.bitsLT(MVT::i32))
13547 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13549 switch (Op.getOpcode()) {
13551 llvm_unreachable("Unknown shift opcode!");
13553 switch (VT.SimpleTy) {
13554 default: return SDValue();
13563 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13566 switch (VT.SimpleTy) {
13567 default: return SDValue();
13574 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13577 switch (VT.SimpleTy) {
13578 default: return SDValue();
13587 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13593 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13594 if (!Subtarget->is64Bit() &&
13595 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13596 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13597 Amt.getOpcode() == ISD::BITCAST &&
13598 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13599 Amt = Amt.getOperand(0);
13600 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13601 VT.getVectorNumElements();
13602 std::vector<SDValue> Vals(Ratio);
13603 for (unsigned i = 0; i != Ratio; ++i)
13604 Vals[i] = Amt.getOperand(i);
13605 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13606 for (unsigned j = 0; j != Ratio; ++j)
13607 if (Vals[j] != Amt.getOperand(i + j))
13610 switch (Op.getOpcode()) {
13612 llvm_unreachable("Unknown shift opcode!");
13614 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13616 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13618 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13625 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13626 SelectionDAG &DAG) {
13628 MVT VT = Op.getSimpleValueType();
13630 SDValue R = Op.getOperand(0);
13631 SDValue Amt = Op.getOperand(1);
13634 if (!Subtarget->hasSSE2())
13637 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13641 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13645 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13647 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13648 if (Subtarget->hasInt256()) {
13649 if (Op.getOpcode() == ISD::SRL &&
13650 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13651 VT == MVT::v4i64 || VT == MVT::v8i32))
13653 if (Op.getOpcode() == ISD::SHL &&
13654 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13655 VT == MVT::v4i64 || VT == MVT::v8i32))
13657 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13661 // If possible, lower this packed shift into a vector multiply instead of
13662 // expanding it into a sequence of scalar shifts.
13663 // Do this only if the vector shift count is a constant build_vector.
13664 if (Op.getOpcode() == ISD::SHL &&
13665 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13666 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13667 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13668 SmallVector<SDValue, 8> Elts;
13669 EVT SVT = VT.getScalarType();
13670 unsigned SVTBits = SVT.getSizeInBits();
13671 const APInt &One = APInt(SVTBits, 1);
13672 unsigned NumElems = VT.getVectorNumElements();
13674 for (unsigned i=0; i !=NumElems; ++i) {
13675 SDValue Op = Amt->getOperand(i);
13676 if (Op->getOpcode() == ISD::UNDEF) {
13677 Elts.push_back(Op);
13681 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13682 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13683 uint64_t ShAmt = C.getZExtValue();
13684 if (ShAmt >= SVTBits) {
13685 Elts.push_back(DAG.getUNDEF(SVT));
13688 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13690 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13691 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13694 // Lower SHL with variable shift amount.
13695 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13696 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13698 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13699 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13700 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13701 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13704 // If possible, lower this shift as a sequence of two shifts by
13705 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13707 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13709 // Could be rewritten as:
13710 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13712 // The advantage is that the two shifts from the example would be
13713 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13714 // the vector shift into four scalar shifts plus four pairs of vector
13716 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13717 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13718 unsigned TargetOpcode = X86ISD::MOVSS;
13719 bool CanBeSimplified;
13720 // The splat value for the first packed shift (the 'X' from the example).
13721 SDValue Amt1 = Amt->getOperand(0);
13722 // The splat value for the second packed shift (the 'Y' from the example).
13723 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13724 Amt->getOperand(2);
13726 // See if it is possible to replace this node with a sequence of
13727 // two shifts followed by a MOVSS/MOVSD
13728 if (VT == MVT::v4i32) {
13729 // Check if it is legal to use a MOVSS.
13730 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13731 Amt2 == Amt->getOperand(3);
13732 if (!CanBeSimplified) {
13733 // Otherwise, check if we can still simplify this node using a MOVSD.
13734 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13735 Amt->getOperand(2) == Amt->getOperand(3);
13736 TargetOpcode = X86ISD::MOVSD;
13737 Amt2 = Amt->getOperand(2);
13740 // Do similar checks for the case where the machine value type
13742 CanBeSimplified = Amt1 == Amt->getOperand(1);
13743 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13744 CanBeSimplified = Amt2 == Amt->getOperand(i);
13746 if (!CanBeSimplified) {
13747 TargetOpcode = X86ISD::MOVSD;
13748 CanBeSimplified = true;
13749 Amt2 = Amt->getOperand(4);
13750 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13751 CanBeSimplified = Amt1 == Amt->getOperand(i);
13752 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13753 CanBeSimplified = Amt2 == Amt->getOperand(j);
13757 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13758 isa<ConstantSDNode>(Amt2)) {
13759 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13760 EVT CastVT = MVT::v4i32;
13762 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13763 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13765 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13766 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13767 if (TargetOpcode == X86ISD::MOVSD)
13768 CastVT = MVT::v2i64;
13769 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13770 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13771 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13773 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13777 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13778 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13781 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13782 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13784 // Turn 'a' into a mask suitable for VSELECT
13785 SDValue VSelM = DAG.getConstant(0x80, VT);
13786 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13787 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13789 SDValue CM1 = DAG.getConstant(0x0f, VT);
13790 SDValue CM2 = DAG.getConstant(0x3f, VT);
13792 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13793 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13794 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13795 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13796 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13799 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13800 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13801 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13803 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13804 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13805 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13806 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13807 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13810 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13811 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13812 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13814 // return VSELECT(r, r+r, a);
13815 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13816 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13820 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13821 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13822 // solution better.
13823 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13824 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13826 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13827 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13828 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13829 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13830 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13833 // Decompose 256-bit shifts into smaller 128-bit shifts.
13834 if (VT.is256BitVector()) {
13835 unsigned NumElems = VT.getVectorNumElements();
13836 MVT EltVT = VT.getVectorElementType();
13837 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13839 // Extract the two vectors
13840 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13841 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13843 // Recreate the shift amount vectors
13844 SDValue Amt1, Amt2;
13845 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13846 // Constant shift amount
13847 SmallVector<SDValue, 4> Amt1Csts;
13848 SmallVector<SDValue, 4> Amt2Csts;
13849 for (unsigned i = 0; i != NumElems/2; ++i)
13850 Amt1Csts.push_back(Amt->getOperand(i));
13851 for (unsigned i = NumElems/2; i != NumElems; ++i)
13852 Amt2Csts.push_back(Amt->getOperand(i));
13854 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13855 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13857 // Variable shift amount
13858 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13859 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13862 // Issue new vector shifts for the smaller types
13863 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13864 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13866 // Concatenate the result back
13867 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13873 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13874 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13875 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13876 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13877 // has only one use.
13878 SDNode *N = Op.getNode();
13879 SDValue LHS = N->getOperand(0);
13880 SDValue RHS = N->getOperand(1);
13881 unsigned BaseOp = 0;
13884 switch (Op.getOpcode()) {
13885 default: llvm_unreachable("Unknown ovf instruction!");
13887 // A subtract of one will be selected as a INC. Note that INC doesn't
13888 // set CF, so we can't do this for UADDO.
13889 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13891 BaseOp = X86ISD::INC;
13892 Cond = X86::COND_O;
13895 BaseOp = X86ISD::ADD;
13896 Cond = X86::COND_O;
13899 BaseOp = X86ISD::ADD;
13900 Cond = X86::COND_B;
13903 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13904 // set CF, so we can't do this for USUBO.
13905 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13907 BaseOp = X86ISD::DEC;
13908 Cond = X86::COND_O;
13911 BaseOp = X86ISD::SUB;
13912 Cond = X86::COND_O;
13915 BaseOp = X86ISD::SUB;
13916 Cond = X86::COND_B;
13919 BaseOp = X86ISD::SMUL;
13920 Cond = X86::COND_O;
13922 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13923 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13925 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13928 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13929 DAG.getConstant(X86::COND_O, MVT::i32),
13930 SDValue(Sum.getNode(), 2));
13932 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13936 // Also sets EFLAGS.
13937 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13938 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13941 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13942 DAG.getConstant(Cond, MVT::i32),
13943 SDValue(Sum.getNode(), 1));
13945 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13948 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13949 SelectionDAG &DAG) const {
13951 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13952 MVT VT = Op.getSimpleValueType();
13954 if (!Subtarget->hasSSE2() || !VT.isVector())
13957 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13958 ExtraVT.getScalarType().getSizeInBits();
13960 switch (VT.SimpleTy) {
13961 default: return SDValue();
13964 if (!Subtarget->hasFp256())
13966 if (!Subtarget->hasInt256()) {
13967 // needs to be split
13968 unsigned NumElems = VT.getVectorNumElements();
13970 // Extract the LHS vectors
13971 SDValue LHS = Op.getOperand(0);
13972 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13973 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13975 MVT EltVT = VT.getVectorElementType();
13976 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13978 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13979 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13980 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13982 SDValue Extra = DAG.getValueType(ExtraVT);
13984 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13985 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13987 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13992 SDValue Op0 = Op.getOperand(0);
13993 SDValue Op00 = Op0.getOperand(0);
13995 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13996 if (Op0.getOpcode() == ISD::BITCAST &&
13997 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13998 // (sext (vzext x)) -> (vsext x)
13999 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14000 if (Tmp1.getNode()) {
14001 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14002 // This folding is only valid when the in-reg type is a vector of i8,
14004 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14005 ExtraEltVT == MVT::i32) {
14006 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14007 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14008 "This optimization is invalid without a VZEXT.");
14009 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14015 // If the above didn't work, then just use Shift-Left + Shift-Right.
14016 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14018 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14024 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14025 SelectionDAG &DAG) {
14027 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14028 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14029 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14030 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14032 // The only fence that needs an instruction is a sequentially-consistent
14033 // cross-thread fence.
14034 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14035 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14036 // no-sse2). There isn't any reason to disable it if the target processor
14038 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14039 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14041 SDValue Chain = Op.getOperand(0);
14042 SDValue Zero = DAG.getConstant(0, MVT::i32);
14044 DAG.getRegister(X86::ESP, MVT::i32), // Base
14045 DAG.getTargetConstant(1, MVT::i8), // Scale
14046 DAG.getRegister(0, MVT::i32), // Index
14047 DAG.getTargetConstant(0, MVT::i32), // Disp
14048 DAG.getRegister(0, MVT::i32), // Segment.
14052 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14053 return SDValue(Res, 0);
14056 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14057 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14060 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14061 SelectionDAG &DAG) {
14062 MVT T = Op.getSimpleValueType();
14066 switch(T.SimpleTy) {
14067 default: llvm_unreachable("Invalid value type!");
14068 case MVT::i8: Reg = X86::AL; size = 1; break;
14069 case MVT::i16: Reg = X86::AX; size = 2; break;
14070 case MVT::i32: Reg = X86::EAX; size = 4; break;
14072 assert(Subtarget->is64Bit() && "Node not type legal!");
14073 Reg = X86::RAX; size = 8;
14076 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14077 Op.getOperand(2), SDValue());
14078 SDValue Ops[] = { cpIn.getValue(0),
14081 DAG.getTargetConstant(size, MVT::i8),
14082 cpIn.getValue(1) };
14083 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14084 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14085 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14088 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14092 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14093 SelectionDAG &DAG) {
14094 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14095 MVT DstVT = Op.getSimpleValueType();
14097 if (SrcVT == MVT::v2i32) {
14098 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14099 if (DstVT != MVT::f64)
14100 // This conversion needs to be expanded.
14104 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14105 Op->getOperand(0), DAG.getIntPtrConstant(0));
14106 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14107 Op->getOperand(0), DAG.getIntPtrConstant(1));
14108 SDValue Elts[] = {Elt0, Elt1, Elt0, Elt0};
14109 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Elts);
14110 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14111 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14112 DAG.getIntPtrConstant(0));
14115 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14116 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14117 assert((DstVT == MVT::i64 ||
14118 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14119 "Unexpected custom BITCAST");
14120 // i64 <=> MMX conversions are Legal.
14121 if (SrcVT==MVT::i64 && DstVT.isVector())
14123 if (DstVT==MVT::i64 && SrcVT.isVector())
14125 // MMX <=> MMX conversions are Legal.
14126 if (SrcVT.isVector() && DstVT.isVector())
14128 // All other conversions need to be expanded.
14132 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14133 SDNode *Node = Op.getNode();
14135 EVT T = Node->getValueType(0);
14136 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14137 DAG.getConstant(0, T), Node->getOperand(2));
14138 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14139 cast<AtomicSDNode>(Node)->getMemoryVT(),
14140 Node->getOperand(0),
14141 Node->getOperand(1), negOp,
14142 cast<AtomicSDNode>(Node)->getMemOperand(),
14143 cast<AtomicSDNode>(Node)->getOrdering(),
14144 cast<AtomicSDNode>(Node)->getSynchScope());
14147 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14148 SDNode *Node = Op.getNode();
14150 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14152 // Convert seq_cst store -> xchg
14153 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14154 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14155 // (The only way to get a 16-byte store is cmpxchg16b)
14156 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14157 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14158 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14159 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14160 cast<AtomicSDNode>(Node)->getMemoryVT(),
14161 Node->getOperand(0),
14162 Node->getOperand(1), Node->getOperand(2),
14163 cast<AtomicSDNode>(Node)->getMemOperand(),
14164 cast<AtomicSDNode>(Node)->getOrdering(),
14165 cast<AtomicSDNode>(Node)->getSynchScope());
14166 return Swap.getValue(1);
14168 // Other atomic stores have a simple pattern.
14172 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14173 EVT VT = Op.getNode()->getSimpleValueType(0);
14175 // Let legalize expand this if it isn't a legal type yet.
14176 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14179 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14182 bool ExtraOp = false;
14183 switch (Op.getOpcode()) {
14184 default: llvm_unreachable("Invalid code");
14185 case ISD::ADDC: Opc = X86ISD::ADD; break;
14186 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14187 case ISD::SUBC: Opc = X86ISD::SUB; break;
14188 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14192 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14194 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14195 Op.getOperand(1), Op.getOperand(2));
14198 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14199 SelectionDAG &DAG) {
14200 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14202 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14203 // which returns the values as { float, float } (in XMM0) or
14204 // { double, double } (which is returned in XMM0, XMM1).
14206 SDValue Arg = Op.getOperand(0);
14207 EVT ArgVT = Arg.getValueType();
14208 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14210 TargetLowering::ArgListTy Args;
14211 TargetLowering::ArgListEntry Entry;
14215 Entry.isSExt = false;
14216 Entry.isZExt = false;
14217 Args.push_back(Entry);
14219 bool isF64 = ArgVT == MVT::f64;
14220 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14221 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14222 // the results are returned via SRet in memory.
14223 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14224 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14225 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14227 Type *RetTy = isF64
14228 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14229 : (Type*)VectorType::get(ArgTy, 4);
14231 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14232 false, false, false, false, 0,
14233 CallingConv::C, /*isTaillCall=*/false,
14234 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14235 Callee, Args, DAG, dl);
14236 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14239 // Returned in xmm0 and xmm1.
14240 return CallResult.first;
14242 // Returned in bits 0:31 and 32:64 xmm0.
14243 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14244 CallResult.first, DAG.getIntPtrConstant(0));
14245 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14246 CallResult.first, DAG.getIntPtrConstant(1));
14247 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14248 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14251 /// LowerOperation - Provide custom lowering hooks for some operations.
14253 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14254 switch (Op.getOpcode()) {
14255 default: llvm_unreachable("Should not custom lower this!");
14256 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14257 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14258 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14259 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14260 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14261 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14262 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14263 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14264 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14265 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14266 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14267 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14268 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14269 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14270 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14271 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14272 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14273 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14274 case ISD::SHL_PARTS:
14275 case ISD::SRA_PARTS:
14276 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14277 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14278 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14279 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14280 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14281 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14282 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14283 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14284 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14285 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14286 case ISD::FABS: return LowerFABS(Op, DAG);
14287 case ISD::FNEG: return LowerFNEG(Op, DAG);
14288 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14289 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14290 case ISD::SETCC: return LowerSETCC(Op, DAG);
14291 case ISD::SELECT: return LowerSELECT(Op, DAG);
14292 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14293 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14294 case ISD::VASTART: return LowerVASTART(Op, DAG);
14295 case ISD::VAARG: return LowerVAARG(Op, DAG);
14296 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14297 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14298 case ISD::INTRINSIC_VOID:
14299 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14300 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14301 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14302 case ISD::FRAME_TO_ARGS_OFFSET:
14303 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14304 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14305 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14306 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14307 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14308 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14309 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14310 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14311 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14312 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14313 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14314 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14315 case ISD::UMUL_LOHI:
14316 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14319 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14325 case ISD::UMULO: return LowerXALUO(Op, DAG);
14326 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14327 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14331 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14332 case ISD::ADD: return LowerADD(Op, DAG);
14333 case ISD::SUB: return LowerSUB(Op, DAG);
14334 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14338 static void ReplaceATOMIC_LOAD(SDNode *Node,
14339 SmallVectorImpl<SDValue> &Results,
14340 SelectionDAG &DAG) {
14342 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14344 // Convert wide load -> cmpxchg8b/cmpxchg16b
14345 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14346 // (The only way to get a 16-byte load is cmpxchg16b)
14347 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14348 SDValue Zero = DAG.getConstant(0, VT);
14349 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14350 Node->getOperand(0),
14351 Node->getOperand(1), Zero, Zero,
14352 cast<AtomicSDNode>(Node)->getMemOperand(),
14353 cast<AtomicSDNode>(Node)->getOrdering(),
14354 cast<AtomicSDNode>(Node)->getOrdering(),
14355 cast<AtomicSDNode>(Node)->getSynchScope());
14356 Results.push_back(Swap.getValue(0));
14357 Results.push_back(Swap.getValue(1));
14361 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14362 SelectionDAG &DAG, unsigned NewOp) {
14364 assert (Node->getValueType(0) == MVT::i64 &&
14365 "Only know how to expand i64 atomics");
14367 SDValue Chain = Node->getOperand(0);
14368 SDValue In1 = Node->getOperand(1);
14369 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14370 Node->getOperand(2), DAG.getIntPtrConstant(0));
14371 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14372 Node->getOperand(2), DAG.getIntPtrConstant(1));
14373 SDValue Ops[] = { Chain, In1, In2L, In2H };
14374 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14376 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14377 cast<MemSDNode>(Node)->getMemOperand());
14378 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14379 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14380 Results.push_back(Result.getValue(2));
14383 /// ReplaceNodeResults - Replace a node with an illegal result type
14384 /// with a new node built out of custom code.
14385 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14386 SmallVectorImpl<SDValue>&Results,
14387 SelectionDAG &DAG) const {
14389 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14390 switch (N->getOpcode()) {
14392 llvm_unreachable("Do not know how to custom type legalize this operation!");
14393 case ISD::SIGN_EXTEND_INREG:
14398 // We don't want to expand or promote these.
14405 case ISD::UDIVREM: {
14406 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14407 Results.push_back(V);
14410 case ISD::FP_TO_SINT:
14411 case ISD::FP_TO_UINT: {
14412 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14414 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14417 std::pair<SDValue,SDValue> Vals =
14418 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14419 SDValue FIST = Vals.first, StackSlot = Vals.second;
14420 if (FIST.getNode()) {
14421 EVT VT = N->getValueType(0);
14422 // Return a load from the stack slot.
14423 if (StackSlot.getNode())
14424 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14425 MachinePointerInfo(),
14426 false, false, false, 0));
14428 Results.push_back(FIST);
14432 case ISD::UINT_TO_FP: {
14433 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14434 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14435 N->getValueType(0) != MVT::v2f32)
14437 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14439 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14441 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14442 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14443 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14444 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14445 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14446 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14449 case ISD::FP_ROUND: {
14450 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14452 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14453 Results.push_back(V);
14456 case ISD::INTRINSIC_W_CHAIN: {
14457 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14459 default : llvm_unreachable("Do not know how to custom type "
14460 "legalize this intrinsic operation!");
14461 case Intrinsic::x86_rdtsc:
14462 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14464 case Intrinsic::x86_rdtscp:
14465 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14469 case ISD::READCYCLECOUNTER: {
14470 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14473 case ISD::ATOMIC_CMP_SWAP: {
14474 EVT T = N->getValueType(0);
14475 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14476 bool Regs64bit = T == MVT::i128;
14477 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14478 SDValue cpInL, cpInH;
14479 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14480 DAG.getConstant(0, HalfT));
14481 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14482 DAG.getConstant(1, HalfT));
14483 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14484 Regs64bit ? X86::RAX : X86::EAX,
14486 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14487 Regs64bit ? X86::RDX : X86::EDX,
14488 cpInH, cpInL.getValue(1));
14489 SDValue swapInL, swapInH;
14490 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14491 DAG.getConstant(0, HalfT));
14492 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14493 DAG.getConstant(1, HalfT));
14494 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14495 Regs64bit ? X86::RBX : X86::EBX,
14496 swapInL, cpInH.getValue(1));
14497 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14498 Regs64bit ? X86::RCX : X86::ECX,
14499 swapInH, swapInL.getValue(1));
14500 SDValue Ops[] = { swapInH.getValue(0),
14502 swapInH.getValue(1) };
14503 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14504 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14505 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14506 X86ISD::LCMPXCHG8_DAG;
14507 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14508 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14509 Regs64bit ? X86::RAX : X86::EAX,
14510 HalfT, Result.getValue(1));
14511 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14512 Regs64bit ? X86::RDX : X86::EDX,
14513 HalfT, cpOutL.getValue(2));
14514 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14515 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14516 Results.push_back(cpOutH.getValue(1));
14519 case ISD::ATOMIC_LOAD_ADD:
14520 case ISD::ATOMIC_LOAD_AND:
14521 case ISD::ATOMIC_LOAD_NAND:
14522 case ISD::ATOMIC_LOAD_OR:
14523 case ISD::ATOMIC_LOAD_SUB:
14524 case ISD::ATOMIC_LOAD_XOR:
14525 case ISD::ATOMIC_LOAD_MAX:
14526 case ISD::ATOMIC_LOAD_MIN:
14527 case ISD::ATOMIC_LOAD_UMAX:
14528 case ISD::ATOMIC_LOAD_UMIN:
14529 case ISD::ATOMIC_SWAP: {
14531 switch (N->getOpcode()) {
14532 default: llvm_unreachable("Unexpected opcode");
14533 case ISD::ATOMIC_LOAD_ADD:
14534 Opc = X86ISD::ATOMADD64_DAG;
14536 case ISD::ATOMIC_LOAD_AND:
14537 Opc = X86ISD::ATOMAND64_DAG;
14539 case ISD::ATOMIC_LOAD_NAND:
14540 Opc = X86ISD::ATOMNAND64_DAG;
14542 case ISD::ATOMIC_LOAD_OR:
14543 Opc = X86ISD::ATOMOR64_DAG;
14545 case ISD::ATOMIC_LOAD_SUB:
14546 Opc = X86ISD::ATOMSUB64_DAG;
14548 case ISD::ATOMIC_LOAD_XOR:
14549 Opc = X86ISD::ATOMXOR64_DAG;
14551 case ISD::ATOMIC_LOAD_MAX:
14552 Opc = X86ISD::ATOMMAX64_DAG;
14554 case ISD::ATOMIC_LOAD_MIN:
14555 Opc = X86ISD::ATOMMIN64_DAG;
14557 case ISD::ATOMIC_LOAD_UMAX:
14558 Opc = X86ISD::ATOMUMAX64_DAG;
14560 case ISD::ATOMIC_LOAD_UMIN:
14561 Opc = X86ISD::ATOMUMIN64_DAG;
14563 case ISD::ATOMIC_SWAP:
14564 Opc = X86ISD::ATOMSWAP64_DAG;
14567 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14570 case ISD::ATOMIC_LOAD: {
14571 ReplaceATOMIC_LOAD(N, Results, DAG);
14574 case ISD::BITCAST: {
14575 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14576 EVT DstVT = N->getValueType(0);
14577 EVT SrcVT = N->getOperand(0)->getValueType(0);
14579 if (SrcVT == MVT::f64 && DstVT == MVT::v2i32) {
14580 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14581 MVT::v2f64, N->getOperand(0));
14582 SDValue ToV4I32 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Expanded);
14583 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14584 ToV4I32, DAG.getIntPtrConstant(0));
14585 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14586 ToV4I32, DAG.getIntPtrConstant(1));
14587 SDValue Elts[] = {Elt0, Elt1};
14588 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Elts));
14594 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14596 default: return nullptr;
14597 case X86ISD::BSF: return "X86ISD::BSF";
14598 case X86ISD::BSR: return "X86ISD::BSR";
14599 case X86ISD::SHLD: return "X86ISD::SHLD";
14600 case X86ISD::SHRD: return "X86ISD::SHRD";
14601 case X86ISD::FAND: return "X86ISD::FAND";
14602 case X86ISD::FANDN: return "X86ISD::FANDN";
14603 case X86ISD::FOR: return "X86ISD::FOR";
14604 case X86ISD::FXOR: return "X86ISD::FXOR";
14605 case X86ISD::FSRL: return "X86ISD::FSRL";
14606 case X86ISD::FILD: return "X86ISD::FILD";
14607 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14608 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14609 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14610 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14611 case X86ISD::FLD: return "X86ISD::FLD";
14612 case X86ISD::FST: return "X86ISD::FST";
14613 case X86ISD::CALL: return "X86ISD::CALL";
14614 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14615 case X86ISD::BT: return "X86ISD::BT";
14616 case X86ISD::CMP: return "X86ISD::CMP";
14617 case X86ISD::COMI: return "X86ISD::COMI";
14618 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14619 case X86ISD::CMPM: return "X86ISD::CMPM";
14620 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14621 case X86ISD::SETCC: return "X86ISD::SETCC";
14622 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14623 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14624 case X86ISD::CMOV: return "X86ISD::CMOV";
14625 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14626 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14627 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14628 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14629 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14630 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14631 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14632 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14633 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14634 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14635 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14636 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14637 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14638 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14639 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14640 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14641 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14642 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14643 case X86ISD::HADD: return "X86ISD::HADD";
14644 case X86ISD::HSUB: return "X86ISD::HSUB";
14645 case X86ISD::FHADD: return "X86ISD::FHADD";
14646 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14647 case X86ISD::UMAX: return "X86ISD::UMAX";
14648 case X86ISD::UMIN: return "X86ISD::UMIN";
14649 case X86ISD::SMAX: return "X86ISD::SMAX";
14650 case X86ISD::SMIN: return "X86ISD::SMIN";
14651 case X86ISD::FMAX: return "X86ISD::FMAX";
14652 case X86ISD::FMIN: return "X86ISD::FMIN";
14653 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14654 case X86ISD::FMINC: return "X86ISD::FMINC";
14655 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14656 case X86ISD::FRCP: return "X86ISD::FRCP";
14657 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14658 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14659 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14660 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14661 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14662 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14663 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14664 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14665 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14666 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14667 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14668 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14669 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14670 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14671 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14672 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14673 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14674 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14675 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14676 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14677 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14678 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14679 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14680 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14681 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14682 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14683 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14684 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14685 case X86ISD::VSHL: return "X86ISD::VSHL";
14686 case X86ISD::VSRL: return "X86ISD::VSRL";
14687 case X86ISD::VSRA: return "X86ISD::VSRA";
14688 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14689 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14690 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14691 case X86ISD::CMPP: return "X86ISD::CMPP";
14692 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14693 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14694 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14695 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14696 case X86ISD::ADD: return "X86ISD::ADD";
14697 case X86ISD::SUB: return "X86ISD::SUB";
14698 case X86ISD::ADC: return "X86ISD::ADC";
14699 case X86ISD::SBB: return "X86ISD::SBB";
14700 case X86ISD::SMUL: return "X86ISD::SMUL";
14701 case X86ISD::UMUL: return "X86ISD::UMUL";
14702 case X86ISD::INC: return "X86ISD::INC";
14703 case X86ISD::DEC: return "X86ISD::DEC";
14704 case X86ISD::OR: return "X86ISD::OR";
14705 case X86ISD::XOR: return "X86ISD::XOR";
14706 case X86ISD::AND: return "X86ISD::AND";
14707 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14708 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14709 case X86ISD::PTEST: return "X86ISD::PTEST";
14710 case X86ISD::TESTP: return "X86ISD::TESTP";
14711 case X86ISD::TESTM: return "X86ISD::TESTM";
14712 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14713 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14714 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14715 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14716 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14717 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14718 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14719 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14720 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14721 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14722 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14723 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14724 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14725 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14726 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14727 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14728 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14729 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14730 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14731 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14732 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14733 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14734 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14735 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14736 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14737 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14738 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14739 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14740 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14741 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14742 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14743 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14744 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14745 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14746 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14747 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14748 case X86ISD::SAHF: return "X86ISD::SAHF";
14749 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14750 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14751 case X86ISD::FMADD: return "X86ISD::FMADD";
14752 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14753 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14754 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14755 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14756 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14757 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14758 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14759 case X86ISD::XTEST: return "X86ISD::XTEST";
14763 // isLegalAddressingMode - Return true if the addressing mode represented
14764 // by AM is legal for this target, for a load/store of the specified type.
14765 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14767 // X86 supports extremely general addressing modes.
14768 CodeModel::Model M = getTargetMachine().getCodeModel();
14769 Reloc::Model R = getTargetMachine().getRelocationModel();
14771 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14772 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14777 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14779 // If a reference to this global requires an extra load, we can't fold it.
14780 if (isGlobalStubReference(GVFlags))
14783 // If BaseGV requires a register for the PIC base, we cannot also have a
14784 // BaseReg specified.
14785 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14788 // If lower 4G is not available, then we must use rip-relative addressing.
14789 if ((M != CodeModel::Small || R != Reloc::Static) &&
14790 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14794 switch (AM.Scale) {
14800 // These scales always work.
14805 // These scales are formed with basereg+scalereg. Only accept if there is
14810 default: // Other stuff never works.
14817 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14818 unsigned Bits = Ty->getScalarSizeInBits();
14820 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14821 // particularly cheaper than those without.
14825 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14826 // variable shifts just as cheap as scalar ones.
14827 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14830 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14831 // fully general vector.
14835 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14836 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14838 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14839 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14840 return NumBits1 > NumBits2;
14843 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14844 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14847 if (!isTypeLegal(EVT::getEVT(Ty1)))
14850 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14852 // Assuming the caller doesn't have a zeroext or signext return parameter,
14853 // truncation all the way down to i1 is valid.
14857 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14858 return isInt<32>(Imm);
14861 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14862 // Can also use sub to handle negated immediates.
14863 return isInt<32>(Imm);
14866 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14867 if (!VT1.isInteger() || !VT2.isInteger())
14869 unsigned NumBits1 = VT1.getSizeInBits();
14870 unsigned NumBits2 = VT2.getSizeInBits();
14871 return NumBits1 > NumBits2;
14874 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14875 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14876 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14879 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14880 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14881 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14884 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14885 EVT VT1 = Val.getValueType();
14886 if (isZExtFree(VT1, VT2))
14889 if (Val.getOpcode() != ISD::LOAD)
14892 if (!VT1.isSimple() || !VT1.isInteger() ||
14893 !VT2.isSimple() || !VT2.isInteger())
14896 switch (VT1.getSimpleVT().SimpleTy) {
14901 // X86 has 8, 16, and 32-bit zero-extending loads.
14909 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14910 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14913 VT = VT.getScalarType();
14915 if (!VT.isSimple())
14918 switch (VT.getSimpleVT().SimpleTy) {
14929 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14930 // i16 instructions are longer (0x66 prefix) and potentially slower.
14931 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14934 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14935 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14936 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14937 /// are assumed to be legal.
14939 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14941 if (!VT.isSimple())
14944 MVT SVT = VT.getSimpleVT();
14946 // Very little shuffling can be done for 64-bit vectors right now.
14947 if (VT.getSizeInBits() == 64)
14950 // FIXME: pshufb, blends, shifts.
14951 return (SVT.getVectorNumElements() == 2 ||
14952 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14953 isMOVLMask(M, SVT) ||
14954 isSHUFPMask(M, SVT) ||
14955 isPSHUFDMask(M, SVT) ||
14956 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14957 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14958 isPALIGNRMask(M, SVT, Subtarget) ||
14959 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14960 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14961 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14962 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14966 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14968 if (!VT.isSimple())
14971 MVT SVT = VT.getSimpleVT();
14972 unsigned NumElts = SVT.getVectorNumElements();
14973 // FIXME: This collection of masks seems suspect.
14976 if (NumElts == 4 && SVT.is128BitVector()) {
14977 return (isMOVLMask(Mask, SVT) ||
14978 isCommutedMOVLMask(Mask, SVT, true) ||
14979 isSHUFPMask(Mask, SVT) ||
14980 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14985 //===----------------------------------------------------------------------===//
14986 // X86 Scheduler Hooks
14987 //===----------------------------------------------------------------------===//
14989 /// Utility function to emit xbegin specifying the start of an RTM region.
14990 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14991 const TargetInstrInfo *TII) {
14992 DebugLoc DL = MI->getDebugLoc();
14994 const BasicBlock *BB = MBB->getBasicBlock();
14995 MachineFunction::iterator I = MBB;
14998 // For the v = xbegin(), we generate
15009 MachineBasicBlock *thisMBB = MBB;
15010 MachineFunction *MF = MBB->getParent();
15011 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15012 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15013 MF->insert(I, mainMBB);
15014 MF->insert(I, sinkMBB);
15016 // Transfer the remainder of BB and its successor edges to sinkMBB.
15017 sinkMBB->splice(sinkMBB->begin(), MBB,
15018 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15019 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15023 // # fallthrough to mainMBB
15024 // # abortion to sinkMBB
15025 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15026 thisMBB->addSuccessor(mainMBB);
15027 thisMBB->addSuccessor(sinkMBB);
15031 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15032 mainMBB->addSuccessor(sinkMBB);
15035 // EAX is live into the sinkMBB
15036 sinkMBB->addLiveIn(X86::EAX);
15037 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15038 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15041 MI->eraseFromParent();
15045 // Get CMPXCHG opcode for the specified data type.
15046 static unsigned getCmpXChgOpcode(EVT VT) {
15047 switch (VT.getSimpleVT().SimpleTy) {
15048 case MVT::i8: return X86::LCMPXCHG8;
15049 case MVT::i16: return X86::LCMPXCHG16;
15050 case MVT::i32: return X86::LCMPXCHG32;
15051 case MVT::i64: return X86::LCMPXCHG64;
15055 llvm_unreachable("Invalid operand size!");
15058 // Get LOAD opcode for the specified data type.
15059 static unsigned getLoadOpcode(EVT VT) {
15060 switch (VT.getSimpleVT().SimpleTy) {
15061 case MVT::i8: return X86::MOV8rm;
15062 case MVT::i16: return X86::MOV16rm;
15063 case MVT::i32: return X86::MOV32rm;
15064 case MVT::i64: return X86::MOV64rm;
15068 llvm_unreachable("Invalid operand size!");
15071 // Get opcode of the non-atomic one from the specified atomic instruction.
15072 static unsigned getNonAtomicOpcode(unsigned Opc) {
15074 case X86::ATOMAND8: return X86::AND8rr;
15075 case X86::ATOMAND16: return X86::AND16rr;
15076 case X86::ATOMAND32: return X86::AND32rr;
15077 case X86::ATOMAND64: return X86::AND64rr;
15078 case X86::ATOMOR8: return X86::OR8rr;
15079 case X86::ATOMOR16: return X86::OR16rr;
15080 case X86::ATOMOR32: return X86::OR32rr;
15081 case X86::ATOMOR64: return X86::OR64rr;
15082 case X86::ATOMXOR8: return X86::XOR8rr;
15083 case X86::ATOMXOR16: return X86::XOR16rr;
15084 case X86::ATOMXOR32: return X86::XOR32rr;
15085 case X86::ATOMXOR64: return X86::XOR64rr;
15087 llvm_unreachable("Unhandled atomic-load-op opcode!");
15090 // Get opcode of the non-atomic one from the specified atomic instruction with
15092 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15093 unsigned &ExtraOpc) {
15095 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15096 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15097 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15098 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15099 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15100 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15101 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15102 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15103 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15104 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15105 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15106 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15107 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15108 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15109 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15110 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15111 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15112 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15113 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15114 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15116 llvm_unreachable("Unhandled atomic-load-op opcode!");
15119 // Get opcode of the non-atomic one from the specified atomic instruction for
15120 // 64-bit data type on 32-bit target.
15121 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15123 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15124 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15125 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15126 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15127 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15128 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15129 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15130 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15131 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15132 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15134 llvm_unreachable("Unhandled atomic-load-op opcode!");
15137 // Get opcode of the non-atomic one from the specified atomic instruction for
15138 // 64-bit data type on 32-bit target with extra opcode.
15139 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15141 unsigned &ExtraOpc) {
15143 case X86::ATOMNAND6432:
15144 ExtraOpc = X86::NOT32r;
15145 HiOpc = X86::AND32rr;
15146 return X86::AND32rr;
15148 llvm_unreachable("Unhandled atomic-load-op opcode!");
15151 // Get pseudo CMOV opcode from the specified data type.
15152 static unsigned getPseudoCMOVOpc(EVT VT) {
15153 switch (VT.getSimpleVT().SimpleTy) {
15154 case MVT::i8: return X86::CMOV_GR8;
15155 case MVT::i16: return X86::CMOV_GR16;
15156 case MVT::i32: return X86::CMOV_GR32;
15160 llvm_unreachable("Unknown CMOV opcode!");
15163 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15164 // They will be translated into a spin-loop or compare-exchange loop from
15167 // dst = atomic-fetch-op MI.addr, MI.val
15173 // t1 = LOAD MI.addr
15175 // t4 = phi(t1, t3 / loop)
15176 // t2 = OP MI.val, t4
15178 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15184 MachineBasicBlock *
15185 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15186 MachineBasicBlock *MBB) const {
15187 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15188 DebugLoc DL = MI->getDebugLoc();
15190 MachineFunction *MF = MBB->getParent();
15191 MachineRegisterInfo &MRI = MF->getRegInfo();
15193 const BasicBlock *BB = MBB->getBasicBlock();
15194 MachineFunction::iterator I = MBB;
15197 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15198 "Unexpected number of operands");
15200 assert(MI->hasOneMemOperand() &&
15201 "Expected atomic-load-op to have one memoperand");
15203 // Memory Reference
15204 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15205 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15207 unsigned DstReg, SrcReg;
15208 unsigned MemOpndSlot;
15210 unsigned CurOp = 0;
15212 DstReg = MI->getOperand(CurOp++).getReg();
15213 MemOpndSlot = CurOp;
15214 CurOp += X86::AddrNumOperands;
15215 SrcReg = MI->getOperand(CurOp++).getReg();
15217 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15218 MVT::SimpleValueType VT = *RC->vt_begin();
15219 unsigned t1 = MRI.createVirtualRegister(RC);
15220 unsigned t2 = MRI.createVirtualRegister(RC);
15221 unsigned t3 = MRI.createVirtualRegister(RC);
15222 unsigned t4 = MRI.createVirtualRegister(RC);
15223 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15225 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15226 unsigned LOADOpc = getLoadOpcode(VT);
15228 // For the atomic load-arith operator, we generate
15231 // t1 = LOAD [MI.addr]
15233 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15234 // t1 = OP MI.val, EAX
15236 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15242 MachineBasicBlock *thisMBB = MBB;
15243 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15244 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15245 MF->insert(I, mainMBB);
15246 MF->insert(I, sinkMBB);
15248 MachineInstrBuilder MIB;
15250 // Transfer the remainder of BB and its successor edges to sinkMBB.
15251 sinkMBB->splice(sinkMBB->begin(), MBB,
15252 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15253 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15256 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15257 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15258 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15260 NewMO.setIsKill(false);
15261 MIB.addOperand(NewMO);
15263 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15264 unsigned flags = (*MMOI)->getFlags();
15265 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15266 MachineMemOperand *MMO =
15267 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15268 (*MMOI)->getSize(),
15269 (*MMOI)->getBaseAlignment(),
15270 (*MMOI)->getTBAAInfo(),
15271 (*MMOI)->getRanges());
15272 MIB.addMemOperand(MMO);
15275 thisMBB->addSuccessor(mainMBB);
15278 MachineBasicBlock *origMainMBB = mainMBB;
15281 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15282 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15284 unsigned Opc = MI->getOpcode();
15287 llvm_unreachable("Unhandled atomic-load-op opcode!");
15288 case X86::ATOMAND8:
15289 case X86::ATOMAND16:
15290 case X86::ATOMAND32:
15291 case X86::ATOMAND64:
15293 case X86::ATOMOR16:
15294 case X86::ATOMOR32:
15295 case X86::ATOMOR64:
15296 case X86::ATOMXOR8:
15297 case X86::ATOMXOR16:
15298 case X86::ATOMXOR32:
15299 case X86::ATOMXOR64: {
15300 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15301 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15305 case X86::ATOMNAND8:
15306 case X86::ATOMNAND16:
15307 case X86::ATOMNAND32:
15308 case X86::ATOMNAND64: {
15309 unsigned Tmp = MRI.createVirtualRegister(RC);
15311 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15312 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15314 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15317 case X86::ATOMMAX8:
15318 case X86::ATOMMAX16:
15319 case X86::ATOMMAX32:
15320 case X86::ATOMMAX64:
15321 case X86::ATOMMIN8:
15322 case X86::ATOMMIN16:
15323 case X86::ATOMMIN32:
15324 case X86::ATOMMIN64:
15325 case X86::ATOMUMAX8:
15326 case X86::ATOMUMAX16:
15327 case X86::ATOMUMAX32:
15328 case X86::ATOMUMAX64:
15329 case X86::ATOMUMIN8:
15330 case X86::ATOMUMIN16:
15331 case X86::ATOMUMIN32:
15332 case X86::ATOMUMIN64: {
15334 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15336 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15340 if (Subtarget->hasCMov()) {
15341 if (VT != MVT::i8) {
15343 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15347 // Promote i8 to i32 to use CMOV32
15348 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15349 const TargetRegisterClass *RC32 =
15350 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15351 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15352 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15353 unsigned Tmp = MRI.createVirtualRegister(RC32);
15355 unsigned Undef = MRI.createVirtualRegister(RC32);
15356 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15358 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15361 .addImm(X86::sub_8bit);
15362 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15365 .addImm(X86::sub_8bit);
15367 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15371 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15372 .addReg(Tmp, 0, X86::sub_8bit);
15375 // Use pseudo select and lower them.
15376 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15377 "Invalid atomic-load-op transformation!");
15378 unsigned SelOpc = getPseudoCMOVOpc(VT);
15379 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15380 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15381 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15382 .addReg(SrcReg).addReg(t4)
15384 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15385 // Replace the original PHI node as mainMBB is changed after CMOV
15387 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15388 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15389 Phi->eraseFromParent();
15395 // Copy PhyReg back from virtual register.
15396 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15399 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15400 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15401 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15403 NewMO.setIsKill(false);
15404 MIB.addOperand(NewMO);
15407 MIB.setMemRefs(MMOBegin, MMOEnd);
15409 // Copy PhyReg back to virtual register.
15410 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15413 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15415 mainMBB->addSuccessor(origMainMBB);
15416 mainMBB->addSuccessor(sinkMBB);
15419 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15420 TII->get(TargetOpcode::COPY), DstReg)
15423 MI->eraseFromParent();
15427 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15428 // instructions. They will be translated into a spin-loop or compare-exchange
15432 // dst = atomic-fetch-op MI.addr, MI.val
15438 // t1L = LOAD [MI.addr + 0]
15439 // t1H = LOAD [MI.addr + 4]
15441 // t4L = phi(t1L, t3L / loop)
15442 // t4H = phi(t1H, t3H / loop)
15443 // t2L = OP MI.val.lo, t4L
15444 // t2H = OP MI.val.hi, t4H
15449 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15457 MachineBasicBlock *
15458 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15459 MachineBasicBlock *MBB) const {
15460 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15461 DebugLoc DL = MI->getDebugLoc();
15463 MachineFunction *MF = MBB->getParent();
15464 MachineRegisterInfo &MRI = MF->getRegInfo();
15466 const BasicBlock *BB = MBB->getBasicBlock();
15467 MachineFunction::iterator I = MBB;
15470 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15471 "Unexpected number of operands");
15473 assert(MI->hasOneMemOperand() &&
15474 "Expected atomic-load-op32 to have one memoperand");
15476 // Memory Reference
15477 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15478 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15480 unsigned DstLoReg, DstHiReg;
15481 unsigned SrcLoReg, SrcHiReg;
15482 unsigned MemOpndSlot;
15484 unsigned CurOp = 0;
15486 DstLoReg = MI->getOperand(CurOp++).getReg();
15487 DstHiReg = MI->getOperand(CurOp++).getReg();
15488 MemOpndSlot = CurOp;
15489 CurOp += X86::AddrNumOperands;
15490 SrcLoReg = MI->getOperand(CurOp++).getReg();
15491 SrcHiReg = MI->getOperand(CurOp++).getReg();
15493 const TargetRegisterClass *RC = &X86::GR32RegClass;
15494 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15496 unsigned t1L = MRI.createVirtualRegister(RC);
15497 unsigned t1H = MRI.createVirtualRegister(RC);
15498 unsigned t2L = MRI.createVirtualRegister(RC);
15499 unsigned t2H = MRI.createVirtualRegister(RC);
15500 unsigned t3L = MRI.createVirtualRegister(RC);
15501 unsigned t3H = MRI.createVirtualRegister(RC);
15502 unsigned t4L = MRI.createVirtualRegister(RC);
15503 unsigned t4H = MRI.createVirtualRegister(RC);
15505 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15506 unsigned LOADOpc = X86::MOV32rm;
15508 // For the atomic load-arith operator, we generate
15511 // t1L = LOAD [MI.addr + 0]
15512 // t1H = LOAD [MI.addr + 4]
15514 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15515 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15516 // t2L = OP MI.val.lo, t4L
15517 // t2H = OP MI.val.hi, t4H
15520 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15528 MachineBasicBlock *thisMBB = MBB;
15529 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15530 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15531 MF->insert(I, mainMBB);
15532 MF->insert(I, sinkMBB);
15534 MachineInstrBuilder MIB;
15536 // Transfer the remainder of BB and its successor edges to sinkMBB.
15537 sinkMBB->splice(sinkMBB->begin(), MBB,
15538 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15539 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15543 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15544 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15545 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15547 NewMO.setIsKill(false);
15548 MIB.addOperand(NewMO);
15550 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15551 unsigned flags = (*MMOI)->getFlags();
15552 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15553 MachineMemOperand *MMO =
15554 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15555 (*MMOI)->getSize(),
15556 (*MMOI)->getBaseAlignment(),
15557 (*MMOI)->getTBAAInfo(),
15558 (*MMOI)->getRanges());
15559 MIB.addMemOperand(MMO);
15561 MachineInstr *LowMI = MIB;
15564 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15565 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15566 if (i == X86::AddrDisp) {
15567 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15569 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15571 NewMO.setIsKill(false);
15572 MIB.addOperand(NewMO);
15575 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15577 thisMBB->addSuccessor(mainMBB);
15580 MachineBasicBlock *origMainMBB = mainMBB;
15583 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15584 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15585 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15586 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15588 unsigned Opc = MI->getOpcode();
15591 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15592 case X86::ATOMAND6432:
15593 case X86::ATOMOR6432:
15594 case X86::ATOMXOR6432:
15595 case X86::ATOMADD6432:
15596 case X86::ATOMSUB6432: {
15598 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15599 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15601 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15605 case X86::ATOMNAND6432: {
15606 unsigned HiOpc, NOTOpc;
15607 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15608 unsigned TmpL = MRI.createVirtualRegister(RC);
15609 unsigned TmpH = MRI.createVirtualRegister(RC);
15610 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15612 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15614 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15615 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15618 case X86::ATOMMAX6432:
15619 case X86::ATOMMIN6432:
15620 case X86::ATOMUMAX6432:
15621 case X86::ATOMUMIN6432: {
15623 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15624 unsigned cL = MRI.createVirtualRegister(RC8);
15625 unsigned cH = MRI.createVirtualRegister(RC8);
15626 unsigned cL32 = MRI.createVirtualRegister(RC);
15627 unsigned cH32 = MRI.createVirtualRegister(RC);
15628 unsigned cc = MRI.createVirtualRegister(RC);
15629 // cl := cmp src_lo, lo
15630 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15631 .addReg(SrcLoReg).addReg(t4L);
15632 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15633 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15634 // ch := cmp src_hi, hi
15635 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15636 .addReg(SrcHiReg).addReg(t4H);
15637 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15638 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15639 // cc := if (src_hi == hi) ? cl : ch;
15640 if (Subtarget->hasCMov()) {
15641 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15642 .addReg(cH32).addReg(cL32);
15644 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15645 .addReg(cH32).addReg(cL32)
15646 .addImm(X86::COND_E);
15647 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15649 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15650 if (Subtarget->hasCMov()) {
15651 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15652 .addReg(SrcLoReg).addReg(t4L);
15653 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15654 .addReg(SrcHiReg).addReg(t4H);
15656 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15657 .addReg(SrcLoReg).addReg(t4L)
15658 .addImm(X86::COND_NE);
15659 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15660 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15661 // 2nd CMOV lowering.
15662 mainMBB->addLiveIn(X86::EFLAGS);
15663 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15664 .addReg(SrcHiReg).addReg(t4H)
15665 .addImm(X86::COND_NE);
15666 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15667 // Replace the original PHI node as mainMBB is changed after CMOV
15669 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15670 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15671 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15672 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15673 PhiL->eraseFromParent();
15674 PhiH->eraseFromParent();
15678 case X86::ATOMSWAP6432: {
15680 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15681 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15682 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15687 // Copy EDX:EAX back from HiReg:LoReg
15688 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15689 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15690 // Copy ECX:EBX from t1H:t1L
15691 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15692 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15694 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15695 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15696 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15698 NewMO.setIsKill(false);
15699 MIB.addOperand(NewMO);
15701 MIB.setMemRefs(MMOBegin, MMOEnd);
15703 // Copy EDX:EAX back to t3H:t3L
15704 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15705 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15707 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15709 mainMBB->addSuccessor(origMainMBB);
15710 mainMBB->addSuccessor(sinkMBB);
15713 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15714 TII->get(TargetOpcode::COPY), DstLoReg)
15716 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15717 TII->get(TargetOpcode::COPY), DstHiReg)
15720 MI->eraseFromParent();
15724 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15725 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15726 // in the .td file.
15727 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15728 const TargetInstrInfo *TII) {
15730 switch (MI->getOpcode()) {
15731 default: llvm_unreachable("illegal opcode!");
15732 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15733 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15734 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15735 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15736 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15737 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15738 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15739 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15742 DebugLoc dl = MI->getDebugLoc();
15743 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15745 unsigned NumArgs = MI->getNumOperands();
15746 for (unsigned i = 1; i < NumArgs; ++i) {
15747 MachineOperand &Op = MI->getOperand(i);
15748 if (!(Op.isReg() && Op.isImplicit()))
15749 MIB.addOperand(Op);
15751 if (MI->hasOneMemOperand())
15752 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15754 BuildMI(*BB, MI, dl,
15755 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15756 .addReg(X86::XMM0);
15758 MI->eraseFromParent();
15762 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15763 // defs in an instruction pattern
15764 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15765 const TargetInstrInfo *TII) {
15767 switch (MI->getOpcode()) {
15768 default: llvm_unreachable("illegal opcode!");
15769 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15770 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15771 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15772 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15773 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15774 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15775 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15776 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15779 DebugLoc dl = MI->getDebugLoc();
15780 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15782 unsigned NumArgs = MI->getNumOperands(); // remove the results
15783 for (unsigned i = 1; i < NumArgs; ++i) {
15784 MachineOperand &Op = MI->getOperand(i);
15785 if (!(Op.isReg() && Op.isImplicit()))
15786 MIB.addOperand(Op);
15788 if (MI->hasOneMemOperand())
15789 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15791 BuildMI(*BB, MI, dl,
15792 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15795 MI->eraseFromParent();
15799 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15800 const TargetInstrInfo *TII,
15801 const X86Subtarget* Subtarget) {
15802 DebugLoc dl = MI->getDebugLoc();
15804 // Address into RAX/EAX, other two args into ECX, EDX.
15805 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15806 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15807 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15808 for (int i = 0; i < X86::AddrNumOperands; ++i)
15809 MIB.addOperand(MI->getOperand(i));
15811 unsigned ValOps = X86::AddrNumOperands;
15812 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15813 .addReg(MI->getOperand(ValOps).getReg());
15814 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15815 .addReg(MI->getOperand(ValOps+1).getReg());
15817 // The instruction doesn't actually take any operands though.
15818 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15820 MI->eraseFromParent(); // The pseudo is gone now.
15824 MachineBasicBlock *
15825 X86TargetLowering::EmitVAARG64WithCustomInserter(
15827 MachineBasicBlock *MBB) const {
15828 // Emit va_arg instruction on X86-64.
15830 // Operands to this pseudo-instruction:
15831 // 0 ) Output : destination address (reg)
15832 // 1-5) Input : va_list address (addr, i64mem)
15833 // 6 ) ArgSize : Size (in bytes) of vararg type
15834 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15835 // 8 ) Align : Alignment of type
15836 // 9 ) EFLAGS (implicit-def)
15838 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15839 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15841 unsigned DestReg = MI->getOperand(0).getReg();
15842 MachineOperand &Base = MI->getOperand(1);
15843 MachineOperand &Scale = MI->getOperand(2);
15844 MachineOperand &Index = MI->getOperand(3);
15845 MachineOperand &Disp = MI->getOperand(4);
15846 MachineOperand &Segment = MI->getOperand(5);
15847 unsigned ArgSize = MI->getOperand(6).getImm();
15848 unsigned ArgMode = MI->getOperand(7).getImm();
15849 unsigned Align = MI->getOperand(8).getImm();
15851 // Memory Reference
15852 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15853 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15854 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15856 // Machine Information
15857 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15858 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15859 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15860 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15861 DebugLoc DL = MI->getDebugLoc();
15863 // struct va_list {
15866 // i64 overflow_area (address)
15867 // i64 reg_save_area (address)
15869 // sizeof(va_list) = 24
15870 // alignment(va_list) = 8
15872 unsigned TotalNumIntRegs = 6;
15873 unsigned TotalNumXMMRegs = 8;
15874 bool UseGPOffset = (ArgMode == 1);
15875 bool UseFPOffset = (ArgMode == 2);
15876 unsigned MaxOffset = TotalNumIntRegs * 8 +
15877 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15879 /* Align ArgSize to a multiple of 8 */
15880 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15881 bool NeedsAlign = (Align > 8);
15883 MachineBasicBlock *thisMBB = MBB;
15884 MachineBasicBlock *overflowMBB;
15885 MachineBasicBlock *offsetMBB;
15886 MachineBasicBlock *endMBB;
15888 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15889 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15890 unsigned OffsetReg = 0;
15892 if (!UseGPOffset && !UseFPOffset) {
15893 // If we only pull from the overflow region, we don't create a branch.
15894 // We don't need to alter control flow.
15895 OffsetDestReg = 0; // unused
15896 OverflowDestReg = DestReg;
15898 offsetMBB = nullptr;
15899 overflowMBB = thisMBB;
15902 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15903 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15904 // If not, pull from overflow_area. (branch to overflowMBB)
15909 // offsetMBB overflowMBB
15914 // Registers for the PHI in endMBB
15915 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15916 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15918 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15919 MachineFunction *MF = MBB->getParent();
15920 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15921 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15922 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15924 MachineFunction::iterator MBBIter = MBB;
15927 // Insert the new basic blocks
15928 MF->insert(MBBIter, offsetMBB);
15929 MF->insert(MBBIter, overflowMBB);
15930 MF->insert(MBBIter, endMBB);
15932 // Transfer the remainder of MBB and its successor edges to endMBB.
15933 endMBB->splice(endMBB->begin(), thisMBB,
15934 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15935 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15937 // Make offsetMBB and overflowMBB successors of thisMBB
15938 thisMBB->addSuccessor(offsetMBB);
15939 thisMBB->addSuccessor(overflowMBB);
15941 // endMBB is a successor of both offsetMBB and overflowMBB
15942 offsetMBB->addSuccessor(endMBB);
15943 overflowMBB->addSuccessor(endMBB);
15945 // Load the offset value into a register
15946 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15947 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15951 .addDisp(Disp, UseFPOffset ? 4 : 0)
15952 .addOperand(Segment)
15953 .setMemRefs(MMOBegin, MMOEnd);
15955 // Check if there is enough room left to pull this argument.
15956 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15958 .addImm(MaxOffset + 8 - ArgSizeA8);
15960 // Branch to "overflowMBB" if offset >= max
15961 // Fall through to "offsetMBB" otherwise
15962 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15963 .addMBB(overflowMBB);
15966 // In offsetMBB, emit code to use the reg_save_area.
15968 assert(OffsetReg != 0);
15970 // Read the reg_save_area address.
15971 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15972 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15977 .addOperand(Segment)
15978 .setMemRefs(MMOBegin, MMOEnd);
15980 // Zero-extend the offset
15981 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15982 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15985 .addImm(X86::sub_32bit);
15987 // Add the offset to the reg_save_area to get the final address.
15988 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15989 .addReg(OffsetReg64)
15990 .addReg(RegSaveReg);
15992 // Compute the offset for the next argument
15993 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15994 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15996 .addImm(UseFPOffset ? 16 : 8);
15998 // Store it back into the va_list.
15999 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16003 .addDisp(Disp, UseFPOffset ? 4 : 0)
16004 .addOperand(Segment)
16005 .addReg(NextOffsetReg)
16006 .setMemRefs(MMOBegin, MMOEnd);
16009 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16014 // Emit code to use overflow area
16017 // Load the overflow_area address into a register.
16018 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16019 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16024 .addOperand(Segment)
16025 .setMemRefs(MMOBegin, MMOEnd);
16027 // If we need to align it, do so. Otherwise, just copy the address
16028 // to OverflowDestReg.
16030 // Align the overflow address
16031 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16032 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16034 // aligned_addr = (addr + (align-1)) & ~(align-1)
16035 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16036 .addReg(OverflowAddrReg)
16039 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16041 .addImm(~(uint64_t)(Align-1));
16043 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16044 .addReg(OverflowAddrReg);
16047 // Compute the next overflow address after this argument.
16048 // (the overflow address should be kept 8-byte aligned)
16049 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16050 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16051 .addReg(OverflowDestReg)
16052 .addImm(ArgSizeA8);
16054 // Store the new overflow address.
16055 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16060 .addOperand(Segment)
16061 .addReg(NextAddrReg)
16062 .setMemRefs(MMOBegin, MMOEnd);
16064 // If we branched, emit the PHI to the front of endMBB.
16066 BuildMI(*endMBB, endMBB->begin(), DL,
16067 TII->get(X86::PHI), DestReg)
16068 .addReg(OffsetDestReg).addMBB(offsetMBB)
16069 .addReg(OverflowDestReg).addMBB(overflowMBB);
16072 // Erase the pseudo instruction
16073 MI->eraseFromParent();
16078 MachineBasicBlock *
16079 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16081 MachineBasicBlock *MBB) const {
16082 // Emit code to save XMM registers to the stack. The ABI says that the
16083 // number of registers to save is given in %al, so it's theoretically
16084 // possible to do an indirect jump trick to avoid saving all of them,
16085 // however this code takes a simpler approach and just executes all
16086 // of the stores if %al is non-zero. It's less code, and it's probably
16087 // easier on the hardware branch predictor, and stores aren't all that
16088 // expensive anyway.
16090 // Create the new basic blocks. One block contains all the XMM stores,
16091 // and one block is the final destination regardless of whether any
16092 // stores were performed.
16093 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16094 MachineFunction *F = MBB->getParent();
16095 MachineFunction::iterator MBBIter = MBB;
16097 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16098 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16099 F->insert(MBBIter, XMMSaveMBB);
16100 F->insert(MBBIter, EndMBB);
16102 // Transfer the remainder of MBB and its successor edges to EndMBB.
16103 EndMBB->splice(EndMBB->begin(), MBB,
16104 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16105 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16107 // The original block will now fall through to the XMM save block.
16108 MBB->addSuccessor(XMMSaveMBB);
16109 // The XMMSaveMBB will fall through to the end block.
16110 XMMSaveMBB->addSuccessor(EndMBB);
16112 // Now add the instructions.
16113 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16114 DebugLoc DL = MI->getDebugLoc();
16116 unsigned CountReg = MI->getOperand(0).getReg();
16117 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16118 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16120 if (!Subtarget->isTargetWin64()) {
16121 // If %al is 0, branch around the XMM save block.
16122 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16123 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16124 MBB->addSuccessor(EndMBB);
16127 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16128 // that was just emitted, but clearly shouldn't be "saved".
16129 assert((MI->getNumOperands() <= 3 ||
16130 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16131 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16132 && "Expected last argument to be EFLAGS");
16133 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16134 // In the XMM save block, save all the XMM argument registers.
16135 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16136 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16137 MachineMemOperand *MMO =
16138 F->getMachineMemOperand(
16139 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16140 MachineMemOperand::MOStore,
16141 /*Size=*/16, /*Align=*/16);
16142 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16143 .addFrameIndex(RegSaveFrameIndex)
16144 .addImm(/*Scale=*/1)
16145 .addReg(/*IndexReg=*/0)
16146 .addImm(/*Disp=*/Offset)
16147 .addReg(/*Segment=*/0)
16148 .addReg(MI->getOperand(i).getReg())
16149 .addMemOperand(MMO);
16152 MI->eraseFromParent(); // The pseudo instruction is gone now.
16157 // The EFLAGS operand of SelectItr might be missing a kill marker
16158 // because there were multiple uses of EFLAGS, and ISel didn't know
16159 // which to mark. Figure out whether SelectItr should have had a
16160 // kill marker, and set it if it should. Returns the correct kill
16162 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16163 MachineBasicBlock* BB,
16164 const TargetRegisterInfo* TRI) {
16165 // Scan forward through BB for a use/def of EFLAGS.
16166 MachineBasicBlock::iterator miI(std::next(SelectItr));
16167 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16168 const MachineInstr& mi = *miI;
16169 if (mi.readsRegister(X86::EFLAGS))
16171 if (mi.definesRegister(X86::EFLAGS))
16172 break; // Should have kill-flag - update below.
16175 // If we hit the end of the block, check whether EFLAGS is live into a
16177 if (miI == BB->end()) {
16178 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16179 sEnd = BB->succ_end();
16180 sItr != sEnd; ++sItr) {
16181 MachineBasicBlock* succ = *sItr;
16182 if (succ->isLiveIn(X86::EFLAGS))
16187 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16188 // out. SelectMI should have a kill flag on EFLAGS.
16189 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16193 MachineBasicBlock *
16194 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16195 MachineBasicBlock *BB) const {
16196 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16197 DebugLoc DL = MI->getDebugLoc();
16199 // To "insert" a SELECT_CC instruction, we actually have to insert the
16200 // diamond control-flow pattern. The incoming instruction knows the
16201 // destination vreg to set, the condition code register to branch on, the
16202 // true/false values to select between, and a branch opcode to use.
16203 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16204 MachineFunction::iterator It = BB;
16210 // cmpTY ccX, r1, r2
16212 // fallthrough --> copy0MBB
16213 MachineBasicBlock *thisMBB = BB;
16214 MachineFunction *F = BB->getParent();
16215 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16216 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16217 F->insert(It, copy0MBB);
16218 F->insert(It, sinkMBB);
16220 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16221 // live into the sink and copy blocks.
16222 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16223 if (!MI->killsRegister(X86::EFLAGS) &&
16224 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16225 copy0MBB->addLiveIn(X86::EFLAGS);
16226 sinkMBB->addLiveIn(X86::EFLAGS);
16229 // Transfer the remainder of BB and its successor edges to sinkMBB.
16230 sinkMBB->splice(sinkMBB->begin(), BB,
16231 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16232 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16234 // Add the true and fallthrough blocks as its successors.
16235 BB->addSuccessor(copy0MBB);
16236 BB->addSuccessor(sinkMBB);
16238 // Create the conditional branch instruction.
16240 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16241 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16244 // %FalseValue = ...
16245 // # fallthrough to sinkMBB
16246 copy0MBB->addSuccessor(sinkMBB);
16249 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16251 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16252 TII->get(X86::PHI), MI->getOperand(0).getReg())
16253 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16254 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16256 MI->eraseFromParent(); // The pseudo instruction is gone now.
16260 MachineBasicBlock *
16261 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16262 bool Is64Bit) const {
16263 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16264 DebugLoc DL = MI->getDebugLoc();
16265 MachineFunction *MF = BB->getParent();
16266 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16268 assert(MF->shouldSplitStack());
16270 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16271 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16274 // ... [Till the alloca]
16275 // If stacklet is not large enough, jump to mallocMBB
16278 // Allocate by subtracting from RSP
16279 // Jump to continueMBB
16282 // Allocate by call to runtime
16286 // [rest of original BB]
16289 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16290 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16291 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16293 MachineRegisterInfo &MRI = MF->getRegInfo();
16294 const TargetRegisterClass *AddrRegClass =
16295 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16297 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16298 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16299 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16300 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16301 sizeVReg = MI->getOperand(1).getReg(),
16302 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16304 MachineFunction::iterator MBBIter = BB;
16307 MF->insert(MBBIter, bumpMBB);
16308 MF->insert(MBBIter, mallocMBB);
16309 MF->insert(MBBIter, continueMBB);
16311 continueMBB->splice(continueMBB->begin(), BB,
16312 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16313 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16315 // Add code to the main basic block to check if the stack limit has been hit,
16316 // and if so, jump to mallocMBB otherwise to bumpMBB.
16317 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16318 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16319 .addReg(tmpSPVReg).addReg(sizeVReg);
16320 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16321 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16322 .addReg(SPLimitVReg);
16323 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16325 // bumpMBB simply decreases the stack pointer, since we know the current
16326 // stacklet has enough space.
16327 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16328 .addReg(SPLimitVReg);
16329 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16330 .addReg(SPLimitVReg);
16331 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16333 // Calls into a routine in libgcc to allocate more space from the heap.
16334 const uint32_t *RegMask =
16335 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16337 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16339 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16340 .addExternalSymbol("__morestack_allocate_stack_space")
16341 .addRegMask(RegMask)
16342 .addReg(X86::RDI, RegState::Implicit)
16343 .addReg(X86::RAX, RegState::ImplicitDefine);
16345 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16347 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16348 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16349 .addExternalSymbol("__morestack_allocate_stack_space")
16350 .addRegMask(RegMask)
16351 .addReg(X86::EAX, RegState::ImplicitDefine);
16355 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16358 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16359 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16360 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16362 // Set up the CFG correctly.
16363 BB->addSuccessor(bumpMBB);
16364 BB->addSuccessor(mallocMBB);
16365 mallocMBB->addSuccessor(continueMBB);
16366 bumpMBB->addSuccessor(continueMBB);
16368 // Take care of the PHI nodes.
16369 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16370 MI->getOperand(0).getReg())
16371 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16372 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16374 // Delete the original pseudo instruction.
16375 MI->eraseFromParent();
16378 return continueMBB;
16381 MachineBasicBlock *
16382 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16383 MachineBasicBlock *BB) const {
16384 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16385 DebugLoc DL = MI->getDebugLoc();
16387 assert(!Subtarget->isTargetMacho());
16389 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16390 // non-trivial part is impdef of ESP.
16392 if (Subtarget->isTargetWin64()) {
16393 if (Subtarget->isTargetCygMing()) {
16394 // ___chkstk(Mingw64):
16395 // Clobbers R10, R11, RAX and EFLAGS.
16397 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16398 .addExternalSymbol("___chkstk")
16399 .addReg(X86::RAX, RegState::Implicit)
16400 .addReg(X86::RSP, RegState::Implicit)
16401 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16402 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16403 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16405 // __chkstk(MSVCRT): does not update stack pointer.
16406 // Clobbers R10, R11 and EFLAGS.
16407 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16408 .addExternalSymbol("__chkstk")
16409 .addReg(X86::RAX, RegState::Implicit)
16410 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16411 // RAX has the offset to be subtracted from RSP.
16412 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16417 const char *StackProbeSymbol =
16418 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16420 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16421 .addExternalSymbol(StackProbeSymbol)
16422 .addReg(X86::EAX, RegState::Implicit)
16423 .addReg(X86::ESP, RegState::Implicit)
16424 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16425 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16426 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16429 MI->eraseFromParent(); // The pseudo instruction is gone now.
16433 MachineBasicBlock *
16434 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16435 MachineBasicBlock *BB) const {
16436 // This is pretty easy. We're taking the value that we received from
16437 // our load from the relocation, sticking it in either RDI (x86-64)
16438 // or EAX and doing an indirect call. The return value will then
16439 // be in the normal return register.
16440 const X86InstrInfo *TII
16441 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16442 DebugLoc DL = MI->getDebugLoc();
16443 MachineFunction *F = BB->getParent();
16445 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16446 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16448 // Get a register mask for the lowered call.
16449 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16450 // proper register mask.
16451 const uint32_t *RegMask =
16452 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16453 if (Subtarget->is64Bit()) {
16454 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16455 TII->get(X86::MOV64rm), X86::RDI)
16457 .addImm(0).addReg(0)
16458 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16459 MI->getOperand(3).getTargetFlags())
16461 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16462 addDirectMem(MIB, X86::RDI);
16463 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16464 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16465 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16466 TII->get(X86::MOV32rm), X86::EAX)
16468 .addImm(0).addReg(0)
16469 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16470 MI->getOperand(3).getTargetFlags())
16472 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16473 addDirectMem(MIB, X86::EAX);
16474 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16476 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16477 TII->get(X86::MOV32rm), X86::EAX)
16478 .addReg(TII->getGlobalBaseReg(F))
16479 .addImm(0).addReg(0)
16480 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16481 MI->getOperand(3).getTargetFlags())
16483 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16484 addDirectMem(MIB, X86::EAX);
16485 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16488 MI->eraseFromParent(); // The pseudo instruction is gone now.
16492 MachineBasicBlock *
16493 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16494 MachineBasicBlock *MBB) const {
16495 DebugLoc DL = MI->getDebugLoc();
16496 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16498 MachineFunction *MF = MBB->getParent();
16499 MachineRegisterInfo &MRI = MF->getRegInfo();
16501 const BasicBlock *BB = MBB->getBasicBlock();
16502 MachineFunction::iterator I = MBB;
16505 // Memory Reference
16506 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16507 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16510 unsigned MemOpndSlot = 0;
16512 unsigned CurOp = 0;
16514 DstReg = MI->getOperand(CurOp++).getReg();
16515 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16516 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16517 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16518 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16520 MemOpndSlot = CurOp;
16522 MVT PVT = getPointerTy();
16523 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16524 "Invalid Pointer Size!");
16526 // For v = setjmp(buf), we generate
16529 // buf[LabelOffset] = restoreMBB
16530 // SjLjSetup restoreMBB
16536 // v = phi(main, restore)
16541 MachineBasicBlock *thisMBB = MBB;
16542 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16543 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16544 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16545 MF->insert(I, mainMBB);
16546 MF->insert(I, sinkMBB);
16547 MF->push_back(restoreMBB);
16549 MachineInstrBuilder MIB;
16551 // Transfer the remainder of BB and its successor edges to sinkMBB.
16552 sinkMBB->splice(sinkMBB->begin(), MBB,
16553 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16554 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16557 unsigned PtrStoreOpc = 0;
16558 unsigned LabelReg = 0;
16559 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16560 Reloc::Model RM = getTargetMachine().getRelocationModel();
16561 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16562 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16564 // Prepare IP either in reg or imm.
16565 if (!UseImmLabel) {
16566 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16567 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16568 LabelReg = MRI.createVirtualRegister(PtrRC);
16569 if (Subtarget->is64Bit()) {
16570 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16574 .addMBB(restoreMBB)
16577 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16578 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16579 .addReg(XII->getGlobalBaseReg(MF))
16582 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16586 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16588 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16589 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16590 if (i == X86::AddrDisp)
16591 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16593 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16596 MIB.addReg(LabelReg);
16598 MIB.addMBB(restoreMBB);
16599 MIB.setMemRefs(MMOBegin, MMOEnd);
16601 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16602 .addMBB(restoreMBB);
16604 const X86RegisterInfo *RegInfo =
16605 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16606 MIB.addRegMask(RegInfo->getNoPreservedMask());
16607 thisMBB->addSuccessor(mainMBB);
16608 thisMBB->addSuccessor(restoreMBB);
16612 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16613 mainMBB->addSuccessor(sinkMBB);
16616 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16617 TII->get(X86::PHI), DstReg)
16618 .addReg(mainDstReg).addMBB(mainMBB)
16619 .addReg(restoreDstReg).addMBB(restoreMBB);
16622 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16623 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16624 restoreMBB->addSuccessor(sinkMBB);
16626 MI->eraseFromParent();
16630 MachineBasicBlock *
16631 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16632 MachineBasicBlock *MBB) const {
16633 DebugLoc DL = MI->getDebugLoc();
16634 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16636 MachineFunction *MF = MBB->getParent();
16637 MachineRegisterInfo &MRI = MF->getRegInfo();
16639 // Memory Reference
16640 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16641 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16643 MVT PVT = getPointerTy();
16644 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16645 "Invalid Pointer Size!");
16647 const TargetRegisterClass *RC =
16648 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16649 unsigned Tmp = MRI.createVirtualRegister(RC);
16650 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16651 const X86RegisterInfo *RegInfo =
16652 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16653 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16654 unsigned SP = RegInfo->getStackRegister();
16656 MachineInstrBuilder MIB;
16658 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16659 const int64_t SPOffset = 2 * PVT.getStoreSize();
16661 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16662 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16665 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16666 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16667 MIB.addOperand(MI->getOperand(i));
16668 MIB.setMemRefs(MMOBegin, MMOEnd);
16670 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16671 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16672 if (i == X86::AddrDisp)
16673 MIB.addDisp(MI->getOperand(i), LabelOffset);
16675 MIB.addOperand(MI->getOperand(i));
16677 MIB.setMemRefs(MMOBegin, MMOEnd);
16679 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16680 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16681 if (i == X86::AddrDisp)
16682 MIB.addDisp(MI->getOperand(i), SPOffset);
16684 MIB.addOperand(MI->getOperand(i));
16686 MIB.setMemRefs(MMOBegin, MMOEnd);
16688 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16690 MI->eraseFromParent();
16694 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16695 // accumulator loops. Writing back to the accumulator allows the coalescer
16696 // to remove extra copies in the loop.
16697 MachineBasicBlock *
16698 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16699 MachineBasicBlock *MBB) const {
16700 MachineOperand &AddendOp = MI->getOperand(3);
16702 // Bail out early if the addend isn't a register - we can't switch these.
16703 if (!AddendOp.isReg())
16706 MachineFunction &MF = *MBB->getParent();
16707 MachineRegisterInfo &MRI = MF.getRegInfo();
16709 // Check whether the addend is defined by a PHI:
16710 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16711 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16712 if (!AddendDef.isPHI())
16715 // Look for the following pattern:
16717 // %addend = phi [%entry, 0], [%loop, %result]
16719 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16723 // %addend = phi [%entry, 0], [%loop, %result]
16725 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16727 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16728 assert(AddendDef.getOperand(i).isReg());
16729 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16730 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16731 if (&PHISrcInst == MI) {
16732 // Found a matching instruction.
16733 unsigned NewFMAOpc = 0;
16734 switch (MI->getOpcode()) {
16735 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16736 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16737 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16738 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16739 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16740 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16741 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16742 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16743 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16744 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16745 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16746 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16747 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16748 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16749 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16750 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16751 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16752 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16753 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16754 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16755 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16756 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16757 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16758 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16759 default: llvm_unreachable("Unrecognized FMA variant.");
16762 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16763 MachineInstrBuilder MIB =
16764 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16765 .addOperand(MI->getOperand(0))
16766 .addOperand(MI->getOperand(3))
16767 .addOperand(MI->getOperand(2))
16768 .addOperand(MI->getOperand(1));
16769 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16770 MI->eraseFromParent();
16777 MachineBasicBlock *
16778 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16779 MachineBasicBlock *BB) const {
16780 switch (MI->getOpcode()) {
16781 default: llvm_unreachable("Unexpected instr type to insert");
16782 case X86::TAILJMPd64:
16783 case X86::TAILJMPr64:
16784 case X86::TAILJMPm64:
16785 llvm_unreachable("TAILJMP64 would not be touched here.");
16786 case X86::TCRETURNdi64:
16787 case X86::TCRETURNri64:
16788 case X86::TCRETURNmi64:
16790 case X86::WIN_ALLOCA:
16791 return EmitLoweredWinAlloca(MI, BB);
16792 case X86::SEG_ALLOCA_32:
16793 return EmitLoweredSegAlloca(MI, BB, false);
16794 case X86::SEG_ALLOCA_64:
16795 return EmitLoweredSegAlloca(MI, BB, true);
16796 case X86::TLSCall_32:
16797 case X86::TLSCall_64:
16798 return EmitLoweredTLSCall(MI, BB);
16799 case X86::CMOV_GR8:
16800 case X86::CMOV_FR32:
16801 case X86::CMOV_FR64:
16802 case X86::CMOV_V4F32:
16803 case X86::CMOV_V2F64:
16804 case X86::CMOV_V2I64:
16805 case X86::CMOV_V8F32:
16806 case X86::CMOV_V4F64:
16807 case X86::CMOV_V4I64:
16808 case X86::CMOV_V16F32:
16809 case X86::CMOV_V8F64:
16810 case X86::CMOV_V8I64:
16811 case X86::CMOV_GR16:
16812 case X86::CMOV_GR32:
16813 case X86::CMOV_RFP32:
16814 case X86::CMOV_RFP64:
16815 case X86::CMOV_RFP80:
16816 return EmitLoweredSelect(MI, BB);
16818 case X86::FP32_TO_INT16_IN_MEM:
16819 case X86::FP32_TO_INT32_IN_MEM:
16820 case X86::FP32_TO_INT64_IN_MEM:
16821 case X86::FP64_TO_INT16_IN_MEM:
16822 case X86::FP64_TO_INT32_IN_MEM:
16823 case X86::FP64_TO_INT64_IN_MEM:
16824 case X86::FP80_TO_INT16_IN_MEM:
16825 case X86::FP80_TO_INT32_IN_MEM:
16826 case X86::FP80_TO_INT64_IN_MEM: {
16827 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16828 DebugLoc DL = MI->getDebugLoc();
16830 // Change the floating point control register to use "round towards zero"
16831 // mode when truncating to an integer value.
16832 MachineFunction *F = BB->getParent();
16833 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16834 addFrameReference(BuildMI(*BB, MI, DL,
16835 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16837 // Load the old value of the high byte of the control word...
16839 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16840 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16843 // Set the high part to be round to zero...
16844 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16847 // Reload the modified control word now...
16848 addFrameReference(BuildMI(*BB, MI, DL,
16849 TII->get(X86::FLDCW16m)), CWFrameIdx);
16851 // Restore the memory image of control word to original value
16852 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16855 // Get the X86 opcode to use.
16857 switch (MI->getOpcode()) {
16858 default: llvm_unreachable("illegal opcode!");
16859 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16860 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16861 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16862 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16863 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16864 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16865 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16866 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16867 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16871 MachineOperand &Op = MI->getOperand(0);
16873 AM.BaseType = X86AddressMode::RegBase;
16874 AM.Base.Reg = Op.getReg();
16876 AM.BaseType = X86AddressMode::FrameIndexBase;
16877 AM.Base.FrameIndex = Op.getIndex();
16879 Op = MI->getOperand(1);
16881 AM.Scale = Op.getImm();
16882 Op = MI->getOperand(2);
16884 AM.IndexReg = Op.getImm();
16885 Op = MI->getOperand(3);
16886 if (Op.isGlobal()) {
16887 AM.GV = Op.getGlobal();
16889 AM.Disp = Op.getImm();
16891 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16892 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16894 // Reload the original control word now.
16895 addFrameReference(BuildMI(*BB, MI, DL,
16896 TII->get(X86::FLDCW16m)), CWFrameIdx);
16898 MI->eraseFromParent(); // The pseudo instruction is gone now.
16901 // String/text processing lowering.
16902 case X86::PCMPISTRM128REG:
16903 case X86::VPCMPISTRM128REG:
16904 case X86::PCMPISTRM128MEM:
16905 case X86::VPCMPISTRM128MEM:
16906 case X86::PCMPESTRM128REG:
16907 case X86::VPCMPESTRM128REG:
16908 case X86::PCMPESTRM128MEM:
16909 case X86::VPCMPESTRM128MEM:
16910 assert(Subtarget->hasSSE42() &&
16911 "Target must have SSE4.2 or AVX features enabled");
16912 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16914 // String/text processing lowering.
16915 case X86::PCMPISTRIREG:
16916 case X86::VPCMPISTRIREG:
16917 case X86::PCMPISTRIMEM:
16918 case X86::VPCMPISTRIMEM:
16919 case X86::PCMPESTRIREG:
16920 case X86::VPCMPESTRIREG:
16921 case X86::PCMPESTRIMEM:
16922 case X86::VPCMPESTRIMEM:
16923 assert(Subtarget->hasSSE42() &&
16924 "Target must have SSE4.2 or AVX features enabled");
16925 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16927 // Thread synchronization.
16929 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16933 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16935 // Atomic Lowering.
16936 case X86::ATOMAND8:
16937 case X86::ATOMAND16:
16938 case X86::ATOMAND32:
16939 case X86::ATOMAND64:
16942 case X86::ATOMOR16:
16943 case X86::ATOMOR32:
16944 case X86::ATOMOR64:
16946 case X86::ATOMXOR16:
16947 case X86::ATOMXOR8:
16948 case X86::ATOMXOR32:
16949 case X86::ATOMXOR64:
16951 case X86::ATOMNAND8:
16952 case X86::ATOMNAND16:
16953 case X86::ATOMNAND32:
16954 case X86::ATOMNAND64:
16956 case X86::ATOMMAX8:
16957 case X86::ATOMMAX16:
16958 case X86::ATOMMAX32:
16959 case X86::ATOMMAX64:
16961 case X86::ATOMMIN8:
16962 case X86::ATOMMIN16:
16963 case X86::ATOMMIN32:
16964 case X86::ATOMMIN64:
16966 case X86::ATOMUMAX8:
16967 case X86::ATOMUMAX16:
16968 case X86::ATOMUMAX32:
16969 case X86::ATOMUMAX64:
16971 case X86::ATOMUMIN8:
16972 case X86::ATOMUMIN16:
16973 case X86::ATOMUMIN32:
16974 case X86::ATOMUMIN64:
16975 return EmitAtomicLoadArith(MI, BB);
16977 // This group does 64-bit operations on a 32-bit host.
16978 case X86::ATOMAND6432:
16979 case X86::ATOMOR6432:
16980 case X86::ATOMXOR6432:
16981 case X86::ATOMNAND6432:
16982 case X86::ATOMADD6432:
16983 case X86::ATOMSUB6432:
16984 case X86::ATOMMAX6432:
16985 case X86::ATOMMIN6432:
16986 case X86::ATOMUMAX6432:
16987 case X86::ATOMUMIN6432:
16988 case X86::ATOMSWAP6432:
16989 return EmitAtomicLoadArith6432(MI, BB);
16991 case X86::VASTART_SAVE_XMM_REGS:
16992 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16994 case X86::VAARG_64:
16995 return EmitVAARG64WithCustomInserter(MI, BB);
16997 case X86::EH_SjLj_SetJmp32:
16998 case X86::EH_SjLj_SetJmp64:
16999 return emitEHSjLjSetJmp(MI, BB);
17001 case X86::EH_SjLj_LongJmp32:
17002 case X86::EH_SjLj_LongJmp64:
17003 return emitEHSjLjLongJmp(MI, BB);
17005 case TargetOpcode::STACKMAP:
17006 case TargetOpcode::PATCHPOINT:
17007 return emitPatchPoint(MI, BB);
17009 case X86::VFMADDPDr213r:
17010 case X86::VFMADDPSr213r:
17011 case X86::VFMADDSDr213r:
17012 case X86::VFMADDSSr213r:
17013 case X86::VFMSUBPDr213r:
17014 case X86::VFMSUBPSr213r:
17015 case X86::VFMSUBSDr213r:
17016 case X86::VFMSUBSSr213r:
17017 case X86::VFNMADDPDr213r:
17018 case X86::VFNMADDPSr213r:
17019 case X86::VFNMADDSDr213r:
17020 case X86::VFNMADDSSr213r:
17021 case X86::VFNMSUBPDr213r:
17022 case X86::VFNMSUBPSr213r:
17023 case X86::VFNMSUBSDr213r:
17024 case X86::VFNMSUBSSr213r:
17025 case X86::VFMADDPDr213rY:
17026 case X86::VFMADDPSr213rY:
17027 case X86::VFMSUBPDr213rY:
17028 case X86::VFMSUBPSr213rY:
17029 case X86::VFNMADDPDr213rY:
17030 case X86::VFNMADDPSr213rY:
17031 case X86::VFNMSUBPDr213rY:
17032 case X86::VFNMSUBPSr213rY:
17033 return emitFMA3Instr(MI, BB);
17037 //===----------------------------------------------------------------------===//
17038 // X86 Optimization Hooks
17039 //===----------------------------------------------------------------------===//
17041 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
17044 const SelectionDAG &DAG,
17045 unsigned Depth) const {
17046 unsigned BitWidth = KnownZero.getBitWidth();
17047 unsigned Opc = Op.getOpcode();
17048 assert((Opc >= ISD::BUILTIN_OP_END ||
17049 Opc == ISD::INTRINSIC_WO_CHAIN ||
17050 Opc == ISD::INTRINSIC_W_CHAIN ||
17051 Opc == ISD::INTRINSIC_VOID) &&
17052 "Should use MaskedValueIsZero if you don't know whether Op"
17053 " is a target node!");
17055 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17069 // These nodes' second result is a boolean.
17070 if (Op.getResNo() == 0)
17073 case X86ISD::SETCC:
17074 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17076 case ISD::INTRINSIC_WO_CHAIN: {
17077 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17078 unsigned NumLoBits = 0;
17081 case Intrinsic::x86_sse_movmsk_ps:
17082 case Intrinsic::x86_avx_movmsk_ps_256:
17083 case Intrinsic::x86_sse2_movmsk_pd:
17084 case Intrinsic::x86_avx_movmsk_pd_256:
17085 case Intrinsic::x86_mmx_pmovmskb:
17086 case Intrinsic::x86_sse2_pmovmskb_128:
17087 case Intrinsic::x86_avx2_pmovmskb: {
17088 // High bits of movmskp{s|d}, pmovmskb are known zero.
17090 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17091 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17092 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17093 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17094 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17095 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17096 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17097 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17099 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17108 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17110 const SelectionDAG &,
17111 unsigned Depth) const {
17112 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17113 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17114 return Op.getValueType().getScalarType().getSizeInBits();
17120 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17121 /// node is a GlobalAddress + offset.
17122 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17123 const GlobalValue* &GA,
17124 int64_t &Offset) const {
17125 if (N->getOpcode() == X86ISD::Wrapper) {
17126 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17127 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17128 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17132 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17135 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17136 /// same as extracting the high 128-bit part of 256-bit vector and then
17137 /// inserting the result into the low part of a new 256-bit vector
17138 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17139 EVT VT = SVOp->getValueType(0);
17140 unsigned NumElems = VT.getVectorNumElements();
17142 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17143 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17144 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17145 SVOp->getMaskElt(j) >= 0)
17151 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17152 /// same as extracting the low 128-bit part of 256-bit vector and then
17153 /// inserting the result into the high part of a new 256-bit vector
17154 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17155 EVT VT = SVOp->getValueType(0);
17156 unsigned NumElems = VT.getVectorNumElements();
17158 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17159 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17160 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17161 SVOp->getMaskElt(j) >= 0)
17167 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17168 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17169 TargetLowering::DAGCombinerInfo &DCI,
17170 const X86Subtarget* Subtarget) {
17172 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17173 SDValue V1 = SVOp->getOperand(0);
17174 SDValue V2 = SVOp->getOperand(1);
17175 EVT VT = SVOp->getValueType(0);
17176 unsigned NumElems = VT.getVectorNumElements();
17178 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17179 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17183 // V UNDEF BUILD_VECTOR UNDEF
17185 // CONCAT_VECTOR CONCAT_VECTOR
17188 // RESULT: V + zero extended
17190 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17191 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17192 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17195 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17198 // To match the shuffle mask, the first half of the mask should
17199 // be exactly the first vector, and all the rest a splat with the
17200 // first element of the second one.
17201 for (unsigned i = 0; i != NumElems/2; ++i)
17202 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17203 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17206 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17207 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17208 if (Ld->hasNUsesOfValue(1, 0)) {
17209 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17210 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17212 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17214 Ld->getPointerInfo(),
17215 Ld->getAlignment(),
17216 false/*isVolatile*/, true/*ReadMem*/,
17217 false/*WriteMem*/);
17219 // Make sure the newly-created LOAD is in the same position as Ld in
17220 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17221 // and update uses of Ld's output chain to use the TokenFactor.
17222 if (Ld->hasAnyUseOfValue(1)) {
17223 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17224 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17225 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17226 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17227 SDValue(ResNode.getNode(), 1));
17230 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17234 // Emit a zeroed vector and insert the desired subvector on its
17236 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17237 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17238 return DCI.CombineTo(N, InsV);
17241 //===--------------------------------------------------------------------===//
17242 // Combine some shuffles into subvector extracts and inserts:
17245 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17246 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17247 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17248 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17249 return DCI.CombineTo(N, InsV);
17252 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17253 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17254 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17255 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17256 return DCI.CombineTo(N, InsV);
17262 /// PerformShuffleCombine - Performs several different shuffle combines.
17263 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17264 TargetLowering::DAGCombinerInfo &DCI,
17265 const X86Subtarget *Subtarget) {
17267 EVT VT = N->getValueType(0);
17269 // Don't create instructions with illegal types after legalize types has run.
17270 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17271 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17274 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17275 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17276 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17277 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17279 // Only handle 128 wide vector from here on.
17280 if (!VT.is128BitVector())
17283 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17284 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17285 // consecutive, non-overlapping, and in the right order.
17286 SmallVector<SDValue, 16> Elts;
17287 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17288 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17290 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17293 /// PerformTruncateCombine - Converts truncate operation to
17294 /// a sequence of vector shuffle operations.
17295 /// It is possible when we truncate 256-bit vector to 128-bit vector
17296 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17297 TargetLowering::DAGCombinerInfo &DCI,
17298 const X86Subtarget *Subtarget) {
17302 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17303 /// specific shuffle of a load can be folded into a single element load.
17304 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17305 /// shuffles have been customed lowered so we need to handle those here.
17306 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17307 TargetLowering::DAGCombinerInfo &DCI) {
17308 if (DCI.isBeforeLegalizeOps())
17311 SDValue InVec = N->getOperand(0);
17312 SDValue EltNo = N->getOperand(1);
17314 if (!isa<ConstantSDNode>(EltNo))
17317 EVT VT = InVec.getValueType();
17319 bool HasShuffleIntoBitcast = false;
17320 if (InVec.getOpcode() == ISD::BITCAST) {
17321 // Don't duplicate a load with other uses.
17322 if (!InVec.hasOneUse())
17324 EVT BCVT = InVec.getOperand(0).getValueType();
17325 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17327 InVec = InVec.getOperand(0);
17328 HasShuffleIntoBitcast = true;
17331 if (!isTargetShuffle(InVec.getOpcode()))
17334 // Don't duplicate a load with other uses.
17335 if (!InVec.hasOneUse())
17338 SmallVector<int, 16> ShuffleMask;
17340 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17344 // Select the input vector, guarding against out of range extract vector.
17345 unsigned NumElems = VT.getVectorNumElements();
17346 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17347 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17348 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17349 : InVec.getOperand(1);
17351 // If inputs to shuffle are the same for both ops, then allow 2 uses
17352 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17354 if (LdNode.getOpcode() == ISD::BITCAST) {
17355 // Don't duplicate a load with other uses.
17356 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17359 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17360 LdNode = LdNode.getOperand(0);
17363 if (!ISD::isNormalLoad(LdNode.getNode()))
17366 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17368 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17371 if (HasShuffleIntoBitcast) {
17372 // If there's a bitcast before the shuffle, check if the load type and
17373 // alignment is valid.
17374 unsigned Align = LN0->getAlignment();
17375 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17376 unsigned NewAlign = TLI.getDataLayout()->
17377 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17379 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17383 // All checks match so transform back to vector_shuffle so that DAG combiner
17384 // can finish the job
17387 // Create shuffle node taking into account the case that its a unary shuffle
17388 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17389 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17390 InVec.getOperand(0), Shuffle,
17392 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17393 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17397 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17398 /// generation and convert it from being a bunch of shuffles and extracts
17399 /// to a simple store and scalar loads to extract the elements.
17400 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17401 TargetLowering::DAGCombinerInfo &DCI) {
17402 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17403 if (NewOp.getNode())
17406 SDValue InputVector = N->getOperand(0);
17408 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17409 // from mmx to v2i32 has a single usage.
17410 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17411 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17412 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17413 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17414 N->getValueType(0),
17415 InputVector.getNode()->getOperand(0));
17417 // Only operate on vectors of 4 elements, where the alternative shuffling
17418 // gets to be more expensive.
17419 if (InputVector.getValueType() != MVT::v4i32)
17422 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17423 // single use which is a sign-extend or zero-extend, and all elements are
17425 SmallVector<SDNode *, 4> Uses;
17426 unsigned ExtractedElements = 0;
17427 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17428 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17429 if (UI.getUse().getResNo() != InputVector.getResNo())
17432 SDNode *Extract = *UI;
17433 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17436 if (Extract->getValueType(0) != MVT::i32)
17438 if (!Extract->hasOneUse())
17440 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17441 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17443 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17446 // Record which element was extracted.
17447 ExtractedElements |=
17448 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17450 Uses.push_back(Extract);
17453 // If not all the elements were used, this may not be worthwhile.
17454 if (ExtractedElements != 15)
17457 // Ok, we've now decided to do the transformation.
17458 SDLoc dl(InputVector);
17460 // Store the value to a temporary stack slot.
17461 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17462 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17463 MachinePointerInfo(), false, false, 0);
17465 // Replace each use (extract) with a load of the appropriate element.
17466 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17467 UE = Uses.end(); UI != UE; ++UI) {
17468 SDNode *Extract = *UI;
17470 // cOMpute the element's address.
17471 SDValue Idx = Extract->getOperand(1);
17473 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17474 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17475 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17476 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17478 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17479 StackPtr, OffsetVal);
17481 // Load the scalar.
17482 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17483 ScalarAddr, MachinePointerInfo(),
17484 false, false, false, 0);
17486 // Replace the exact with the load.
17487 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17490 // The replacement was made in place; don't return anything.
17494 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17495 static std::pair<unsigned, bool>
17496 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17497 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17498 if (!VT.isVector())
17499 return std::make_pair(0, false);
17501 bool NeedSplit = false;
17502 switch (VT.getSimpleVT().SimpleTy) {
17503 default: return std::make_pair(0, false);
17507 if (!Subtarget->hasAVX2())
17509 if (!Subtarget->hasAVX())
17510 return std::make_pair(0, false);
17515 if (!Subtarget->hasSSE2())
17516 return std::make_pair(0, false);
17519 // SSE2 has only a small subset of the operations.
17520 bool hasUnsigned = Subtarget->hasSSE41() ||
17521 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17522 bool hasSigned = Subtarget->hasSSE41() ||
17523 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17525 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17528 // Check for x CC y ? x : y.
17529 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17530 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17535 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17538 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17541 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17544 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17546 // Check for x CC y ? y : x -- a min/max with reversed arms.
17547 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17548 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17553 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17556 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17559 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17562 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17566 return std::make_pair(Opc, NeedSplit);
17569 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17571 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17572 TargetLowering::DAGCombinerInfo &DCI,
17573 const X86Subtarget *Subtarget) {
17575 SDValue Cond = N->getOperand(0);
17576 // Get the LHS/RHS of the select.
17577 SDValue LHS = N->getOperand(1);
17578 SDValue RHS = N->getOperand(2);
17579 EVT VT = LHS.getValueType();
17580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17582 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17583 // instructions match the semantics of the common C idiom x<y?x:y but not
17584 // x<=y?x:y, because of how they handle negative zero (which can be
17585 // ignored in unsafe-math mode).
17586 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17587 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17588 (Subtarget->hasSSE2() ||
17589 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17590 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17592 unsigned Opcode = 0;
17593 // Check for x CC y ? x : y.
17594 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17595 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17599 // Converting this to a min would handle NaNs incorrectly, and swapping
17600 // the operands would cause it to handle comparisons between positive
17601 // and negative zero incorrectly.
17602 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17603 if (!DAG.getTarget().Options.UnsafeFPMath &&
17604 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17606 std::swap(LHS, RHS);
17608 Opcode = X86ISD::FMIN;
17611 // Converting this to a min would handle comparisons between positive
17612 // and negative zero incorrectly.
17613 if (!DAG.getTarget().Options.UnsafeFPMath &&
17614 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17616 Opcode = X86ISD::FMIN;
17619 // Converting this to a min would handle both negative zeros and NaNs
17620 // incorrectly, but we can swap the operands to fix both.
17621 std::swap(LHS, RHS);
17625 Opcode = X86ISD::FMIN;
17629 // Converting this to a max would handle comparisons between positive
17630 // and negative zero incorrectly.
17631 if (!DAG.getTarget().Options.UnsafeFPMath &&
17632 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17634 Opcode = X86ISD::FMAX;
17637 // Converting this to a max would handle NaNs incorrectly, and swapping
17638 // the operands would cause it to handle comparisons between positive
17639 // and negative zero incorrectly.
17640 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17641 if (!DAG.getTarget().Options.UnsafeFPMath &&
17642 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17644 std::swap(LHS, RHS);
17646 Opcode = X86ISD::FMAX;
17649 // Converting this to a max would handle both negative zeros and NaNs
17650 // incorrectly, but we can swap the operands to fix both.
17651 std::swap(LHS, RHS);
17655 Opcode = X86ISD::FMAX;
17658 // Check for x CC y ? y : x -- a min/max with reversed arms.
17659 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17660 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17664 // Converting this to a min would handle comparisons between positive
17665 // and negative zero incorrectly, and swapping the operands would
17666 // cause it to handle NaNs incorrectly.
17667 if (!DAG.getTarget().Options.UnsafeFPMath &&
17668 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17669 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17671 std::swap(LHS, RHS);
17673 Opcode = X86ISD::FMIN;
17676 // Converting this to a min would handle NaNs incorrectly.
17677 if (!DAG.getTarget().Options.UnsafeFPMath &&
17678 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17680 Opcode = X86ISD::FMIN;
17683 // Converting this to a min would handle both negative zeros and NaNs
17684 // incorrectly, but we can swap the operands to fix both.
17685 std::swap(LHS, RHS);
17689 Opcode = X86ISD::FMIN;
17693 // Converting this to a max would handle NaNs incorrectly.
17694 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17696 Opcode = X86ISD::FMAX;
17699 // Converting this to a max would handle comparisons between positive
17700 // and negative zero incorrectly, and swapping the operands would
17701 // cause it to handle NaNs incorrectly.
17702 if (!DAG.getTarget().Options.UnsafeFPMath &&
17703 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17704 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17706 std::swap(LHS, RHS);
17708 Opcode = X86ISD::FMAX;
17711 // Converting this to a max would handle both negative zeros and NaNs
17712 // incorrectly, but we can swap the operands to fix both.
17713 std::swap(LHS, RHS);
17717 Opcode = X86ISD::FMAX;
17723 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17726 EVT CondVT = Cond.getValueType();
17727 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17728 CondVT.getVectorElementType() == MVT::i1) {
17729 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17730 // lowering on AVX-512. In this case we convert it to
17731 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17732 // The same situation for all 128 and 256-bit vectors of i8 and i16
17733 EVT OpVT = LHS.getValueType();
17734 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17735 (OpVT.getVectorElementType() == MVT::i8 ||
17736 OpVT.getVectorElementType() == MVT::i16)) {
17737 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17738 DCI.AddToWorklist(Cond.getNode());
17739 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17742 // If this is a select between two integer constants, try to do some
17744 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17745 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17746 // Don't do this for crazy integer types.
17747 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17748 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17749 // so that TrueC (the true value) is larger than FalseC.
17750 bool NeedsCondInvert = false;
17752 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17753 // Efficiently invertible.
17754 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17755 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17756 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17757 NeedsCondInvert = true;
17758 std::swap(TrueC, FalseC);
17761 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17762 if (FalseC->getAPIntValue() == 0 &&
17763 TrueC->getAPIntValue().isPowerOf2()) {
17764 if (NeedsCondInvert) // Invert the condition if needed.
17765 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17766 DAG.getConstant(1, Cond.getValueType()));
17768 // Zero extend the condition if needed.
17769 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17771 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17772 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17773 DAG.getConstant(ShAmt, MVT::i8));
17776 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17777 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17778 if (NeedsCondInvert) // Invert the condition if needed.
17779 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17780 DAG.getConstant(1, Cond.getValueType()));
17782 // Zero extend the condition if needed.
17783 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17784 FalseC->getValueType(0), Cond);
17785 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17786 SDValue(FalseC, 0));
17789 // Optimize cases that will turn into an LEA instruction. This requires
17790 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17791 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17792 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17793 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17795 bool isFastMultiplier = false;
17797 switch ((unsigned char)Diff) {
17799 case 1: // result = add base, cond
17800 case 2: // result = lea base( , cond*2)
17801 case 3: // result = lea base(cond, cond*2)
17802 case 4: // result = lea base( , cond*4)
17803 case 5: // result = lea base(cond, cond*4)
17804 case 8: // result = lea base( , cond*8)
17805 case 9: // result = lea base(cond, cond*8)
17806 isFastMultiplier = true;
17811 if (isFastMultiplier) {
17812 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17813 if (NeedsCondInvert) // Invert the condition if needed.
17814 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17815 DAG.getConstant(1, Cond.getValueType()));
17817 // Zero extend the condition if needed.
17818 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17820 // Scale the condition by the difference.
17822 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17823 DAG.getConstant(Diff, Cond.getValueType()));
17825 // Add the base if non-zero.
17826 if (FalseC->getAPIntValue() != 0)
17827 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17828 SDValue(FalseC, 0));
17835 // Canonicalize max and min:
17836 // (x > y) ? x : y -> (x >= y) ? x : y
17837 // (x < y) ? x : y -> (x <= y) ? x : y
17838 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17839 // the need for an extra compare
17840 // against zero. e.g.
17841 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17843 // testl %edi, %edi
17845 // cmovgl %edi, %eax
17849 // cmovsl %eax, %edi
17850 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17851 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17852 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17853 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17858 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17859 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17860 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17861 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17866 // Early exit check
17867 if (!TLI.isTypeLegal(VT))
17870 // Match VSELECTs into subs with unsigned saturation.
17871 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17872 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17873 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17874 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17875 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17877 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17878 // left side invert the predicate to simplify logic below.
17880 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17882 CC = ISD::getSetCCInverse(CC, true);
17883 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17887 if (Other.getNode() && Other->getNumOperands() == 2 &&
17888 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17889 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17890 SDValue CondRHS = Cond->getOperand(1);
17892 // Look for a general sub with unsigned saturation first.
17893 // x >= y ? x-y : 0 --> subus x, y
17894 // x > y ? x-y : 0 --> subus x, y
17895 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17896 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17897 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17899 // If the RHS is a constant we have to reverse the const canonicalization.
17900 // x > C-1 ? x+-C : 0 --> subus x, C
17901 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17902 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17903 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17904 if (CondRHS.getConstantOperandVal(0) == -A-1)
17905 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17906 DAG.getConstant(-A, VT));
17909 // Another special case: If C was a sign bit, the sub has been
17910 // canonicalized into a xor.
17911 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17912 // it's safe to decanonicalize the xor?
17913 // x s< 0 ? x^C : 0 --> subus x, C
17914 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17915 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17916 isSplatVector(OpRHS.getNode())) {
17917 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17919 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17924 // Try to match a min/max vector operation.
17925 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17926 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17927 unsigned Opc = ret.first;
17928 bool NeedSplit = ret.second;
17930 if (Opc && NeedSplit) {
17931 unsigned NumElems = VT.getVectorNumElements();
17932 // Extract the LHS vectors
17933 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17934 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17936 // Extract the RHS vectors
17937 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17938 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17940 // Create min/max for each subvector
17941 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17942 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17944 // Merge the result
17945 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17947 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17950 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17951 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17952 // Check if SETCC has already been promoted
17953 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17954 // Check that condition value type matches vselect operand type
17957 assert(Cond.getValueType().isVector() &&
17958 "vector select expects a vector selector!");
17960 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17961 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17963 if (!TValIsAllOnes && !FValIsAllZeros) {
17964 // Try invert the condition if true value is not all 1s and false value
17966 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17967 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17969 if (TValIsAllZeros || FValIsAllOnes) {
17970 SDValue CC = Cond.getOperand(2);
17971 ISD::CondCode NewCC =
17972 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17973 Cond.getOperand(0).getValueType().isInteger());
17974 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17975 std::swap(LHS, RHS);
17976 TValIsAllOnes = FValIsAllOnes;
17977 FValIsAllZeros = TValIsAllZeros;
17981 if (TValIsAllOnes || FValIsAllZeros) {
17984 if (TValIsAllOnes && FValIsAllZeros)
17986 else if (TValIsAllOnes)
17987 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17988 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17989 else if (FValIsAllZeros)
17990 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17991 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17993 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17997 // Try to fold this VSELECT into a MOVSS/MOVSD
17998 if (N->getOpcode() == ISD::VSELECT &&
17999 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18000 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18001 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18002 bool CanFold = false;
18003 unsigned NumElems = Cond.getNumOperands();
18007 if (isZero(Cond.getOperand(0))) {
18010 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18011 // fold (vselect <0,-1> -> (movsd A, B)
18012 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18013 CanFold = isAllOnes(Cond.getOperand(i));
18014 } else if (isAllOnes(Cond.getOperand(0))) {
18018 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18019 // fold (vselect <-1,0> -> (movsd B, A)
18020 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18021 CanFold = isZero(Cond.getOperand(i));
18025 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18026 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18027 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18030 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18031 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18032 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18033 // (v2i64 (bitcast B)))))
18035 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18036 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18037 // (v2f64 (bitcast B)))))
18039 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18040 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18041 // (v2i64 (bitcast A)))))
18043 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18044 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18045 // (v2f64 (bitcast A)))))
18047 CanFold = (isZero(Cond.getOperand(0)) &&
18048 isZero(Cond.getOperand(1)) &&
18049 isAllOnes(Cond.getOperand(2)) &&
18050 isAllOnes(Cond.getOperand(3)));
18052 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18053 isAllOnes(Cond.getOperand(1)) &&
18054 isZero(Cond.getOperand(2)) &&
18055 isZero(Cond.getOperand(3))) {
18057 std::swap(LHS, RHS);
18061 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18062 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18063 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18064 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18066 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18072 // If we know that this node is legal then we know that it is going to be
18073 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18074 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18075 // to simplify previous instructions.
18076 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18077 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
18078 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18080 // Don't optimize vector selects that map to mask-registers.
18084 // Check all uses of that condition operand to check whether it will be
18085 // consumed by non-BLEND instructions, which may depend on all bits are set
18087 for (SDNode::use_iterator I = Cond->use_begin(),
18088 E = Cond->use_end(); I != E; ++I)
18089 if (I->getOpcode() != ISD::VSELECT)
18090 // TODO: Add other opcodes eventually lowered into BLEND.
18093 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18094 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18096 APInt KnownZero, KnownOne;
18097 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18098 DCI.isBeforeLegalizeOps());
18099 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18100 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18101 DCI.CommitTargetLoweringOpt(TLO);
18107 // Check whether a boolean test is testing a boolean value generated by
18108 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18111 // Simplify the following patterns:
18112 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18113 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18114 // to (Op EFLAGS Cond)
18116 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18117 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18118 // to (Op EFLAGS !Cond)
18120 // where Op could be BRCOND or CMOV.
18122 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18123 // Quit if not CMP and SUB with its value result used.
18124 if (Cmp.getOpcode() != X86ISD::CMP &&
18125 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18128 // Quit if not used as a boolean value.
18129 if (CC != X86::COND_E && CC != X86::COND_NE)
18132 // Check CMP operands. One of them should be 0 or 1 and the other should be
18133 // an SetCC or extended from it.
18134 SDValue Op1 = Cmp.getOperand(0);
18135 SDValue Op2 = Cmp.getOperand(1);
18138 const ConstantSDNode* C = nullptr;
18139 bool needOppositeCond = (CC == X86::COND_E);
18140 bool checkAgainstTrue = false; // Is it a comparison against 1?
18142 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18144 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18146 else // Quit if all operands are not constants.
18149 if (C->getZExtValue() == 1) {
18150 needOppositeCond = !needOppositeCond;
18151 checkAgainstTrue = true;
18152 } else if (C->getZExtValue() != 0)
18153 // Quit if the constant is neither 0 or 1.
18156 bool truncatedToBoolWithAnd = false;
18157 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18158 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18159 SetCC.getOpcode() == ISD::TRUNCATE ||
18160 SetCC.getOpcode() == ISD::AND) {
18161 if (SetCC.getOpcode() == ISD::AND) {
18163 ConstantSDNode *CS;
18164 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18165 CS->getZExtValue() == 1)
18167 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18168 CS->getZExtValue() == 1)
18172 SetCC = SetCC.getOperand(OpIdx);
18173 truncatedToBoolWithAnd = true;
18175 SetCC = SetCC.getOperand(0);
18178 switch (SetCC.getOpcode()) {
18179 case X86ISD::SETCC_CARRY:
18180 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18181 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18182 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18183 // truncated to i1 using 'and'.
18184 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18186 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18187 "Invalid use of SETCC_CARRY!");
18189 case X86ISD::SETCC:
18190 // Set the condition code or opposite one if necessary.
18191 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18192 if (needOppositeCond)
18193 CC = X86::GetOppositeBranchCondition(CC);
18194 return SetCC.getOperand(1);
18195 case X86ISD::CMOV: {
18196 // Check whether false/true value has canonical one, i.e. 0 or 1.
18197 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18198 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18199 // Quit if true value is not a constant.
18202 // Quit if false value is not a constant.
18204 SDValue Op = SetCC.getOperand(0);
18205 // Skip 'zext' or 'trunc' node.
18206 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18207 Op.getOpcode() == ISD::TRUNCATE)
18208 Op = Op.getOperand(0);
18209 // A special case for rdrand/rdseed, where 0 is set if false cond is
18211 if ((Op.getOpcode() != X86ISD::RDRAND &&
18212 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18215 // Quit if false value is not the constant 0 or 1.
18216 bool FValIsFalse = true;
18217 if (FVal && FVal->getZExtValue() != 0) {
18218 if (FVal->getZExtValue() != 1)
18220 // If FVal is 1, opposite cond is needed.
18221 needOppositeCond = !needOppositeCond;
18222 FValIsFalse = false;
18224 // Quit if TVal is not the constant opposite of FVal.
18225 if (FValIsFalse && TVal->getZExtValue() != 1)
18227 if (!FValIsFalse && TVal->getZExtValue() != 0)
18229 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18230 if (needOppositeCond)
18231 CC = X86::GetOppositeBranchCondition(CC);
18232 return SetCC.getOperand(3);
18239 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18240 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18241 TargetLowering::DAGCombinerInfo &DCI,
18242 const X86Subtarget *Subtarget) {
18245 // If the flag operand isn't dead, don't touch this CMOV.
18246 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18249 SDValue FalseOp = N->getOperand(0);
18250 SDValue TrueOp = N->getOperand(1);
18251 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18252 SDValue Cond = N->getOperand(3);
18254 if (CC == X86::COND_E || CC == X86::COND_NE) {
18255 switch (Cond.getOpcode()) {
18259 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18260 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18261 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18267 Flags = checkBoolTestSetCCCombine(Cond, CC);
18268 if (Flags.getNode() &&
18269 // Extra check as FCMOV only supports a subset of X86 cond.
18270 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18271 SDValue Ops[] = { FalseOp, TrueOp,
18272 DAG.getConstant(CC, MVT::i8), Flags };
18273 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18276 // If this is a select between two integer constants, try to do some
18277 // optimizations. Note that the operands are ordered the opposite of SELECT
18279 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18280 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18281 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18282 // larger than FalseC (the false value).
18283 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18284 CC = X86::GetOppositeBranchCondition(CC);
18285 std::swap(TrueC, FalseC);
18286 std::swap(TrueOp, FalseOp);
18289 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18290 // This is efficient for any integer data type (including i8/i16) and
18292 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18293 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18294 DAG.getConstant(CC, MVT::i8), Cond);
18296 // Zero extend the condition if needed.
18297 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18299 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18300 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18301 DAG.getConstant(ShAmt, MVT::i8));
18302 if (N->getNumValues() == 2) // Dead flag value?
18303 return DCI.CombineTo(N, Cond, SDValue());
18307 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18308 // for any integer data type, including i8/i16.
18309 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18310 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18311 DAG.getConstant(CC, MVT::i8), Cond);
18313 // Zero extend the condition if needed.
18314 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18315 FalseC->getValueType(0), Cond);
18316 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18317 SDValue(FalseC, 0));
18319 if (N->getNumValues() == 2) // Dead flag value?
18320 return DCI.CombineTo(N, Cond, SDValue());
18324 // Optimize cases that will turn into an LEA instruction. This requires
18325 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18326 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18327 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18328 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18330 bool isFastMultiplier = false;
18332 switch ((unsigned char)Diff) {
18334 case 1: // result = add base, cond
18335 case 2: // result = lea base( , cond*2)
18336 case 3: // result = lea base(cond, cond*2)
18337 case 4: // result = lea base( , cond*4)
18338 case 5: // result = lea base(cond, cond*4)
18339 case 8: // result = lea base( , cond*8)
18340 case 9: // result = lea base(cond, cond*8)
18341 isFastMultiplier = true;
18346 if (isFastMultiplier) {
18347 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18348 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18349 DAG.getConstant(CC, MVT::i8), Cond);
18350 // Zero extend the condition if needed.
18351 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18353 // Scale the condition by the difference.
18355 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18356 DAG.getConstant(Diff, Cond.getValueType()));
18358 // Add the base if non-zero.
18359 if (FalseC->getAPIntValue() != 0)
18360 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18361 SDValue(FalseC, 0));
18362 if (N->getNumValues() == 2) // Dead flag value?
18363 return DCI.CombineTo(N, Cond, SDValue());
18370 // Handle these cases:
18371 // (select (x != c), e, c) -> select (x != c), e, x),
18372 // (select (x == c), c, e) -> select (x == c), x, e)
18373 // where the c is an integer constant, and the "select" is the combination
18374 // of CMOV and CMP.
18376 // The rationale for this change is that the conditional-move from a constant
18377 // needs two instructions, however, conditional-move from a register needs
18378 // only one instruction.
18380 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18381 // some instruction-combining opportunities. This opt needs to be
18382 // postponed as late as possible.
18384 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18385 // the DCI.xxxx conditions are provided to postpone the optimization as
18386 // late as possible.
18388 ConstantSDNode *CmpAgainst = nullptr;
18389 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18390 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18391 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18393 if (CC == X86::COND_NE &&
18394 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18395 CC = X86::GetOppositeBranchCondition(CC);
18396 std::swap(TrueOp, FalseOp);
18399 if (CC == X86::COND_E &&
18400 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18401 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18402 DAG.getConstant(CC, MVT::i8), Cond };
18403 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18411 /// PerformMulCombine - Optimize a single multiply with constant into two
18412 /// in order to implement it with two cheaper instructions, e.g.
18413 /// LEA + SHL, LEA + LEA.
18414 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18415 TargetLowering::DAGCombinerInfo &DCI) {
18416 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18419 EVT VT = N->getValueType(0);
18420 if (VT != MVT::i64)
18423 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18426 uint64_t MulAmt = C->getZExtValue();
18427 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18430 uint64_t MulAmt1 = 0;
18431 uint64_t MulAmt2 = 0;
18432 if ((MulAmt % 9) == 0) {
18434 MulAmt2 = MulAmt / 9;
18435 } else if ((MulAmt % 5) == 0) {
18437 MulAmt2 = MulAmt / 5;
18438 } else if ((MulAmt % 3) == 0) {
18440 MulAmt2 = MulAmt / 3;
18443 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18446 if (isPowerOf2_64(MulAmt2) &&
18447 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18448 // If second multiplifer is pow2, issue it first. We want the multiply by
18449 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18451 std::swap(MulAmt1, MulAmt2);
18454 if (isPowerOf2_64(MulAmt1))
18455 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18456 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18458 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18459 DAG.getConstant(MulAmt1, VT));
18461 if (isPowerOf2_64(MulAmt2))
18462 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18463 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18465 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18466 DAG.getConstant(MulAmt2, VT));
18468 // Do not add new nodes to DAG combiner worklist.
18469 DCI.CombineTo(N, NewMul, false);
18474 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18475 SDValue N0 = N->getOperand(0);
18476 SDValue N1 = N->getOperand(1);
18477 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18478 EVT VT = N0.getValueType();
18480 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18481 // since the result of setcc_c is all zero's or all ones.
18482 if (VT.isInteger() && !VT.isVector() &&
18483 N1C && N0.getOpcode() == ISD::AND &&
18484 N0.getOperand(1).getOpcode() == ISD::Constant) {
18485 SDValue N00 = N0.getOperand(0);
18486 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18487 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18488 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18489 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18490 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18491 APInt ShAmt = N1C->getAPIntValue();
18492 Mask = Mask.shl(ShAmt);
18494 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18495 N00, DAG.getConstant(Mask, VT));
18499 // Hardware support for vector shifts is sparse which makes us scalarize the
18500 // vector operations in many cases. Also, on sandybridge ADD is faster than
18502 // (shl V, 1) -> add V,V
18503 if (isSplatVector(N1.getNode())) {
18504 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18506 // We shift all of the values by one. In many cases we do not have
18507 // hardware support for this operation. This is better expressed as an ADD
18509 if (N1C && (1 == N1C->getZExtValue())) {
18510 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18517 /// \brief Returns a vector of 0s if the node in input is a vector logical
18518 /// shift by a constant amount which is known to be bigger than or equal
18519 /// to the vector element size in bits.
18520 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18521 const X86Subtarget *Subtarget) {
18522 EVT VT = N->getValueType(0);
18524 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18525 (!Subtarget->hasInt256() ||
18526 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18529 SDValue Amt = N->getOperand(1);
18531 if (isSplatVector(Amt.getNode())) {
18532 SDValue SclrAmt = Amt->getOperand(0);
18533 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18534 APInt ShiftAmt = C->getAPIntValue();
18535 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18537 // SSE2/AVX2 logical shifts always return a vector of 0s
18538 // if the shift amount is bigger than or equal to
18539 // the element size. The constant shift amount will be
18540 // encoded as a 8-bit immediate.
18541 if (ShiftAmt.trunc(8).uge(MaxAmount))
18542 return getZeroVector(VT, Subtarget, DAG, DL);
18549 /// PerformShiftCombine - Combine shifts.
18550 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18551 TargetLowering::DAGCombinerInfo &DCI,
18552 const X86Subtarget *Subtarget) {
18553 if (N->getOpcode() == ISD::SHL) {
18554 SDValue V = PerformSHLCombine(N, DAG);
18555 if (V.getNode()) return V;
18558 if (N->getOpcode() != ISD::SRA) {
18559 // Try to fold this logical shift into a zero vector.
18560 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18561 if (V.getNode()) return V;
18567 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18568 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18569 // and friends. Likewise for OR -> CMPNEQSS.
18570 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18571 TargetLowering::DAGCombinerInfo &DCI,
18572 const X86Subtarget *Subtarget) {
18575 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18576 // we're requiring SSE2 for both.
18577 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18578 SDValue N0 = N->getOperand(0);
18579 SDValue N1 = N->getOperand(1);
18580 SDValue CMP0 = N0->getOperand(1);
18581 SDValue CMP1 = N1->getOperand(1);
18584 // The SETCCs should both refer to the same CMP.
18585 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18588 SDValue CMP00 = CMP0->getOperand(0);
18589 SDValue CMP01 = CMP0->getOperand(1);
18590 EVT VT = CMP00.getValueType();
18592 if (VT == MVT::f32 || VT == MVT::f64) {
18593 bool ExpectingFlags = false;
18594 // Check for any users that want flags:
18595 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18596 !ExpectingFlags && UI != UE; ++UI)
18597 switch (UI->getOpcode()) {
18602 ExpectingFlags = true;
18604 case ISD::CopyToReg:
18605 case ISD::SIGN_EXTEND:
18606 case ISD::ZERO_EXTEND:
18607 case ISD::ANY_EXTEND:
18611 if (!ExpectingFlags) {
18612 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18613 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18615 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18616 X86::CondCode tmp = cc0;
18621 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18622 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18623 // FIXME: need symbolic constants for these magic numbers.
18624 // See X86ATTInstPrinter.cpp:printSSECC().
18625 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18626 if (Subtarget->hasAVX512()) {
18627 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18628 CMP01, DAG.getConstant(x86cc, MVT::i8));
18629 if (N->getValueType(0) != MVT::i1)
18630 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18634 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18635 CMP00.getValueType(), CMP00, CMP01,
18636 DAG.getConstant(x86cc, MVT::i8));
18638 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18639 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18641 if (is64BitFP && !Subtarget->is64Bit()) {
18642 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18643 // 64-bit integer, since that's not a legal type. Since
18644 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18645 // bits, but can do this little dance to extract the lowest 32 bits
18646 // and work with those going forward.
18647 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18649 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18651 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18652 Vector32, DAG.getIntPtrConstant(0));
18656 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18657 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18658 DAG.getConstant(1, IntVT));
18659 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18660 return OneBitOfTruth;
18668 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18669 /// so it can be folded inside ANDNP.
18670 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18671 EVT VT = N->getValueType(0);
18673 // Match direct AllOnes for 128 and 256-bit vectors
18674 if (ISD::isBuildVectorAllOnes(N))
18677 // Look through a bit convert.
18678 if (N->getOpcode() == ISD::BITCAST)
18679 N = N->getOperand(0).getNode();
18681 // Sometimes the operand may come from a insert_subvector building a 256-bit
18683 if (VT.is256BitVector() &&
18684 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18685 SDValue V1 = N->getOperand(0);
18686 SDValue V2 = N->getOperand(1);
18688 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18689 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18690 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18691 ISD::isBuildVectorAllOnes(V2.getNode()))
18698 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18699 // register. In most cases we actually compare or select YMM-sized registers
18700 // and mixing the two types creates horrible code. This method optimizes
18701 // some of the transition sequences.
18702 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18703 TargetLowering::DAGCombinerInfo &DCI,
18704 const X86Subtarget *Subtarget) {
18705 EVT VT = N->getValueType(0);
18706 if (!VT.is256BitVector())
18709 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18710 N->getOpcode() == ISD::ZERO_EXTEND ||
18711 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18713 SDValue Narrow = N->getOperand(0);
18714 EVT NarrowVT = Narrow->getValueType(0);
18715 if (!NarrowVT.is128BitVector())
18718 if (Narrow->getOpcode() != ISD::XOR &&
18719 Narrow->getOpcode() != ISD::AND &&
18720 Narrow->getOpcode() != ISD::OR)
18723 SDValue N0 = Narrow->getOperand(0);
18724 SDValue N1 = Narrow->getOperand(1);
18727 // The Left side has to be a trunc.
18728 if (N0.getOpcode() != ISD::TRUNCATE)
18731 // The type of the truncated inputs.
18732 EVT WideVT = N0->getOperand(0)->getValueType(0);
18736 // The right side has to be a 'trunc' or a constant vector.
18737 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18738 bool RHSConst = (isSplatVector(N1.getNode()) &&
18739 isa<ConstantSDNode>(N1->getOperand(0)));
18740 if (!RHSTrunc && !RHSConst)
18743 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18745 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18748 // Set N0 and N1 to hold the inputs to the new wide operation.
18749 N0 = N0->getOperand(0);
18751 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18752 N1->getOperand(0));
18753 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18754 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18755 } else if (RHSTrunc) {
18756 N1 = N1->getOperand(0);
18759 // Generate the wide operation.
18760 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18761 unsigned Opcode = N->getOpcode();
18763 case ISD::ANY_EXTEND:
18765 case ISD::ZERO_EXTEND: {
18766 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18767 APInt Mask = APInt::getAllOnesValue(InBits);
18768 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18769 return DAG.getNode(ISD::AND, DL, VT,
18770 Op, DAG.getConstant(Mask, VT));
18772 case ISD::SIGN_EXTEND:
18773 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18774 Op, DAG.getValueType(NarrowVT));
18776 llvm_unreachable("Unexpected opcode");
18780 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18781 TargetLowering::DAGCombinerInfo &DCI,
18782 const X86Subtarget *Subtarget) {
18783 EVT VT = N->getValueType(0);
18784 if (DCI.isBeforeLegalizeOps())
18787 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18791 // Create BEXTR instructions
18792 // BEXTR is ((X >> imm) & (2**size-1))
18793 if (VT == MVT::i32 || VT == MVT::i64) {
18794 SDValue N0 = N->getOperand(0);
18795 SDValue N1 = N->getOperand(1);
18798 // Check for BEXTR.
18799 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18800 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18801 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18802 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18803 if (MaskNode && ShiftNode) {
18804 uint64_t Mask = MaskNode->getZExtValue();
18805 uint64_t Shift = ShiftNode->getZExtValue();
18806 if (isMask_64(Mask)) {
18807 uint64_t MaskSize = CountPopulation_64(Mask);
18808 if (Shift + MaskSize <= VT.getSizeInBits())
18809 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18810 DAG.getConstant(Shift | (MaskSize << 8), VT));
18818 // Want to form ANDNP nodes:
18819 // 1) In the hopes of then easily combining them with OR and AND nodes
18820 // to form PBLEND/PSIGN.
18821 // 2) To match ANDN packed intrinsics
18822 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18825 SDValue N0 = N->getOperand(0);
18826 SDValue N1 = N->getOperand(1);
18829 // Check LHS for vnot
18830 if (N0.getOpcode() == ISD::XOR &&
18831 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18832 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18833 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18835 // Check RHS for vnot
18836 if (N1.getOpcode() == ISD::XOR &&
18837 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18838 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18839 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18844 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18845 TargetLowering::DAGCombinerInfo &DCI,
18846 const X86Subtarget *Subtarget) {
18847 if (DCI.isBeforeLegalizeOps())
18850 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18854 SDValue N0 = N->getOperand(0);
18855 SDValue N1 = N->getOperand(1);
18856 EVT VT = N->getValueType(0);
18858 // look for psign/blend
18859 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18860 if (!Subtarget->hasSSSE3() ||
18861 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18864 // Canonicalize pandn to RHS
18865 if (N0.getOpcode() == X86ISD::ANDNP)
18867 // or (and (m, y), (pandn m, x))
18868 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18869 SDValue Mask = N1.getOperand(0);
18870 SDValue X = N1.getOperand(1);
18872 if (N0.getOperand(0) == Mask)
18873 Y = N0.getOperand(1);
18874 if (N0.getOperand(1) == Mask)
18875 Y = N0.getOperand(0);
18877 // Check to see if the mask appeared in both the AND and ANDNP and
18881 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18882 // Look through mask bitcast.
18883 if (Mask.getOpcode() == ISD::BITCAST)
18884 Mask = Mask.getOperand(0);
18885 if (X.getOpcode() == ISD::BITCAST)
18886 X = X.getOperand(0);
18887 if (Y.getOpcode() == ISD::BITCAST)
18888 Y = Y.getOperand(0);
18890 EVT MaskVT = Mask.getValueType();
18892 // Validate that the Mask operand is a vector sra node.
18893 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18894 // there is no psrai.b
18895 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18896 unsigned SraAmt = ~0;
18897 if (Mask.getOpcode() == ISD::SRA) {
18898 SDValue Amt = Mask.getOperand(1);
18899 if (isSplatVector(Amt.getNode())) {
18900 SDValue SclrAmt = Amt->getOperand(0);
18901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18902 SraAmt = C->getZExtValue();
18904 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18905 SDValue SraC = Mask.getOperand(1);
18906 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18908 if ((SraAmt + 1) != EltBits)
18913 // Now we know we at least have a plendvb with the mask val. See if
18914 // we can form a psignb/w/d.
18915 // psign = x.type == y.type == mask.type && y = sub(0, x);
18916 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18917 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18918 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18919 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18920 "Unsupported VT for PSIGN");
18921 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18922 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18924 // PBLENDVB only available on SSE 4.1
18925 if (!Subtarget->hasSSE41())
18928 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18930 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18931 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18932 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18933 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18934 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18938 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18941 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18942 MachineFunction &MF = DAG.getMachineFunction();
18943 bool OptForSize = MF.getFunction()->getAttributes().
18944 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18946 // SHLD/SHRD instructions have lower register pressure, but on some
18947 // platforms they have higher latency than the equivalent
18948 // series of shifts/or that would otherwise be generated.
18949 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18950 // have higher latencies and we are not optimizing for size.
18951 if (!OptForSize && Subtarget->isSHLDSlow())
18954 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18956 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18958 if (!N0.hasOneUse() || !N1.hasOneUse())
18961 SDValue ShAmt0 = N0.getOperand(1);
18962 if (ShAmt0.getValueType() != MVT::i8)
18964 SDValue ShAmt1 = N1.getOperand(1);
18965 if (ShAmt1.getValueType() != MVT::i8)
18967 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18968 ShAmt0 = ShAmt0.getOperand(0);
18969 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18970 ShAmt1 = ShAmt1.getOperand(0);
18973 unsigned Opc = X86ISD::SHLD;
18974 SDValue Op0 = N0.getOperand(0);
18975 SDValue Op1 = N1.getOperand(0);
18976 if (ShAmt0.getOpcode() == ISD::SUB) {
18977 Opc = X86ISD::SHRD;
18978 std::swap(Op0, Op1);
18979 std::swap(ShAmt0, ShAmt1);
18982 unsigned Bits = VT.getSizeInBits();
18983 if (ShAmt1.getOpcode() == ISD::SUB) {
18984 SDValue Sum = ShAmt1.getOperand(0);
18985 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18986 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18987 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18988 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18989 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18990 return DAG.getNode(Opc, DL, VT,
18992 DAG.getNode(ISD::TRUNCATE, DL,
18995 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18996 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18998 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18999 return DAG.getNode(Opc, DL, VT,
19000 N0.getOperand(0), N1.getOperand(0),
19001 DAG.getNode(ISD::TRUNCATE, DL,
19008 // Generate NEG and CMOV for integer abs.
19009 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19010 EVT VT = N->getValueType(0);
19012 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19013 // 8-bit integer abs to NEG and CMOV.
19014 if (VT.isInteger() && VT.getSizeInBits() == 8)
19017 SDValue N0 = N->getOperand(0);
19018 SDValue N1 = N->getOperand(1);
19021 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19022 // and change it to SUB and CMOV.
19023 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19024 N0.getOpcode() == ISD::ADD &&
19025 N0.getOperand(1) == N1 &&
19026 N1.getOpcode() == ISD::SRA &&
19027 N1.getOperand(0) == N0.getOperand(0))
19028 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19029 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19030 // Generate SUB & CMOV.
19031 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19032 DAG.getConstant(0, VT), N0.getOperand(0));
19034 SDValue Ops[] = { N0.getOperand(0), Neg,
19035 DAG.getConstant(X86::COND_GE, MVT::i8),
19036 SDValue(Neg.getNode(), 1) };
19037 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19042 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19043 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19044 TargetLowering::DAGCombinerInfo &DCI,
19045 const X86Subtarget *Subtarget) {
19046 if (DCI.isBeforeLegalizeOps())
19049 if (Subtarget->hasCMov()) {
19050 SDValue RV = performIntegerAbsCombine(N, DAG);
19058 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19059 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19060 TargetLowering::DAGCombinerInfo &DCI,
19061 const X86Subtarget *Subtarget) {
19062 LoadSDNode *Ld = cast<LoadSDNode>(N);
19063 EVT RegVT = Ld->getValueType(0);
19064 EVT MemVT = Ld->getMemoryVT();
19066 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19067 unsigned RegSz = RegVT.getSizeInBits();
19069 // On Sandybridge unaligned 256bit loads are inefficient.
19070 ISD::LoadExtType Ext = Ld->getExtensionType();
19071 unsigned Alignment = Ld->getAlignment();
19072 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19073 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19074 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19075 unsigned NumElems = RegVT.getVectorNumElements();
19079 SDValue Ptr = Ld->getBasePtr();
19080 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19082 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19084 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19085 Ld->getPointerInfo(), Ld->isVolatile(),
19086 Ld->isNonTemporal(), Ld->isInvariant(),
19088 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19089 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19090 Ld->getPointerInfo(), Ld->isVolatile(),
19091 Ld->isNonTemporal(), Ld->isInvariant(),
19092 std::min(16U, Alignment));
19093 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19095 Load2.getValue(1));
19097 SDValue NewVec = DAG.getUNDEF(RegVT);
19098 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19099 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19100 return DCI.CombineTo(N, NewVec, TF, true);
19103 // If this is a vector EXT Load then attempt to optimize it using a
19104 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19105 // expansion is still better than scalar code.
19106 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19107 // emit a shuffle and a arithmetic shift.
19108 // TODO: It is possible to support ZExt by zeroing the undef values
19109 // during the shuffle phase or after the shuffle.
19110 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19111 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19112 assert(MemVT != RegVT && "Cannot extend to the same type");
19113 assert(MemVT.isVector() && "Must load a vector from memory");
19115 unsigned NumElems = RegVT.getVectorNumElements();
19116 unsigned MemSz = MemVT.getSizeInBits();
19117 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19119 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19122 // All sizes must be a power of two.
19123 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19126 // Attempt to load the original value using scalar loads.
19127 // Find the largest scalar type that divides the total loaded size.
19128 MVT SclrLoadTy = MVT::i8;
19129 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19130 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19131 MVT Tp = (MVT::SimpleValueType)tp;
19132 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19137 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19138 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19140 SclrLoadTy = MVT::f64;
19142 // Calculate the number of scalar loads that we need to perform
19143 // in order to load our vector from memory.
19144 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19145 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19148 unsigned loadRegZize = RegSz;
19149 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19152 // Represent our vector as a sequence of elements which are the
19153 // largest scalar that we can load.
19154 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19155 loadRegZize/SclrLoadTy.getSizeInBits());
19157 // Represent the data using the same element type that is stored in
19158 // memory. In practice, we ''widen'' MemVT.
19160 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19161 loadRegZize/MemVT.getScalarType().getSizeInBits());
19163 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19164 "Invalid vector type");
19166 // We can't shuffle using an illegal type.
19167 if (!TLI.isTypeLegal(WideVecVT))
19170 SmallVector<SDValue, 8> Chains;
19171 SDValue Ptr = Ld->getBasePtr();
19172 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19173 TLI.getPointerTy());
19174 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19176 for (unsigned i = 0; i < NumLoads; ++i) {
19177 // Perform a single load.
19178 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19179 Ptr, Ld->getPointerInfo(),
19180 Ld->isVolatile(), Ld->isNonTemporal(),
19181 Ld->isInvariant(), Ld->getAlignment());
19182 Chains.push_back(ScalarLoad.getValue(1));
19183 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19184 // another round of DAGCombining.
19186 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19188 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19189 ScalarLoad, DAG.getIntPtrConstant(i));
19191 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19194 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19196 // Bitcast the loaded value to a vector of the original element type, in
19197 // the size of the target vector type.
19198 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19199 unsigned SizeRatio = RegSz/MemSz;
19201 if (Ext == ISD::SEXTLOAD) {
19202 // If we have SSE4.1 we can directly emit a VSEXT node.
19203 if (Subtarget->hasSSE41()) {
19204 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19205 return DCI.CombineTo(N, Sext, TF, true);
19208 // Otherwise we'll shuffle the small elements in the high bits of the
19209 // larger type and perform an arithmetic shift. If the shift is not legal
19210 // it's better to scalarize.
19211 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19214 // Redistribute the loaded elements into the different locations.
19215 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19216 for (unsigned i = 0; i != NumElems; ++i)
19217 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19219 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19220 DAG.getUNDEF(WideVecVT),
19223 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19225 // Build the arithmetic shift.
19226 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19227 MemVT.getVectorElementType().getSizeInBits();
19228 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19229 DAG.getConstant(Amt, RegVT));
19231 return DCI.CombineTo(N, Shuff, TF, true);
19234 // Redistribute the loaded elements into the different locations.
19235 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19236 for (unsigned i = 0; i != NumElems; ++i)
19237 ShuffleVec[i*SizeRatio] = i;
19239 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19240 DAG.getUNDEF(WideVecVT),
19243 // Bitcast to the requested type.
19244 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19245 // Replace the original load with the new sequence
19246 // and return the new chain.
19247 return DCI.CombineTo(N, Shuff, TF, true);
19253 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19254 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19255 const X86Subtarget *Subtarget) {
19256 StoreSDNode *St = cast<StoreSDNode>(N);
19257 EVT VT = St->getValue().getValueType();
19258 EVT StVT = St->getMemoryVT();
19260 SDValue StoredVal = St->getOperand(1);
19261 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19263 // If we are saving a concatenation of two XMM registers, perform two stores.
19264 // On Sandy Bridge, 256-bit memory operations are executed by two
19265 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19266 // memory operation.
19267 unsigned Alignment = St->getAlignment();
19268 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19269 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19270 StVT == VT && !IsAligned) {
19271 unsigned NumElems = VT.getVectorNumElements();
19275 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19276 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19278 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19279 SDValue Ptr0 = St->getBasePtr();
19280 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19282 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19283 St->getPointerInfo(), St->isVolatile(),
19284 St->isNonTemporal(), Alignment);
19285 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19286 St->getPointerInfo(), St->isVolatile(),
19287 St->isNonTemporal(),
19288 std::min(16U, Alignment));
19289 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19292 // Optimize trunc store (of multiple scalars) to shuffle and store.
19293 // First, pack all of the elements in one place. Next, store to memory
19294 // in fewer chunks.
19295 if (St->isTruncatingStore() && VT.isVector()) {
19296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19297 unsigned NumElems = VT.getVectorNumElements();
19298 assert(StVT != VT && "Cannot truncate to the same type");
19299 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19300 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19302 // From, To sizes and ElemCount must be pow of two
19303 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19304 // We are going to use the original vector elt for storing.
19305 // Accumulated smaller vector elements must be a multiple of the store size.
19306 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19308 unsigned SizeRatio = FromSz / ToSz;
19310 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19312 // Create a type on which we perform the shuffle
19313 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19314 StVT.getScalarType(), NumElems*SizeRatio);
19316 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19318 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19319 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19320 for (unsigned i = 0; i != NumElems; ++i)
19321 ShuffleVec[i] = i * SizeRatio;
19323 // Can't shuffle using an illegal type.
19324 if (!TLI.isTypeLegal(WideVecVT))
19327 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19328 DAG.getUNDEF(WideVecVT),
19330 // At this point all of the data is stored at the bottom of the
19331 // register. We now need to save it to mem.
19333 // Find the largest store unit
19334 MVT StoreType = MVT::i8;
19335 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19336 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19337 MVT Tp = (MVT::SimpleValueType)tp;
19338 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19342 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19343 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19344 (64 <= NumElems * ToSz))
19345 StoreType = MVT::f64;
19347 // Bitcast the original vector into a vector of store-size units
19348 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19349 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19350 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19351 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19352 SmallVector<SDValue, 8> Chains;
19353 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19354 TLI.getPointerTy());
19355 SDValue Ptr = St->getBasePtr();
19357 // Perform one or more big stores into memory.
19358 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19359 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19360 StoreType, ShuffWide,
19361 DAG.getIntPtrConstant(i));
19362 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19363 St->getPointerInfo(), St->isVolatile(),
19364 St->isNonTemporal(), St->getAlignment());
19365 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19366 Chains.push_back(Ch);
19369 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19372 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19373 // the FP state in cases where an emms may be missing.
19374 // A preferable solution to the general problem is to figure out the right
19375 // places to insert EMMS. This qualifies as a quick hack.
19377 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19378 if (VT.getSizeInBits() != 64)
19381 const Function *F = DAG.getMachineFunction().getFunction();
19382 bool NoImplicitFloatOps = F->getAttributes().
19383 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19384 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19385 && Subtarget->hasSSE2();
19386 if ((VT.isVector() ||
19387 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19388 isa<LoadSDNode>(St->getValue()) &&
19389 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19390 St->getChain().hasOneUse() && !St->isVolatile()) {
19391 SDNode* LdVal = St->getValue().getNode();
19392 LoadSDNode *Ld = nullptr;
19393 int TokenFactorIndex = -1;
19394 SmallVector<SDValue, 8> Ops;
19395 SDNode* ChainVal = St->getChain().getNode();
19396 // Must be a store of a load. We currently handle two cases: the load
19397 // is a direct child, and it's under an intervening TokenFactor. It is
19398 // possible to dig deeper under nested TokenFactors.
19399 if (ChainVal == LdVal)
19400 Ld = cast<LoadSDNode>(St->getChain());
19401 else if (St->getValue().hasOneUse() &&
19402 ChainVal->getOpcode() == ISD::TokenFactor) {
19403 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19404 if (ChainVal->getOperand(i).getNode() == LdVal) {
19405 TokenFactorIndex = i;
19406 Ld = cast<LoadSDNode>(St->getValue());
19408 Ops.push_back(ChainVal->getOperand(i));
19412 if (!Ld || !ISD::isNormalLoad(Ld))
19415 // If this is not the MMX case, i.e. we are just turning i64 load/store
19416 // into f64 load/store, avoid the transformation if there are multiple
19417 // uses of the loaded value.
19418 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19423 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19424 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19426 if (Subtarget->is64Bit() || F64IsLegal) {
19427 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19428 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19429 Ld->getPointerInfo(), Ld->isVolatile(),
19430 Ld->isNonTemporal(), Ld->isInvariant(),
19431 Ld->getAlignment());
19432 SDValue NewChain = NewLd.getValue(1);
19433 if (TokenFactorIndex != -1) {
19434 Ops.push_back(NewChain);
19435 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19437 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19438 St->getPointerInfo(),
19439 St->isVolatile(), St->isNonTemporal(),
19440 St->getAlignment());
19443 // Otherwise, lower to two pairs of 32-bit loads / stores.
19444 SDValue LoAddr = Ld->getBasePtr();
19445 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19446 DAG.getConstant(4, MVT::i32));
19448 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19449 Ld->getPointerInfo(),
19450 Ld->isVolatile(), Ld->isNonTemporal(),
19451 Ld->isInvariant(), Ld->getAlignment());
19452 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19453 Ld->getPointerInfo().getWithOffset(4),
19454 Ld->isVolatile(), Ld->isNonTemporal(),
19456 MinAlign(Ld->getAlignment(), 4));
19458 SDValue NewChain = LoLd.getValue(1);
19459 if (TokenFactorIndex != -1) {
19460 Ops.push_back(LoLd);
19461 Ops.push_back(HiLd);
19462 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19465 LoAddr = St->getBasePtr();
19466 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19467 DAG.getConstant(4, MVT::i32));
19469 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19470 St->getPointerInfo(),
19471 St->isVolatile(), St->isNonTemporal(),
19472 St->getAlignment());
19473 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19474 St->getPointerInfo().getWithOffset(4),
19476 St->isNonTemporal(),
19477 MinAlign(St->getAlignment(), 4));
19478 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19483 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19484 /// and return the operands for the horizontal operation in LHS and RHS. A
19485 /// horizontal operation performs the binary operation on successive elements
19486 /// of its first operand, then on successive elements of its second operand,
19487 /// returning the resulting values in a vector. For example, if
19488 /// A = < float a0, float a1, float a2, float a3 >
19490 /// B = < float b0, float b1, float b2, float b3 >
19491 /// then the result of doing a horizontal operation on A and B is
19492 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19493 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19494 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19495 /// set to A, RHS to B, and the routine returns 'true'.
19496 /// Note that the binary operation should have the property that if one of the
19497 /// operands is UNDEF then the result is UNDEF.
19498 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19499 // Look for the following pattern: if
19500 // A = < float a0, float a1, float a2, float a3 >
19501 // B = < float b0, float b1, float b2, float b3 >
19503 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19504 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19505 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19506 // which is A horizontal-op B.
19508 // At least one of the operands should be a vector shuffle.
19509 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19510 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19513 MVT VT = LHS.getSimpleValueType();
19515 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19516 "Unsupported vector type for horizontal add/sub");
19518 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19519 // operate independently on 128-bit lanes.
19520 unsigned NumElts = VT.getVectorNumElements();
19521 unsigned NumLanes = VT.getSizeInBits()/128;
19522 unsigned NumLaneElts = NumElts / NumLanes;
19523 assert((NumLaneElts % 2 == 0) &&
19524 "Vector type should have an even number of elements in each lane");
19525 unsigned HalfLaneElts = NumLaneElts/2;
19527 // View LHS in the form
19528 // LHS = VECTOR_SHUFFLE A, B, LMask
19529 // If LHS is not a shuffle then pretend it is the shuffle
19530 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19531 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19534 SmallVector<int, 16> LMask(NumElts);
19535 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19536 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19537 A = LHS.getOperand(0);
19538 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19539 B = LHS.getOperand(1);
19540 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19541 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19543 if (LHS.getOpcode() != ISD::UNDEF)
19545 for (unsigned i = 0; i != NumElts; ++i)
19549 // Likewise, view RHS in the form
19550 // RHS = VECTOR_SHUFFLE C, D, RMask
19552 SmallVector<int, 16> RMask(NumElts);
19553 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19554 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19555 C = RHS.getOperand(0);
19556 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19557 D = RHS.getOperand(1);
19558 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19559 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19561 if (RHS.getOpcode() != ISD::UNDEF)
19563 for (unsigned i = 0; i != NumElts; ++i)
19567 // Check that the shuffles are both shuffling the same vectors.
19568 if (!(A == C && B == D) && !(A == D && B == C))
19571 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19572 if (!A.getNode() && !B.getNode())
19575 // If A and B occur in reverse order in RHS, then "swap" them (which means
19576 // rewriting the mask).
19578 CommuteVectorShuffleMask(RMask, NumElts);
19580 // At this point LHS and RHS are equivalent to
19581 // LHS = VECTOR_SHUFFLE A, B, LMask
19582 // RHS = VECTOR_SHUFFLE A, B, RMask
19583 // Check that the masks correspond to performing a horizontal operation.
19584 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19585 for (unsigned i = 0; i != NumLaneElts; ++i) {
19586 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19588 // Ignore any UNDEF components.
19589 if (LIdx < 0 || RIdx < 0 ||
19590 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19591 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19594 // Check that successive elements are being operated on. If not, this is
19595 // not a horizontal operation.
19596 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19597 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19598 if (!(LIdx == Index && RIdx == Index + 1) &&
19599 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19604 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19605 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19609 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19610 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19611 const X86Subtarget *Subtarget) {
19612 EVT VT = N->getValueType(0);
19613 SDValue LHS = N->getOperand(0);
19614 SDValue RHS = N->getOperand(1);
19616 // Try to synthesize horizontal adds from adds of shuffles.
19617 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19618 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19619 isHorizontalBinOp(LHS, RHS, true))
19620 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19624 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19625 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19626 const X86Subtarget *Subtarget) {
19627 EVT VT = N->getValueType(0);
19628 SDValue LHS = N->getOperand(0);
19629 SDValue RHS = N->getOperand(1);
19631 // Try to synthesize horizontal subs from subs of shuffles.
19632 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19633 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19634 isHorizontalBinOp(LHS, RHS, false))
19635 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19639 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19640 /// X86ISD::FXOR nodes.
19641 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19642 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19643 // F[X]OR(0.0, x) -> x
19644 // F[X]OR(x, 0.0) -> x
19645 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19646 if (C->getValueAPF().isPosZero())
19647 return N->getOperand(1);
19648 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19649 if (C->getValueAPF().isPosZero())
19650 return N->getOperand(0);
19654 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19655 /// X86ISD::FMAX nodes.
19656 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19657 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19659 // Only perform optimizations if UnsafeMath is used.
19660 if (!DAG.getTarget().Options.UnsafeFPMath)
19663 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19664 // into FMINC and FMAXC, which are Commutative operations.
19665 unsigned NewOp = 0;
19666 switch (N->getOpcode()) {
19667 default: llvm_unreachable("unknown opcode");
19668 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19669 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19672 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19673 N->getOperand(0), N->getOperand(1));
19676 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19677 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19678 // FAND(0.0, x) -> 0.0
19679 // FAND(x, 0.0) -> 0.0
19680 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19681 if (C->getValueAPF().isPosZero())
19682 return N->getOperand(0);
19683 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19684 if (C->getValueAPF().isPosZero())
19685 return N->getOperand(1);
19689 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19690 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19691 // FANDN(x, 0.0) -> 0.0
19692 // FANDN(0.0, x) -> x
19693 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19694 if (C->getValueAPF().isPosZero())
19695 return N->getOperand(1);
19696 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19697 if (C->getValueAPF().isPosZero())
19698 return N->getOperand(1);
19702 static SDValue PerformBTCombine(SDNode *N,
19704 TargetLowering::DAGCombinerInfo &DCI) {
19705 // BT ignores high bits in the bit index operand.
19706 SDValue Op1 = N->getOperand(1);
19707 if (Op1.hasOneUse()) {
19708 unsigned BitWidth = Op1.getValueSizeInBits();
19709 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19710 APInt KnownZero, KnownOne;
19711 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19712 !DCI.isBeforeLegalizeOps());
19713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19714 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19715 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19716 DCI.CommitTargetLoweringOpt(TLO);
19721 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19722 SDValue Op = N->getOperand(0);
19723 if (Op.getOpcode() == ISD::BITCAST)
19724 Op = Op.getOperand(0);
19725 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19726 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19727 VT.getVectorElementType().getSizeInBits() ==
19728 OpVT.getVectorElementType().getSizeInBits()) {
19729 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19734 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19735 const X86Subtarget *Subtarget) {
19736 EVT VT = N->getValueType(0);
19737 if (!VT.isVector())
19740 SDValue N0 = N->getOperand(0);
19741 SDValue N1 = N->getOperand(1);
19742 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19745 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19746 // both SSE and AVX2 since there is no sign-extended shift right
19747 // operation on a vector with 64-bit elements.
19748 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19749 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19750 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19751 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19752 SDValue N00 = N0.getOperand(0);
19754 // EXTLOAD has a better solution on AVX2,
19755 // it may be replaced with X86ISD::VSEXT node.
19756 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19757 if (!ISD::isNormalLoad(N00.getNode()))
19760 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19761 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19763 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19769 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19770 TargetLowering::DAGCombinerInfo &DCI,
19771 const X86Subtarget *Subtarget) {
19772 if (!DCI.isBeforeLegalizeOps())
19775 if (!Subtarget->hasFp256())
19778 EVT VT = N->getValueType(0);
19779 if (VT.isVector() && VT.getSizeInBits() == 256) {
19780 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19788 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19789 const X86Subtarget* Subtarget) {
19791 EVT VT = N->getValueType(0);
19793 // Let legalize expand this if it isn't a legal type yet.
19794 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19797 EVT ScalarVT = VT.getScalarType();
19798 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19799 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19802 SDValue A = N->getOperand(0);
19803 SDValue B = N->getOperand(1);
19804 SDValue C = N->getOperand(2);
19806 bool NegA = (A.getOpcode() == ISD::FNEG);
19807 bool NegB = (B.getOpcode() == ISD::FNEG);
19808 bool NegC = (C.getOpcode() == ISD::FNEG);
19810 // Negative multiplication when NegA xor NegB
19811 bool NegMul = (NegA != NegB);
19813 A = A.getOperand(0);
19815 B = B.getOperand(0);
19817 C = C.getOperand(0);
19821 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19823 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19825 return DAG.getNode(Opcode, dl, VT, A, B, C);
19828 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19829 TargetLowering::DAGCombinerInfo &DCI,
19830 const X86Subtarget *Subtarget) {
19831 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19832 // (and (i32 x86isd::setcc_carry), 1)
19833 // This eliminates the zext. This transformation is necessary because
19834 // ISD::SETCC is always legalized to i8.
19836 SDValue N0 = N->getOperand(0);
19837 EVT VT = N->getValueType(0);
19839 if (N0.getOpcode() == ISD::AND &&
19841 N0.getOperand(0).hasOneUse()) {
19842 SDValue N00 = N0.getOperand(0);
19843 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19844 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19845 if (!C || C->getZExtValue() != 1)
19847 return DAG.getNode(ISD::AND, dl, VT,
19848 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19849 N00.getOperand(0), N00.getOperand(1)),
19850 DAG.getConstant(1, VT));
19854 if (N0.getOpcode() == ISD::TRUNCATE &&
19856 N0.getOperand(0).hasOneUse()) {
19857 SDValue N00 = N0.getOperand(0);
19858 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19859 return DAG.getNode(ISD::AND, dl, VT,
19860 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19861 N00.getOperand(0), N00.getOperand(1)),
19862 DAG.getConstant(1, VT));
19865 if (VT.is256BitVector()) {
19866 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19874 // Optimize x == -y --> x+y == 0
19875 // x != -y --> x+y != 0
19876 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19877 const X86Subtarget* Subtarget) {
19878 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19879 SDValue LHS = N->getOperand(0);
19880 SDValue RHS = N->getOperand(1);
19881 EVT VT = N->getValueType(0);
19884 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19885 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19886 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19887 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19888 LHS.getValueType(), RHS, LHS.getOperand(1));
19889 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19890 addV, DAG.getConstant(0, addV.getValueType()), CC);
19892 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19894 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19895 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19896 RHS.getValueType(), LHS, RHS.getOperand(1));
19897 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19898 addV, DAG.getConstant(0, addV.getValueType()), CC);
19901 if (VT.getScalarType() == MVT::i1) {
19902 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19903 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19904 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19905 if (!IsSEXT0 && !IsVZero0)
19907 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19908 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19909 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19911 if (!IsSEXT1 && !IsVZero1)
19914 if (IsSEXT0 && IsVZero1) {
19915 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19916 if (CC == ISD::SETEQ)
19917 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19918 return LHS.getOperand(0);
19920 if (IsSEXT1 && IsVZero0) {
19921 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19922 if (CC == ISD::SETEQ)
19923 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19924 return RHS.getOperand(0);
19931 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19932 // as "sbb reg,reg", since it can be extended without zext and produces
19933 // an all-ones bit which is more useful than 0/1 in some cases.
19934 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19937 return DAG.getNode(ISD::AND, DL, VT,
19938 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19939 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19940 DAG.getConstant(1, VT));
19941 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19942 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19943 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19944 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19947 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19948 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19949 TargetLowering::DAGCombinerInfo &DCI,
19950 const X86Subtarget *Subtarget) {
19952 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19953 SDValue EFLAGS = N->getOperand(1);
19955 if (CC == X86::COND_A) {
19956 // Try to convert COND_A into COND_B in an attempt to facilitate
19957 // materializing "setb reg".
19959 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19960 // cannot take an immediate as its first operand.
19962 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19963 EFLAGS.getValueType().isInteger() &&
19964 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19965 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19966 EFLAGS.getNode()->getVTList(),
19967 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19968 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19969 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19973 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19974 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19976 if (CC == X86::COND_B)
19977 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19981 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19982 if (Flags.getNode()) {
19983 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19984 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19990 // Optimize branch condition evaluation.
19992 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19993 TargetLowering::DAGCombinerInfo &DCI,
19994 const X86Subtarget *Subtarget) {
19996 SDValue Chain = N->getOperand(0);
19997 SDValue Dest = N->getOperand(1);
19998 SDValue EFLAGS = N->getOperand(3);
19999 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20003 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20004 if (Flags.getNode()) {
20005 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20006 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20013 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20014 const X86TargetLowering *XTLI) {
20015 SDValue Op0 = N->getOperand(0);
20016 EVT InVT = Op0->getValueType(0);
20018 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20019 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20021 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20022 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20023 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20026 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20027 // a 32-bit target where SSE doesn't support i64->FP operations.
20028 if (Op0.getOpcode() == ISD::LOAD) {
20029 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20030 EVT VT = Ld->getValueType(0);
20031 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20032 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20033 !XTLI->getSubtarget()->is64Bit() &&
20035 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20036 Ld->getChain(), Op0, DAG);
20037 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20044 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20045 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20046 X86TargetLowering::DAGCombinerInfo &DCI) {
20047 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20048 // the result is either zero or one (depending on the input carry bit).
20049 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20050 if (X86::isZeroNode(N->getOperand(0)) &&
20051 X86::isZeroNode(N->getOperand(1)) &&
20052 // We don't have a good way to replace an EFLAGS use, so only do this when
20054 SDValue(N, 1).use_empty()) {
20056 EVT VT = N->getValueType(0);
20057 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20058 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20059 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20060 DAG.getConstant(X86::COND_B,MVT::i8),
20062 DAG.getConstant(1, VT));
20063 return DCI.CombineTo(N, Res1, CarryOut);
20069 // fold (add Y, (sete X, 0)) -> adc 0, Y
20070 // (add Y, (setne X, 0)) -> sbb -1, Y
20071 // (sub (sete X, 0), Y) -> sbb 0, Y
20072 // (sub (setne X, 0), Y) -> adc -1, Y
20073 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20076 // Look through ZExts.
20077 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20078 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20081 SDValue SetCC = Ext.getOperand(0);
20082 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20085 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20086 if (CC != X86::COND_E && CC != X86::COND_NE)
20089 SDValue Cmp = SetCC.getOperand(1);
20090 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20091 !X86::isZeroNode(Cmp.getOperand(1)) ||
20092 !Cmp.getOperand(0).getValueType().isInteger())
20095 SDValue CmpOp0 = Cmp.getOperand(0);
20096 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20097 DAG.getConstant(1, CmpOp0.getValueType()));
20099 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20100 if (CC == X86::COND_NE)
20101 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20102 DL, OtherVal.getValueType(), OtherVal,
20103 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20104 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20105 DL, OtherVal.getValueType(), OtherVal,
20106 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20109 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20110 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20111 const X86Subtarget *Subtarget) {
20112 EVT VT = N->getValueType(0);
20113 SDValue Op0 = N->getOperand(0);
20114 SDValue Op1 = N->getOperand(1);
20116 // Try to synthesize horizontal adds from adds of shuffles.
20117 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20118 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20119 isHorizontalBinOp(Op0, Op1, true))
20120 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20122 return OptimizeConditionalInDecrement(N, DAG);
20125 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20126 const X86Subtarget *Subtarget) {
20127 SDValue Op0 = N->getOperand(0);
20128 SDValue Op1 = N->getOperand(1);
20130 // X86 can't encode an immediate LHS of a sub. See if we can push the
20131 // negation into a preceding instruction.
20132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20133 // If the RHS of the sub is a XOR with one use and a constant, invert the
20134 // immediate. Then add one to the LHS of the sub so we can turn
20135 // X-Y -> X+~Y+1, saving one register.
20136 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20137 isa<ConstantSDNode>(Op1.getOperand(1))) {
20138 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20139 EVT VT = Op0.getValueType();
20140 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20142 DAG.getConstant(~XorC, VT));
20143 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20144 DAG.getConstant(C->getAPIntValue()+1, VT));
20148 // Try to synthesize horizontal adds from adds of shuffles.
20149 EVT VT = N->getValueType(0);
20150 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20151 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20152 isHorizontalBinOp(Op0, Op1, true))
20153 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20155 return OptimizeConditionalInDecrement(N, DAG);
20158 /// performVZEXTCombine - Performs build vector combines
20159 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20160 TargetLowering::DAGCombinerInfo &DCI,
20161 const X86Subtarget *Subtarget) {
20162 // (vzext (bitcast (vzext (x)) -> (vzext x)
20163 SDValue In = N->getOperand(0);
20164 while (In.getOpcode() == ISD::BITCAST)
20165 In = In.getOperand(0);
20167 if (In.getOpcode() != X86ISD::VZEXT)
20170 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20174 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20175 DAGCombinerInfo &DCI) const {
20176 SelectionDAG &DAG = DCI.DAG;
20177 switch (N->getOpcode()) {
20179 case ISD::EXTRACT_VECTOR_ELT:
20180 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20182 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20183 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20184 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20185 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20186 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20187 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20190 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20191 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20192 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20193 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20194 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20195 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20196 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20197 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20198 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20200 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20202 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20203 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20204 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20205 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20206 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20207 case ISD::ANY_EXTEND:
20208 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20209 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20210 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20211 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20212 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20213 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20214 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20215 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20216 case X86ISD::SHUFP: // Handle all target specific shuffles
20217 case X86ISD::PALIGNR:
20218 case X86ISD::UNPCKH:
20219 case X86ISD::UNPCKL:
20220 case X86ISD::MOVHLPS:
20221 case X86ISD::MOVLHPS:
20222 case X86ISD::PSHUFD:
20223 case X86ISD::PSHUFHW:
20224 case X86ISD::PSHUFLW:
20225 case X86ISD::MOVSS:
20226 case X86ISD::MOVSD:
20227 case X86ISD::VPERMILP:
20228 case X86ISD::VPERM2X128:
20229 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20230 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20236 /// isTypeDesirableForOp - Return true if the target has native support for
20237 /// the specified value type and it is 'desirable' to use the type for the
20238 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20239 /// instruction encodings are longer and some i16 instructions are slow.
20240 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20241 if (!isTypeLegal(VT))
20243 if (VT != MVT::i16)
20250 case ISD::SIGN_EXTEND:
20251 case ISD::ZERO_EXTEND:
20252 case ISD::ANY_EXTEND:
20265 /// IsDesirableToPromoteOp - This method query the target whether it is
20266 /// beneficial for dag combiner to promote the specified node. If true, it
20267 /// should return the desired promotion type by reference.
20268 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20269 EVT VT = Op.getValueType();
20270 if (VT != MVT::i16)
20273 bool Promote = false;
20274 bool Commute = false;
20275 switch (Op.getOpcode()) {
20278 LoadSDNode *LD = cast<LoadSDNode>(Op);
20279 // If the non-extending load has a single use and it's not live out, then it
20280 // might be folded.
20281 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20282 Op.hasOneUse()*/) {
20283 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20284 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20285 // The only case where we'd want to promote LOAD (rather then it being
20286 // promoted as an operand is when it's only use is liveout.
20287 if (UI->getOpcode() != ISD::CopyToReg)
20294 case ISD::SIGN_EXTEND:
20295 case ISD::ZERO_EXTEND:
20296 case ISD::ANY_EXTEND:
20301 SDValue N0 = Op.getOperand(0);
20302 // Look out for (store (shl (load), x)).
20303 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20316 SDValue N0 = Op.getOperand(0);
20317 SDValue N1 = Op.getOperand(1);
20318 if (!Commute && MayFoldLoad(N1))
20320 // Avoid disabling potential load folding opportunities.
20321 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20323 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20333 //===----------------------------------------------------------------------===//
20334 // X86 Inline Assembly Support
20335 //===----------------------------------------------------------------------===//
20338 // Helper to match a string separated by whitespace.
20339 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20340 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20342 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20343 StringRef piece(*args[i]);
20344 if (!s.startswith(piece)) // Check if the piece matches.
20347 s = s.substr(piece.size());
20348 StringRef::size_type pos = s.find_first_not_of(" \t");
20349 if (pos == 0) // We matched a prefix.
20357 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20360 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20362 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20363 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20364 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20365 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20367 if (AsmPieces.size() == 3)
20369 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20376 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20377 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20379 std::string AsmStr = IA->getAsmString();
20381 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20382 if (!Ty || Ty->getBitWidth() % 16 != 0)
20385 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20386 SmallVector<StringRef, 4> AsmPieces;
20387 SplitString(AsmStr, AsmPieces, ";\n");
20389 switch (AsmPieces.size()) {
20390 default: return false;
20392 // FIXME: this should verify that we are targeting a 486 or better. If not,
20393 // we will turn this bswap into something that will be lowered to logical
20394 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20395 // lower so don't worry about this.
20397 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20398 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20399 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20400 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20401 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20402 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20403 // No need to check constraints, nothing other than the equivalent of
20404 // "=r,0" would be valid here.
20405 return IntrinsicLowering::LowerToByteSwap(CI);
20408 // rorw $$8, ${0:w} --> llvm.bswap.i16
20409 if (CI->getType()->isIntegerTy(16) &&
20410 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20411 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20412 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20414 const std::string &ConstraintsStr = IA->getConstraintString();
20415 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20416 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20417 if (clobbersFlagRegisters(AsmPieces))
20418 return IntrinsicLowering::LowerToByteSwap(CI);
20422 if (CI->getType()->isIntegerTy(32) &&
20423 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20424 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20425 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20426 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20428 const std::string &ConstraintsStr = IA->getConstraintString();
20429 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20430 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20431 if (clobbersFlagRegisters(AsmPieces))
20432 return IntrinsicLowering::LowerToByteSwap(CI);
20435 if (CI->getType()->isIntegerTy(64)) {
20436 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20437 if (Constraints.size() >= 2 &&
20438 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20439 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20440 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20441 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20442 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20443 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20444 return IntrinsicLowering::LowerToByteSwap(CI);
20452 /// getConstraintType - Given a constraint letter, return the type of
20453 /// constraint it is for this target.
20454 X86TargetLowering::ConstraintType
20455 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20456 if (Constraint.size() == 1) {
20457 switch (Constraint[0]) {
20468 return C_RegisterClass;
20492 return TargetLowering::getConstraintType(Constraint);
20495 /// Examine constraint type and operand type and determine a weight value.
20496 /// This object must already have been set up with the operand type
20497 /// and the current alternative constraint selected.
20498 TargetLowering::ConstraintWeight
20499 X86TargetLowering::getSingleConstraintMatchWeight(
20500 AsmOperandInfo &info, const char *constraint) const {
20501 ConstraintWeight weight = CW_Invalid;
20502 Value *CallOperandVal = info.CallOperandVal;
20503 // If we don't have a value, we can't do a match,
20504 // but allow it at the lowest weight.
20505 if (!CallOperandVal)
20507 Type *type = CallOperandVal->getType();
20508 // Look at the constraint type.
20509 switch (*constraint) {
20511 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20522 if (CallOperandVal->getType()->isIntegerTy())
20523 weight = CW_SpecificReg;
20528 if (type->isFloatingPointTy())
20529 weight = CW_SpecificReg;
20532 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20533 weight = CW_SpecificReg;
20537 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20538 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20539 weight = CW_Register;
20542 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20543 if (C->getZExtValue() <= 31)
20544 weight = CW_Constant;
20548 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20549 if (C->getZExtValue() <= 63)
20550 weight = CW_Constant;
20554 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20555 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20556 weight = CW_Constant;
20560 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20561 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20562 weight = CW_Constant;
20566 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20567 if (C->getZExtValue() <= 3)
20568 weight = CW_Constant;
20572 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20573 if (C->getZExtValue() <= 0xff)
20574 weight = CW_Constant;
20579 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20580 weight = CW_Constant;
20584 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20585 if ((C->getSExtValue() >= -0x80000000LL) &&
20586 (C->getSExtValue() <= 0x7fffffffLL))
20587 weight = CW_Constant;
20591 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20592 if (C->getZExtValue() <= 0xffffffff)
20593 weight = CW_Constant;
20600 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20601 /// with another that has more specific requirements based on the type of the
20602 /// corresponding operand.
20603 const char *X86TargetLowering::
20604 LowerXConstraint(EVT ConstraintVT) const {
20605 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20606 // 'f' like normal targets.
20607 if (ConstraintVT.isFloatingPoint()) {
20608 if (Subtarget->hasSSE2())
20610 if (Subtarget->hasSSE1())
20614 return TargetLowering::LowerXConstraint(ConstraintVT);
20617 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20618 /// vector. If it is invalid, don't add anything to Ops.
20619 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20620 std::string &Constraint,
20621 std::vector<SDValue>&Ops,
20622 SelectionDAG &DAG) const {
20625 // Only support length 1 constraints for now.
20626 if (Constraint.length() > 1) return;
20628 char ConstraintLetter = Constraint[0];
20629 switch (ConstraintLetter) {
20632 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20633 if (C->getZExtValue() <= 31) {
20634 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20640 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20641 if (C->getZExtValue() <= 63) {
20642 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20648 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20649 if (isInt<8>(C->getSExtValue())) {
20650 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20656 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20657 if (C->getZExtValue() <= 255) {
20658 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20664 // 32-bit signed value
20665 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20666 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20667 C->getSExtValue())) {
20668 // Widen to 64 bits here to get it sign extended.
20669 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20672 // FIXME gcc accepts some relocatable values here too, but only in certain
20673 // memory models; it's complicated.
20678 // 32-bit unsigned value
20679 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20680 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20681 C->getZExtValue())) {
20682 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20686 // FIXME gcc accepts some relocatable values here too, but only in certain
20687 // memory models; it's complicated.
20691 // Literal immediates are always ok.
20692 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20693 // Widen to 64 bits here to get it sign extended.
20694 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20698 // In any sort of PIC mode addresses need to be computed at runtime by
20699 // adding in a register or some sort of table lookup. These can't
20700 // be used as immediates.
20701 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20704 // If we are in non-pic codegen mode, we allow the address of a global (with
20705 // an optional displacement) to be used with 'i'.
20706 GlobalAddressSDNode *GA = nullptr;
20707 int64_t Offset = 0;
20709 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20711 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20712 Offset += GA->getOffset();
20714 } else if (Op.getOpcode() == ISD::ADD) {
20715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20716 Offset += C->getZExtValue();
20717 Op = Op.getOperand(0);
20720 } else if (Op.getOpcode() == ISD::SUB) {
20721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20722 Offset += -C->getZExtValue();
20723 Op = Op.getOperand(0);
20728 // Otherwise, this isn't something we can handle, reject it.
20732 const GlobalValue *GV = GA->getGlobal();
20733 // If we require an extra load to get this address, as in PIC mode, we
20734 // can't accept it.
20735 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20736 getTargetMachine())))
20739 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20740 GA->getValueType(0), Offset);
20745 if (Result.getNode()) {
20746 Ops.push_back(Result);
20749 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20752 std::pair<unsigned, const TargetRegisterClass*>
20753 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20755 // First, see if this is a constraint that directly corresponds to an LLVM
20757 if (Constraint.size() == 1) {
20758 // GCC Constraint Letters
20759 switch (Constraint[0]) {
20761 // TODO: Slight differences here in allocation order and leaving
20762 // RIP in the class. Do they matter any more here than they do
20763 // in the normal allocation?
20764 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20765 if (Subtarget->is64Bit()) {
20766 if (VT == MVT::i32 || VT == MVT::f32)
20767 return std::make_pair(0U, &X86::GR32RegClass);
20768 if (VT == MVT::i16)
20769 return std::make_pair(0U, &X86::GR16RegClass);
20770 if (VT == MVT::i8 || VT == MVT::i1)
20771 return std::make_pair(0U, &X86::GR8RegClass);
20772 if (VT == MVT::i64 || VT == MVT::f64)
20773 return std::make_pair(0U, &X86::GR64RegClass);
20776 // 32-bit fallthrough
20777 case 'Q': // Q_REGS
20778 if (VT == MVT::i32 || VT == MVT::f32)
20779 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20780 if (VT == MVT::i16)
20781 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20782 if (VT == MVT::i8 || VT == MVT::i1)
20783 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20784 if (VT == MVT::i64)
20785 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20787 case 'r': // GENERAL_REGS
20788 case 'l': // INDEX_REGS
20789 if (VT == MVT::i8 || VT == MVT::i1)
20790 return std::make_pair(0U, &X86::GR8RegClass);
20791 if (VT == MVT::i16)
20792 return std::make_pair(0U, &X86::GR16RegClass);
20793 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20794 return std::make_pair(0U, &X86::GR32RegClass);
20795 return std::make_pair(0U, &X86::GR64RegClass);
20796 case 'R': // LEGACY_REGS
20797 if (VT == MVT::i8 || VT == MVT::i1)
20798 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20799 if (VT == MVT::i16)
20800 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20801 if (VT == MVT::i32 || !Subtarget->is64Bit())
20802 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20803 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20804 case 'f': // FP Stack registers.
20805 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20806 // value to the correct fpstack register class.
20807 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20808 return std::make_pair(0U, &X86::RFP32RegClass);
20809 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20810 return std::make_pair(0U, &X86::RFP64RegClass);
20811 return std::make_pair(0U, &X86::RFP80RegClass);
20812 case 'y': // MMX_REGS if MMX allowed.
20813 if (!Subtarget->hasMMX()) break;
20814 return std::make_pair(0U, &X86::VR64RegClass);
20815 case 'Y': // SSE_REGS if SSE2 allowed
20816 if (!Subtarget->hasSSE2()) break;
20818 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20819 if (!Subtarget->hasSSE1()) break;
20821 switch (VT.SimpleTy) {
20823 // Scalar SSE types.
20826 return std::make_pair(0U, &X86::FR32RegClass);
20829 return std::make_pair(0U, &X86::FR64RegClass);
20837 return std::make_pair(0U, &X86::VR128RegClass);
20845 return std::make_pair(0U, &X86::VR256RegClass);
20850 return std::make_pair(0U, &X86::VR512RegClass);
20856 // Use the default implementation in TargetLowering to convert the register
20857 // constraint into a member of a register class.
20858 std::pair<unsigned, const TargetRegisterClass*> Res;
20859 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20861 // Not found as a standard register?
20863 // Map st(0) -> st(7) -> ST0
20864 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20865 tolower(Constraint[1]) == 's' &&
20866 tolower(Constraint[2]) == 't' &&
20867 Constraint[3] == '(' &&
20868 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20869 Constraint[5] == ')' &&
20870 Constraint[6] == '}') {
20872 Res.first = X86::ST0+Constraint[4]-'0';
20873 Res.second = &X86::RFP80RegClass;
20877 // GCC allows "st(0)" to be called just plain "st".
20878 if (StringRef("{st}").equals_lower(Constraint)) {
20879 Res.first = X86::ST0;
20880 Res.second = &X86::RFP80RegClass;
20885 if (StringRef("{flags}").equals_lower(Constraint)) {
20886 Res.first = X86::EFLAGS;
20887 Res.second = &X86::CCRRegClass;
20891 // 'A' means EAX + EDX.
20892 if (Constraint == "A") {
20893 Res.first = X86::EAX;
20894 Res.second = &X86::GR32_ADRegClass;
20900 // Otherwise, check to see if this is a register class of the wrong value
20901 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20902 // turn into {ax},{dx}.
20903 if (Res.second->hasType(VT))
20904 return Res; // Correct type already, nothing to do.
20906 // All of the single-register GCC register classes map their values onto
20907 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20908 // really want an 8-bit or 32-bit register, map to the appropriate register
20909 // class and return the appropriate register.
20910 if (Res.second == &X86::GR16RegClass) {
20911 if (VT == MVT::i8 || VT == MVT::i1) {
20912 unsigned DestReg = 0;
20913 switch (Res.first) {
20915 case X86::AX: DestReg = X86::AL; break;
20916 case X86::DX: DestReg = X86::DL; break;
20917 case X86::CX: DestReg = X86::CL; break;
20918 case X86::BX: DestReg = X86::BL; break;
20921 Res.first = DestReg;
20922 Res.second = &X86::GR8RegClass;
20924 } else if (VT == MVT::i32 || VT == MVT::f32) {
20925 unsigned DestReg = 0;
20926 switch (Res.first) {
20928 case X86::AX: DestReg = X86::EAX; break;
20929 case X86::DX: DestReg = X86::EDX; break;
20930 case X86::CX: DestReg = X86::ECX; break;
20931 case X86::BX: DestReg = X86::EBX; break;
20932 case X86::SI: DestReg = X86::ESI; break;
20933 case X86::DI: DestReg = X86::EDI; break;
20934 case X86::BP: DestReg = X86::EBP; break;
20935 case X86::SP: DestReg = X86::ESP; break;
20938 Res.first = DestReg;
20939 Res.second = &X86::GR32RegClass;
20941 } else if (VT == MVT::i64 || VT == MVT::f64) {
20942 unsigned DestReg = 0;
20943 switch (Res.first) {
20945 case X86::AX: DestReg = X86::RAX; break;
20946 case X86::DX: DestReg = X86::RDX; break;
20947 case X86::CX: DestReg = X86::RCX; break;
20948 case X86::BX: DestReg = X86::RBX; break;
20949 case X86::SI: DestReg = X86::RSI; break;
20950 case X86::DI: DestReg = X86::RDI; break;
20951 case X86::BP: DestReg = X86::RBP; break;
20952 case X86::SP: DestReg = X86::RSP; break;
20955 Res.first = DestReg;
20956 Res.second = &X86::GR64RegClass;
20959 } else if (Res.second == &X86::FR32RegClass ||
20960 Res.second == &X86::FR64RegClass ||
20961 Res.second == &X86::VR128RegClass ||
20962 Res.second == &X86::VR256RegClass ||
20963 Res.second == &X86::FR32XRegClass ||
20964 Res.second == &X86::FR64XRegClass ||
20965 Res.second == &X86::VR128XRegClass ||
20966 Res.second == &X86::VR256XRegClass ||
20967 Res.second == &X86::VR512RegClass) {
20968 // Handle references to XMM physical registers that got mapped into the
20969 // wrong class. This can happen with constraints like {xmm0} where the
20970 // target independent register mapper will just pick the first match it can
20971 // find, ignoring the required type.
20973 if (VT == MVT::f32 || VT == MVT::i32)
20974 Res.second = &X86::FR32RegClass;
20975 else if (VT == MVT::f64 || VT == MVT::i64)
20976 Res.second = &X86::FR64RegClass;
20977 else if (X86::VR128RegClass.hasType(VT))
20978 Res.second = &X86::VR128RegClass;
20979 else if (X86::VR256RegClass.hasType(VT))
20980 Res.second = &X86::VR256RegClass;
20981 else if (X86::VR512RegClass.hasType(VT))
20982 Res.second = &X86::VR512RegClass;
20988 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20990 // Scaling factors are not free at all.
20991 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20992 // will take 2 allocations in the out of order engine instead of 1
20993 // for plain addressing mode, i.e. inst (reg1).
20995 // vaddps (%rsi,%drx), %ymm0, %ymm1
20996 // Requires two allocations (one for the load, one for the computation)
20998 // vaddps (%rsi), %ymm0, %ymm1
20999 // Requires just 1 allocation, i.e., freeing allocations for other operations
21000 // and having less micro operations to execute.
21002 // For some X86 architectures, this is even worse because for instance for
21003 // stores, the complex addressing mode forces the instruction to use the
21004 // "load" ports instead of the dedicated "store" port.
21005 // E.g., on Haswell:
21006 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21007 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21008 if (isLegalAddressingMode(AM, Ty))
21009 // Scale represents reg2 * scale, thus account for 1
21010 // as soon as we use a second register.
21011 return AM.Scale != 0;