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);
1043 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1044 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1045 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1046 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1047 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1048 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1049 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1050 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1051 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1052 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1053 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1055 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1060 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1064 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1066 // FIXME: Do we need to handle scalar-to-vector here?
1067 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1072 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1073 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1075 // i8 and i16 vectors are custom , because the source register and source
1076 // source memory operand types are not the same width. f32 vectors are
1077 // custom since the immediate controlling the insert encodes additional
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1080 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1081 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1082 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1086 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1089 // FIXME: these should be Legal but thats only for the case where
1090 // the index is constant. For now custom expand to deal with that.
1091 if (Subtarget->is64Bit()) {
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1093 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1097 if (Subtarget->hasSSE2()) {
1098 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1099 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1101 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1102 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1104 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1105 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1107 // In the customized shift lowering, the legal cases in AVX2 will be
1109 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1110 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1112 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1113 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1115 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1118 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1119 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1126 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1127 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1128 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1130 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1141 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1143 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1154 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1156 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1157 // even though v8i16 is a legal type.
1158 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1159 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1160 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1162 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1163 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1164 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1166 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1167 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1169 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1171 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1172 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1174 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1175 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1177 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1178 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1186 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1187 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1189 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1191 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1192 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1201 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1202 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1203 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1204 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1205 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1207 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1208 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1209 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1210 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1211 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1212 setOperationAction(ISD::FMA, MVT::f32, Legal);
1213 setOperationAction(ISD::FMA, MVT::f64, Legal);
1216 if (Subtarget->hasInt256()) {
1217 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1218 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1219 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1220 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1222 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1223 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1224 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1225 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1227 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1228 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1229 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1230 // Don't lower v32i8 because there is no 128-bit byte mul
1232 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1233 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1234 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1235 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1237 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1239 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1240 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1241 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1242 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1244 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1245 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1247 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1249 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1250 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1252 // Don't lower v32i8 because there is no 128-bit byte mul
1255 // In the customized shift lowering, the legal cases in AVX2 will be
1257 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1258 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1261 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1263 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1265 // Custom lower several nodes for 256-bit types.
1266 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1267 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1268 MVT VT = (MVT::SimpleValueType)i;
1270 // Extract subvector is special because the value type
1271 // (result) is 128-bit but the source is 256-bit wide.
1272 if (VT.is128BitVector())
1273 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1275 // Do not attempt to custom lower other non-256-bit vectors
1276 if (!VT.is256BitVector())
1279 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1280 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1281 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1282 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1283 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1284 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1285 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1288 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1289 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1290 MVT VT = (MVT::SimpleValueType)i;
1292 // Do not attempt to promote non-256-bit vectors
1293 if (!VT.is256BitVector())
1296 setOperationAction(ISD::AND, VT, Promote);
1297 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1298 setOperationAction(ISD::OR, VT, Promote);
1299 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1300 setOperationAction(ISD::XOR, VT, Promote);
1301 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1302 setOperationAction(ISD::LOAD, VT, Promote);
1303 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1304 setOperationAction(ISD::SELECT, VT, Promote);
1305 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1309 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1310 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1315 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1316 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1317 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1319 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1320 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1321 setOperationAction(ISD::XOR, MVT::i1, Legal);
1322 setOperationAction(ISD::OR, MVT::i1, Legal);
1323 setOperationAction(ISD::AND, MVT::i1, Legal);
1324 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1328 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1329 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1331 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1336 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1338 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1344 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1348 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1349 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1350 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1351 if (Subtarget->is64Bit()) {
1352 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1353 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1354 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1355 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1357 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1358 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1359 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1361 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1364 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1365 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1366 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1368 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1373 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1374 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1375 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1379 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1380 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1386 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1389 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1390 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1392 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1398 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1399 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1400 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1401 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1402 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1404 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1405 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1407 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1408 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1410 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1412 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1413 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1415 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1416 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1418 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1419 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1421 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1422 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1423 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1424 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1425 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1426 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1428 // Custom lower several nodes.
1429 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1430 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1431 MVT VT = (MVT::SimpleValueType)i;
1433 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1434 // Extract subvector is special because the value type
1435 // (result) is 256/128-bit but the source is 512-bit wide.
1436 if (VT.is128BitVector() || VT.is256BitVector())
1437 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1439 if (VT.getVectorElementType() == MVT::i1)
1440 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1442 // Do not attempt to custom lower other non-512-bit vectors
1443 if (!VT.is512BitVector())
1446 if ( EltSize >= 32) {
1447 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1448 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1449 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1450 setOperationAction(ISD::VSELECT, VT, Legal);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1452 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1453 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1456 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1457 MVT VT = (MVT::SimpleValueType)i;
1459 // Do not attempt to promote non-256-bit vectors
1460 if (!VT.is512BitVector())
1463 setOperationAction(ISD::SELECT, VT, Promote);
1464 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1468 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1469 // of this type with custom code.
1470 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1471 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1472 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1476 // We want to custom lower some of our intrinsics.
1477 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1478 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1479 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1480 if (!Subtarget->is64Bit())
1481 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1483 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1484 // handle type legalization for these operations here.
1486 // FIXME: We really should do custom legalization for addition and
1487 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1488 // than generic legalization for 64-bit multiplication-with-overflow, though.
1489 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1490 // Add/Sub/Mul with overflow operations are custom lowered.
1492 setOperationAction(ISD::SADDO, VT, Custom);
1493 setOperationAction(ISD::UADDO, VT, Custom);
1494 setOperationAction(ISD::SSUBO, VT, Custom);
1495 setOperationAction(ISD::USUBO, VT, Custom);
1496 setOperationAction(ISD::SMULO, VT, Custom);
1497 setOperationAction(ISD::UMULO, VT, Custom);
1500 // There are no 8-bit 3-address imul/mul instructions
1501 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1502 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1504 if (!Subtarget->is64Bit()) {
1505 // These libcalls are not available in 32-bit.
1506 setLibcallName(RTLIB::SHL_I128, nullptr);
1507 setLibcallName(RTLIB::SRL_I128, nullptr);
1508 setLibcallName(RTLIB::SRA_I128, nullptr);
1511 // Combine sin / cos into one node or libcall if possible.
1512 if (Subtarget->hasSinCos()) {
1513 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1514 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1515 if (Subtarget->isTargetDarwin()) {
1516 // For MacOSX, we don't want to the normal expansion of a libcall to
1517 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1519 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1520 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1524 if (Subtarget->isTargetWin64()) {
1525 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1526 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1527 setOperationAction(ISD::SREM, MVT::i128, Custom);
1528 setOperationAction(ISD::UREM, MVT::i128, Custom);
1529 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1530 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1533 // We have target-specific dag combine patterns for the following nodes:
1534 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1535 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1536 setTargetDAGCombine(ISD::VSELECT);
1537 setTargetDAGCombine(ISD::SELECT);
1538 setTargetDAGCombine(ISD::SHL);
1539 setTargetDAGCombine(ISD::SRA);
1540 setTargetDAGCombine(ISD::SRL);
1541 setTargetDAGCombine(ISD::OR);
1542 setTargetDAGCombine(ISD::AND);
1543 setTargetDAGCombine(ISD::ADD);
1544 setTargetDAGCombine(ISD::FADD);
1545 setTargetDAGCombine(ISD::FSUB);
1546 setTargetDAGCombine(ISD::FMA);
1547 setTargetDAGCombine(ISD::SUB);
1548 setTargetDAGCombine(ISD::LOAD);
1549 setTargetDAGCombine(ISD::STORE);
1550 setTargetDAGCombine(ISD::ZERO_EXTEND);
1551 setTargetDAGCombine(ISD::ANY_EXTEND);
1552 setTargetDAGCombine(ISD::SIGN_EXTEND);
1553 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1554 setTargetDAGCombine(ISD::TRUNCATE);
1555 setTargetDAGCombine(ISD::SINT_TO_FP);
1556 setTargetDAGCombine(ISD::SETCC);
1557 if (Subtarget->is64Bit())
1558 setTargetDAGCombine(ISD::MUL);
1559 setTargetDAGCombine(ISD::XOR);
1561 computeRegisterProperties();
1563 // On Darwin, -Os means optimize for size without hurting performance,
1564 // do not reduce the limit.
1565 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1566 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1567 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1568 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1569 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1570 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1571 setPrefLoopAlignment(4); // 2^4 bytes.
1573 // Predictable cmov don't hurt on atom because it's in-order.
1574 PredictableSelectIsExpensive = !Subtarget->isAtom();
1576 setPrefFunctionAlignment(4); // 2^4 bytes.
1579 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1581 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1583 if (Subtarget->hasAVX512())
1584 switch(VT.getVectorNumElements()) {
1585 case 8: return MVT::v8i1;
1586 case 16: return MVT::v16i1;
1589 return VT.changeVectorElementTypeToInteger();
1592 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1593 /// the desired ByVal argument alignment.
1594 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1597 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1598 if (VTy->getBitWidth() == 128)
1600 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1601 unsigned EltAlign = 0;
1602 getMaxByValAlign(ATy->getElementType(), EltAlign);
1603 if (EltAlign > MaxAlign)
1604 MaxAlign = EltAlign;
1605 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1606 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1607 unsigned EltAlign = 0;
1608 getMaxByValAlign(STy->getElementType(i), EltAlign);
1609 if (EltAlign > MaxAlign)
1610 MaxAlign = EltAlign;
1617 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1618 /// function arguments in the caller parameter area. For X86, aggregates
1619 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1620 /// are at 4-byte boundaries.
1621 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1622 if (Subtarget->is64Bit()) {
1623 // Max of 8 and alignment of type.
1624 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1631 if (Subtarget->hasSSE1())
1632 getMaxByValAlign(Ty, Align);
1636 /// getOptimalMemOpType - Returns the target specific optimal type for load
1637 /// and store operations as a result of memset, memcpy, and memmove
1638 /// lowering. If DstAlign is zero that means it's safe to destination
1639 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1640 /// means there isn't a need to check it against alignment requirement,
1641 /// probably because the source does not need to be loaded. If 'IsMemset' is
1642 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1643 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1644 /// source is constant so it does not need to be loaded.
1645 /// It returns EVT::Other if the type should be determined using generic
1646 /// target-independent logic.
1648 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1649 unsigned DstAlign, unsigned SrcAlign,
1650 bool IsMemset, bool ZeroMemset,
1652 MachineFunction &MF) const {
1653 const Function *F = MF.getFunction();
1654 if ((!IsMemset || ZeroMemset) &&
1655 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1656 Attribute::NoImplicitFloat)) {
1658 (Subtarget->isUnalignedMemAccessFast() ||
1659 ((DstAlign == 0 || DstAlign >= 16) &&
1660 (SrcAlign == 0 || SrcAlign >= 16)))) {
1662 if (Subtarget->hasInt256())
1664 if (Subtarget->hasFp256())
1667 if (Subtarget->hasSSE2())
1669 if (Subtarget->hasSSE1())
1671 } else if (!MemcpyStrSrc && Size >= 8 &&
1672 !Subtarget->is64Bit() &&
1673 Subtarget->hasSSE2()) {
1674 // Do not use f64 to lower memcpy if source is string constant. It's
1675 // better to use i32 to avoid the loads.
1679 if (Subtarget->is64Bit() && Size >= 8)
1684 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1686 return X86ScalarSSEf32;
1687 else if (VT == MVT::f64)
1688 return X86ScalarSSEf64;
1693 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1697 *Fast = Subtarget->isUnalignedMemAccessFast();
1701 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1702 /// current function. The returned value is a member of the
1703 /// MachineJumpTableInfo::JTEntryKind enum.
1704 unsigned X86TargetLowering::getJumpTableEncoding() const {
1705 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1707 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1708 Subtarget->isPICStyleGOT())
1709 return MachineJumpTableInfo::EK_Custom32;
1711 // Otherwise, use the normal jump table encoding heuristics.
1712 return TargetLowering::getJumpTableEncoding();
1716 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1717 const MachineBasicBlock *MBB,
1718 unsigned uid,MCContext &Ctx) const{
1719 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1720 Subtarget->isPICStyleGOT());
1721 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1723 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1724 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1727 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1729 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1730 SelectionDAG &DAG) const {
1731 if (!Subtarget->is64Bit())
1732 // This doesn't have SDLoc associated with it, but is not really the
1733 // same as a Register.
1734 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1738 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1739 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1741 const MCExpr *X86TargetLowering::
1742 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1743 MCContext &Ctx) const {
1744 // X86-64 uses RIP relative addressing based on the jump table label.
1745 if (Subtarget->isPICStyleRIPRel())
1746 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1748 // Otherwise, the reference is relative to the PIC base.
1749 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1752 // FIXME: Why this routine is here? Move to RegInfo!
1753 std::pair<const TargetRegisterClass*, uint8_t>
1754 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1755 const TargetRegisterClass *RRC = nullptr;
1757 switch (VT.SimpleTy) {
1759 return TargetLowering::findRepresentativeClass(VT);
1760 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1761 RRC = Subtarget->is64Bit() ?
1762 (const TargetRegisterClass*)&X86::GR64RegClass :
1763 (const TargetRegisterClass*)&X86::GR32RegClass;
1766 RRC = &X86::VR64RegClass;
1768 case MVT::f32: case MVT::f64:
1769 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1770 case MVT::v4f32: case MVT::v2f64:
1771 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1773 RRC = &X86::VR128RegClass;
1776 return std::make_pair(RRC, Cost);
1779 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1780 unsigned &Offset) const {
1781 if (!Subtarget->isTargetLinux())
1784 if (Subtarget->is64Bit()) {
1785 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1787 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1799 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1800 unsigned DestAS) const {
1801 assert(SrcAS != DestAS && "Expected different address spaces!");
1803 return SrcAS < 256 && DestAS < 256;
1806 //===----------------------------------------------------------------------===//
1807 // Return Value Calling Convention Implementation
1808 //===----------------------------------------------------------------------===//
1810 #include "X86GenCallingConv.inc"
1813 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1814 MachineFunction &MF, bool isVarArg,
1815 const SmallVectorImpl<ISD::OutputArg> &Outs,
1816 LLVMContext &Context) const {
1817 SmallVector<CCValAssign, 16> RVLocs;
1818 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1820 return CCInfo.CheckReturn(Outs, RetCC_X86);
1823 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1824 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1829 X86TargetLowering::LowerReturn(SDValue Chain,
1830 CallingConv::ID CallConv, bool isVarArg,
1831 const SmallVectorImpl<ISD::OutputArg> &Outs,
1832 const SmallVectorImpl<SDValue> &OutVals,
1833 SDLoc dl, SelectionDAG &DAG) const {
1834 MachineFunction &MF = DAG.getMachineFunction();
1835 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1837 SmallVector<CCValAssign, 16> RVLocs;
1838 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1839 RVLocs, *DAG.getContext());
1840 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1843 SmallVector<SDValue, 6> RetOps;
1844 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1845 // Operand #1 = Bytes To Pop
1846 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1849 // Copy the result values into the output registers.
1850 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1851 CCValAssign &VA = RVLocs[i];
1852 assert(VA.isRegLoc() && "Can only return in registers!");
1853 SDValue ValToCopy = OutVals[i];
1854 EVT ValVT = ValToCopy.getValueType();
1856 // Promote values to the appropriate types
1857 if (VA.getLocInfo() == CCValAssign::SExt)
1858 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1859 else if (VA.getLocInfo() == CCValAssign::ZExt)
1860 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1861 else if (VA.getLocInfo() == CCValAssign::AExt)
1862 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1863 else if (VA.getLocInfo() == CCValAssign::BCvt)
1864 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1866 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1867 "Unexpected FP-extend for return value.");
1869 // If this is x86-64, and we disabled SSE, we can't return FP values,
1870 // or SSE or MMX vectors.
1871 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1872 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1873 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1874 report_fatal_error("SSE register return with SSE disabled");
1876 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1877 // llvm-gcc has never done it right and no one has noticed, so this
1878 // should be OK for now.
1879 if (ValVT == MVT::f64 &&
1880 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1881 report_fatal_error("SSE2 register return with SSE2 disabled");
1883 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1884 // the RET instruction and handled by the FP Stackifier.
1885 if (VA.getLocReg() == X86::ST0 ||
1886 VA.getLocReg() == X86::ST1) {
1887 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1888 // change the value to the FP stack register class.
1889 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1890 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1891 RetOps.push_back(ValToCopy);
1892 // Don't emit a copytoreg.
1896 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1897 // which is returned in RAX / RDX.
1898 if (Subtarget->is64Bit()) {
1899 if (ValVT == MVT::x86mmx) {
1900 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1901 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1902 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1904 // If we don't have SSE2 available, convert to v4f32 so the generated
1905 // register is legal.
1906 if (!Subtarget->hasSSE2())
1907 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1912 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1913 Flag = Chain.getValue(1);
1914 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1917 // The x86-64 ABIs require that for returning structs by value we copy
1918 // the sret argument into %rax/%eax (depending on ABI) for the return.
1919 // Win32 requires us to put the sret argument to %eax as well.
1920 // We saved the argument into a virtual register in the entry block,
1921 // so now we copy the value out and into %rax/%eax.
1922 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1923 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1924 MachineFunction &MF = DAG.getMachineFunction();
1925 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1926 unsigned Reg = FuncInfo->getSRetReturnReg();
1928 "SRetReturnReg should have been set in LowerFormalArguments().");
1929 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1932 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1933 X86::RAX : X86::EAX;
1934 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1935 Flag = Chain.getValue(1);
1937 // RAX/EAX now acts like a return value.
1938 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1941 RetOps[0] = Chain; // Update chain.
1943 // Add the flag if we have it.
1945 RetOps.push_back(Flag);
1947 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1950 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1951 if (N->getNumValues() != 1)
1953 if (!N->hasNUsesOfValue(1, 0))
1956 SDValue TCChain = Chain;
1957 SDNode *Copy = *N->use_begin();
1958 if (Copy->getOpcode() == ISD::CopyToReg) {
1959 // If the copy has a glue operand, we conservatively assume it isn't safe to
1960 // perform a tail call.
1961 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1963 TCChain = Copy->getOperand(0);
1964 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1967 bool HasRet = false;
1968 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1970 if (UI->getOpcode() != X86ISD::RET_FLAG)
1983 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1984 ISD::NodeType ExtendKind) const {
1986 // TODO: Is this also valid on 32-bit?
1987 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1988 ReturnMVT = MVT::i8;
1990 ReturnMVT = MVT::i32;
1992 MVT MinVT = getRegisterType(ReturnMVT);
1993 return VT.bitsLT(MinVT) ? MinVT : VT;
1996 /// LowerCallResult - Lower the result values of a call into the
1997 /// appropriate copies out of appropriate physical registers.
2000 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2001 CallingConv::ID CallConv, bool isVarArg,
2002 const SmallVectorImpl<ISD::InputArg> &Ins,
2003 SDLoc dl, SelectionDAG &DAG,
2004 SmallVectorImpl<SDValue> &InVals) const {
2006 // Assign locations to each value returned by this call.
2007 SmallVector<CCValAssign, 16> RVLocs;
2008 bool Is64Bit = Subtarget->is64Bit();
2009 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2010 getTargetMachine(), RVLocs, *DAG.getContext());
2011 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2013 // Copy all of the result registers out of their specified physreg.
2014 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2015 CCValAssign &VA = RVLocs[i];
2016 EVT CopyVT = VA.getValVT();
2018 // If this is x86-64, and we disabled SSE, we can't return FP values
2019 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2020 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2021 report_fatal_error("SSE register return with SSE disabled");
2026 // If this is a call to a function that returns an fp value on the floating
2027 // point stack, we must guarantee the value is popped from the stack, so
2028 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2029 // if the return value is not used. We use the FpPOP_RETVAL instruction
2031 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2032 // If we prefer to use the value in xmm registers, copy it out as f80 and
2033 // use a truncate to move it from fp stack reg to xmm reg.
2034 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2035 SDValue Ops[] = { Chain, InFlag };
2036 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2037 MVT::Other, MVT::Glue, Ops), 1);
2038 Val = Chain.getValue(0);
2040 // Round the f80 to the right size, which also moves it to the appropriate
2042 if (CopyVT != VA.getValVT())
2043 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2044 // This truncation won't change the value.
2045 DAG.getIntPtrConstant(1));
2047 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2048 CopyVT, InFlag).getValue(1);
2049 Val = Chain.getValue(0);
2051 InFlag = Chain.getValue(2);
2052 InVals.push_back(Val);
2058 //===----------------------------------------------------------------------===//
2059 // C & StdCall & Fast Calling Convention implementation
2060 //===----------------------------------------------------------------------===//
2061 // StdCall calling convention seems to be standard for many Windows' API
2062 // routines and around. It differs from C calling convention just a little:
2063 // callee should clean up the stack, not caller. Symbols should be also
2064 // decorated in some fancy way :) It doesn't support any vector arguments.
2065 // For info on fast calling convention see Fast Calling Convention (tail call)
2066 // implementation LowerX86_32FastCCCallTo.
2068 /// CallIsStructReturn - Determines whether a call uses struct return
2070 enum StructReturnType {
2075 static StructReturnType
2076 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2078 return NotStructReturn;
2080 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2081 if (!Flags.isSRet())
2082 return NotStructReturn;
2083 if (Flags.isInReg())
2084 return RegStructReturn;
2085 return StackStructReturn;
2088 /// ArgsAreStructReturn - Determines whether a function uses struct
2089 /// return semantics.
2090 static StructReturnType
2091 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2093 return NotStructReturn;
2095 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2096 if (!Flags.isSRet())
2097 return NotStructReturn;
2098 if (Flags.isInReg())
2099 return RegStructReturn;
2100 return StackStructReturn;
2103 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2104 /// by "Src" to address "Dst" with size and alignment information specified by
2105 /// the specific parameter attribute. The copy will be passed as a byval
2106 /// function parameter.
2108 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2109 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2111 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2113 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2114 /*isVolatile*/false, /*AlwaysInline=*/true,
2115 MachinePointerInfo(), MachinePointerInfo());
2118 /// IsTailCallConvention - Return true if the calling convention is one that
2119 /// supports tail call optimization.
2120 static bool IsTailCallConvention(CallingConv::ID CC) {
2121 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2122 CC == CallingConv::HiPE);
2125 /// \brief Return true if the calling convention is a C calling convention.
2126 static bool IsCCallConvention(CallingConv::ID CC) {
2127 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2128 CC == CallingConv::X86_64_SysV);
2131 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2132 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2136 CallingConv::ID CalleeCC = CS.getCallingConv();
2137 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2143 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2144 /// a tailcall target by changing its ABI.
2145 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2146 bool GuaranteedTailCallOpt) {
2147 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2151 X86TargetLowering::LowerMemArgument(SDValue Chain,
2152 CallingConv::ID CallConv,
2153 const SmallVectorImpl<ISD::InputArg> &Ins,
2154 SDLoc dl, SelectionDAG &DAG,
2155 const CCValAssign &VA,
2156 MachineFrameInfo *MFI,
2158 // Create the nodes corresponding to a load from this parameter slot.
2159 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2160 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2161 getTargetMachine().Options.GuaranteedTailCallOpt);
2162 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2165 // If value is passed by pointer we have address passed instead of the value
2167 if (VA.getLocInfo() == CCValAssign::Indirect)
2168 ValVT = VA.getLocVT();
2170 ValVT = VA.getValVT();
2172 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2173 // changed with more analysis.
2174 // In case of tail call optimization mark all arguments mutable. Since they
2175 // could be overwritten by lowering of arguments in case of a tail call.
2176 if (Flags.isByVal()) {
2177 unsigned Bytes = Flags.getByValSize();
2178 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2179 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2180 return DAG.getFrameIndex(FI, getPointerTy());
2182 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2183 VA.getLocMemOffset(), isImmutable);
2184 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2185 return DAG.getLoad(ValVT, dl, Chain, FIN,
2186 MachinePointerInfo::getFixedStack(FI),
2187 false, false, false, 0);
2192 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2193 CallingConv::ID CallConv,
2195 const SmallVectorImpl<ISD::InputArg> &Ins,
2198 SmallVectorImpl<SDValue> &InVals)
2200 MachineFunction &MF = DAG.getMachineFunction();
2201 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2203 const Function* Fn = MF.getFunction();
2204 if (Fn->hasExternalLinkage() &&
2205 Subtarget->isTargetCygMing() &&
2206 Fn->getName() == "main")
2207 FuncInfo->setForceFramePointer(true);
2209 MachineFrameInfo *MFI = MF.getFrameInfo();
2210 bool Is64Bit = Subtarget->is64Bit();
2211 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2213 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2214 "Var args not supported with calling convention fastcc, ghc or hipe");
2216 // Assign locations to all of the incoming arguments.
2217 SmallVector<CCValAssign, 16> ArgLocs;
2218 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2219 ArgLocs, *DAG.getContext());
2221 // Allocate shadow area for Win64
2223 CCInfo.AllocateStack(32, 8);
2225 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2227 unsigned LastVal = ~0U;
2229 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2230 CCValAssign &VA = ArgLocs[i];
2231 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2233 assert(VA.getValNo() != LastVal &&
2234 "Don't support value assigned to multiple locs yet");
2236 LastVal = VA.getValNo();
2238 if (VA.isRegLoc()) {
2239 EVT RegVT = VA.getLocVT();
2240 const TargetRegisterClass *RC;
2241 if (RegVT == MVT::i32)
2242 RC = &X86::GR32RegClass;
2243 else if (Is64Bit && RegVT == MVT::i64)
2244 RC = &X86::GR64RegClass;
2245 else if (RegVT == MVT::f32)
2246 RC = &X86::FR32RegClass;
2247 else if (RegVT == MVT::f64)
2248 RC = &X86::FR64RegClass;
2249 else if (RegVT.is512BitVector())
2250 RC = &X86::VR512RegClass;
2251 else if (RegVT.is256BitVector())
2252 RC = &X86::VR256RegClass;
2253 else if (RegVT.is128BitVector())
2254 RC = &X86::VR128RegClass;
2255 else if (RegVT == MVT::x86mmx)
2256 RC = &X86::VR64RegClass;
2257 else if (RegVT == MVT::i1)
2258 RC = &X86::VK1RegClass;
2259 else if (RegVT == MVT::v8i1)
2260 RC = &X86::VK8RegClass;
2261 else if (RegVT == MVT::v16i1)
2262 RC = &X86::VK16RegClass;
2264 llvm_unreachable("Unknown argument type!");
2266 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2267 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2269 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2270 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2272 if (VA.getLocInfo() == CCValAssign::SExt)
2273 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2274 DAG.getValueType(VA.getValVT()));
2275 else if (VA.getLocInfo() == CCValAssign::ZExt)
2276 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2277 DAG.getValueType(VA.getValVT()));
2278 else if (VA.getLocInfo() == CCValAssign::BCvt)
2279 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2281 if (VA.isExtInLoc()) {
2282 // Handle MMX values passed in XMM regs.
2283 if (RegVT.isVector())
2284 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2286 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2289 assert(VA.isMemLoc());
2290 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2293 // If value is passed via pointer - do a load.
2294 if (VA.getLocInfo() == CCValAssign::Indirect)
2295 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2296 MachinePointerInfo(), false, false, false, 0);
2298 InVals.push_back(ArgValue);
2301 // The x86-64 ABIs require that for returning structs by value we copy
2302 // the sret argument into %rax/%eax (depending on ABI) for the return.
2303 // Win32 requires us to put the sret argument to %eax as well.
2304 // Save the argument into a virtual register so that we can access it
2305 // from the return points.
2306 if (MF.getFunction()->hasStructRetAttr() &&
2307 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2308 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2309 unsigned Reg = FuncInfo->getSRetReturnReg();
2311 MVT PtrTy = getPointerTy();
2312 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2313 FuncInfo->setSRetReturnReg(Reg);
2315 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2316 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2319 unsigned StackSize = CCInfo.getNextStackOffset();
2320 // Align stack specially for tail calls.
2321 if (FuncIsMadeTailCallSafe(CallConv,
2322 MF.getTarget().Options.GuaranteedTailCallOpt))
2323 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2325 // If the function takes variable number of arguments, make a frame index for
2326 // the start of the first vararg value... for expansion of llvm.va_start.
2328 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2329 CallConv != CallingConv::X86_ThisCall)) {
2330 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2333 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2335 // FIXME: We should really autogenerate these arrays
2336 static const MCPhysReg GPR64ArgRegsWin64[] = {
2337 X86::RCX, X86::RDX, X86::R8, X86::R9
2339 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2340 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2342 static const MCPhysReg XMMArgRegs64Bit[] = {
2343 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2344 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2346 const MCPhysReg *GPR64ArgRegs;
2347 unsigned NumXMMRegs = 0;
2350 // The XMM registers which might contain var arg parameters are shadowed
2351 // in their paired GPR. So we only need to save the GPR to their home
2353 TotalNumIntRegs = 4;
2354 GPR64ArgRegs = GPR64ArgRegsWin64;
2356 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2357 GPR64ArgRegs = GPR64ArgRegs64Bit;
2359 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2362 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2365 bool NoImplicitFloatOps = Fn->getAttributes().
2366 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2367 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2368 "SSE register cannot be used when SSE is disabled!");
2369 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2370 NoImplicitFloatOps) &&
2371 "SSE register cannot be used when SSE is disabled!");
2372 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2373 !Subtarget->hasSSE1())
2374 // Kernel mode asks for SSE to be disabled, so don't push them
2376 TotalNumXMMRegs = 0;
2379 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2380 // Get to the caller-allocated home save location. Add 8 to account
2381 // for the return address.
2382 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2383 FuncInfo->setRegSaveFrameIndex(
2384 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2385 // Fixup to set vararg frame on shadow area (4 x i64).
2387 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2389 // For X86-64, if there are vararg parameters that are passed via
2390 // registers, then we must store them to their spots on the stack so
2391 // they may be loaded by deferencing the result of va_next.
2392 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2393 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2394 FuncInfo->setRegSaveFrameIndex(
2395 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2399 // Store the integer parameter registers.
2400 SmallVector<SDValue, 8> MemOps;
2401 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2403 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2404 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2405 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2406 DAG.getIntPtrConstant(Offset));
2407 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2408 &X86::GR64RegClass);
2409 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2411 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2412 MachinePointerInfo::getFixedStack(
2413 FuncInfo->getRegSaveFrameIndex(), Offset),
2415 MemOps.push_back(Store);
2419 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2420 // Now store the XMM (fp + vector) parameter registers.
2421 SmallVector<SDValue, 11> SaveXMMOps;
2422 SaveXMMOps.push_back(Chain);
2424 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2425 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2426 SaveXMMOps.push_back(ALVal);
2428 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2429 FuncInfo->getRegSaveFrameIndex()));
2430 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2431 FuncInfo->getVarArgsFPOffset()));
2433 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2434 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2435 &X86::VR128RegClass);
2436 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2437 SaveXMMOps.push_back(Val);
2439 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2440 MVT::Other, SaveXMMOps));
2443 if (!MemOps.empty())
2444 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2448 // Some CCs need callee pop.
2449 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2450 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2451 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2453 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2454 // If this is an sret function, the return should pop the hidden pointer.
2455 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2456 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2457 argsAreStructReturn(Ins) == StackStructReturn)
2458 FuncInfo->setBytesToPopOnReturn(4);
2462 // RegSaveFrameIndex is X86-64 only.
2463 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2464 if (CallConv == CallingConv::X86_FastCall ||
2465 CallConv == CallingConv::X86_ThisCall)
2466 // fastcc functions can't have varargs.
2467 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2470 FuncInfo->setArgumentStackSize(StackSize);
2476 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2477 SDValue StackPtr, SDValue Arg,
2478 SDLoc dl, SelectionDAG &DAG,
2479 const CCValAssign &VA,
2480 ISD::ArgFlagsTy Flags) const {
2481 unsigned LocMemOffset = VA.getLocMemOffset();
2482 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2483 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2484 if (Flags.isByVal())
2485 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2487 return DAG.getStore(Chain, dl, Arg, PtrOff,
2488 MachinePointerInfo::getStack(LocMemOffset),
2492 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2493 /// optimization is performed and it is required.
2495 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2496 SDValue &OutRetAddr, SDValue Chain,
2497 bool IsTailCall, bool Is64Bit,
2498 int FPDiff, SDLoc dl) const {
2499 // Adjust the Return address stack slot.
2500 EVT VT = getPointerTy();
2501 OutRetAddr = getReturnAddressFrameIndex(DAG);
2503 // Load the "old" Return address.
2504 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2505 false, false, false, 0);
2506 return SDValue(OutRetAddr.getNode(), 1);
2509 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2510 /// optimization is performed and it is required (FPDiff!=0).
2511 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2512 SDValue Chain, SDValue RetAddrFrIdx,
2513 EVT PtrVT, unsigned SlotSize,
2514 int FPDiff, SDLoc dl) {
2515 // Store the return address to the appropriate stack slot.
2516 if (!FPDiff) return Chain;
2517 // Calculate the new stack slot for the return address.
2518 int NewReturnAddrFI =
2519 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2521 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2522 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2523 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2529 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2530 SmallVectorImpl<SDValue> &InVals) const {
2531 SelectionDAG &DAG = CLI.DAG;
2533 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2534 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2535 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2536 SDValue Chain = CLI.Chain;
2537 SDValue Callee = CLI.Callee;
2538 CallingConv::ID CallConv = CLI.CallConv;
2539 bool &isTailCall = CLI.IsTailCall;
2540 bool isVarArg = CLI.IsVarArg;
2542 MachineFunction &MF = DAG.getMachineFunction();
2543 bool Is64Bit = Subtarget->is64Bit();
2544 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2545 StructReturnType SR = callIsStructReturn(Outs);
2546 bool IsSibcall = false;
2548 if (MF.getTarget().Options.DisableTailCalls)
2551 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2553 // Force this to be a tail call. The verifier rules are enough to ensure
2554 // that we can lower this successfully without moving the return address
2557 } else if (isTailCall) {
2558 // Check if it's really possible to do a tail call.
2559 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2560 isVarArg, SR != NotStructReturn,
2561 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2562 Outs, OutVals, Ins, DAG);
2564 // Sibcalls are automatically detected tailcalls which do not require
2566 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2573 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2574 "Var args not supported with calling convention fastcc, ghc or hipe");
2576 // Analyze operands of the call, assigning locations to each operand.
2577 SmallVector<CCValAssign, 16> ArgLocs;
2578 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2579 ArgLocs, *DAG.getContext());
2581 // Allocate shadow area for Win64
2583 CCInfo.AllocateStack(32, 8);
2585 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2587 // Get a count of how many bytes are to be pushed on the stack.
2588 unsigned NumBytes = CCInfo.getNextStackOffset();
2590 // This is a sibcall. The memory operands are available in caller's
2591 // own caller's stack.
2593 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2594 IsTailCallConvention(CallConv))
2595 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2598 if (isTailCall && !IsSibcall && !IsMustTail) {
2599 // Lower arguments at fp - stackoffset + fpdiff.
2600 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2601 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2603 FPDiff = NumBytesCallerPushed - NumBytes;
2605 // Set the delta of movement of the returnaddr stackslot.
2606 // But only set if delta is greater than previous delta.
2607 if (FPDiff < X86Info->getTCReturnAddrDelta())
2608 X86Info->setTCReturnAddrDelta(FPDiff);
2611 unsigned NumBytesToPush = NumBytes;
2612 unsigned NumBytesToPop = NumBytes;
2614 // If we have an inalloca argument, all stack space has already been allocated
2615 // for us and be right at the top of the stack. We don't support multiple
2616 // arguments passed in memory when using inalloca.
2617 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2619 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2620 "an inalloca argument must be the only memory argument");
2624 Chain = DAG.getCALLSEQ_START(
2625 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2627 SDValue RetAddrFrIdx;
2628 // Load return address for tail calls.
2629 if (isTailCall && FPDiff)
2630 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2631 Is64Bit, FPDiff, dl);
2633 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2634 SmallVector<SDValue, 8> MemOpChains;
2637 // Walk the register/memloc assignments, inserting copies/loads. In the case
2638 // of tail call optimization arguments are handle later.
2639 const X86RegisterInfo *RegInfo =
2640 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2641 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2642 // Skip inalloca arguments, they have already been written.
2643 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2644 if (Flags.isInAlloca())
2647 CCValAssign &VA = ArgLocs[i];
2648 EVT RegVT = VA.getLocVT();
2649 SDValue Arg = OutVals[i];
2650 bool isByVal = Flags.isByVal();
2652 // Promote the value if needed.
2653 switch (VA.getLocInfo()) {
2654 default: llvm_unreachable("Unknown loc info!");
2655 case CCValAssign::Full: break;
2656 case CCValAssign::SExt:
2657 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2659 case CCValAssign::ZExt:
2660 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2662 case CCValAssign::AExt:
2663 if (RegVT.is128BitVector()) {
2664 // Special case: passing MMX values in XMM registers.
2665 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2666 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2667 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2669 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2671 case CCValAssign::BCvt:
2672 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2674 case CCValAssign::Indirect: {
2675 // Store the argument.
2676 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2677 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2678 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2679 MachinePointerInfo::getFixedStack(FI),
2686 if (VA.isRegLoc()) {
2687 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2688 if (isVarArg && IsWin64) {
2689 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2690 // shadow reg if callee is a varargs function.
2691 unsigned ShadowReg = 0;
2692 switch (VA.getLocReg()) {
2693 case X86::XMM0: ShadowReg = X86::RCX; break;
2694 case X86::XMM1: ShadowReg = X86::RDX; break;
2695 case X86::XMM2: ShadowReg = X86::R8; break;
2696 case X86::XMM3: ShadowReg = X86::R9; break;
2699 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2701 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2702 assert(VA.isMemLoc());
2703 if (!StackPtr.getNode())
2704 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2706 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2707 dl, DAG, VA, Flags));
2711 if (!MemOpChains.empty())
2712 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2714 if (Subtarget->isPICStyleGOT()) {
2715 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2718 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2719 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2721 // If we are tail calling and generating PIC/GOT style code load the
2722 // address of the callee into ECX. The value in ecx is used as target of
2723 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2724 // for tail calls on PIC/GOT architectures. Normally we would just put the
2725 // address of GOT into ebx and then call target@PLT. But for tail calls
2726 // ebx would be restored (since ebx is callee saved) before jumping to the
2729 // Note: The actual moving to ECX is done further down.
2730 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2731 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2732 !G->getGlobal()->hasProtectedVisibility())
2733 Callee = LowerGlobalAddress(Callee, DAG);
2734 else if (isa<ExternalSymbolSDNode>(Callee))
2735 Callee = LowerExternalSymbol(Callee, DAG);
2739 if (Is64Bit && isVarArg && !IsWin64) {
2740 // From AMD64 ABI document:
2741 // For calls that may call functions that use varargs or stdargs
2742 // (prototype-less calls or calls to functions containing ellipsis (...) in
2743 // the declaration) %al is used as hidden argument to specify the number
2744 // of SSE registers used. The contents of %al do not need to match exactly
2745 // the number of registers, but must be an ubound on the number of SSE
2746 // registers used and is in the range 0 - 8 inclusive.
2748 // Count the number of XMM registers allocated.
2749 static const MCPhysReg XMMArgRegs[] = {
2750 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2751 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2753 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2754 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2755 && "SSE registers cannot be used when SSE is disabled");
2757 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2758 DAG.getConstant(NumXMMRegs, MVT::i8)));
2761 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2762 // don't need this because the eligibility check rejects calls that require
2763 // shuffling arguments passed in memory.
2764 if (!IsSibcall && isTailCall) {
2765 // Force all the incoming stack arguments to be loaded from the stack
2766 // before any new outgoing arguments are stored to the stack, because the
2767 // outgoing stack slots may alias the incoming argument stack slots, and
2768 // the alias isn't otherwise explicit. This is slightly more conservative
2769 // than necessary, because it means that each store effectively depends
2770 // on every argument instead of just those arguments it would clobber.
2771 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2773 SmallVector<SDValue, 8> MemOpChains2;
2776 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2777 CCValAssign &VA = ArgLocs[i];
2780 assert(VA.isMemLoc());
2781 SDValue Arg = OutVals[i];
2782 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2783 // Skip inalloca arguments. They don't require any work.
2784 if (Flags.isInAlloca())
2786 // Create frame index.
2787 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2788 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2789 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2790 FIN = DAG.getFrameIndex(FI, getPointerTy());
2792 if (Flags.isByVal()) {
2793 // Copy relative to framepointer.
2794 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2795 if (!StackPtr.getNode())
2796 StackPtr = DAG.getCopyFromReg(Chain, dl,
2797 RegInfo->getStackRegister(),
2799 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2801 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2805 // Store relative to framepointer.
2806 MemOpChains2.push_back(
2807 DAG.getStore(ArgChain, dl, Arg, FIN,
2808 MachinePointerInfo::getFixedStack(FI),
2813 if (!MemOpChains2.empty())
2814 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2816 // Store the return address to the appropriate stack slot.
2817 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2818 getPointerTy(), RegInfo->getSlotSize(),
2822 // Build a sequence of copy-to-reg nodes chained together with token chain
2823 // and flag operands which copy the outgoing args into registers.
2825 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2826 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2827 RegsToPass[i].second, InFlag);
2828 InFlag = Chain.getValue(1);
2831 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2832 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2833 // In the 64-bit large code model, we have to make all calls
2834 // through a register, since the call instruction's 32-bit
2835 // pc-relative offset may not be large enough to hold the whole
2837 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2838 // If the callee is a GlobalAddress node (quite common, every direct call
2839 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2842 // We should use extra load for direct calls to dllimported functions in
2844 const GlobalValue *GV = G->getGlobal();
2845 if (!GV->hasDLLImportStorageClass()) {
2846 unsigned char OpFlags = 0;
2847 bool ExtraLoad = false;
2848 unsigned WrapperKind = ISD::DELETED_NODE;
2850 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2851 // external symbols most go through the PLT in PIC mode. If the symbol
2852 // has hidden or protected visibility, or if it is static or local, then
2853 // we don't need to use the PLT - we can directly call it.
2854 if (Subtarget->isTargetELF() &&
2855 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2856 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2857 OpFlags = X86II::MO_PLT;
2858 } else if (Subtarget->isPICStyleStubAny() &&
2859 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2860 (!Subtarget->getTargetTriple().isMacOSX() ||
2861 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2862 // PC-relative references to external symbols should go through $stub,
2863 // unless we're building with the leopard linker or later, which
2864 // automatically synthesizes these stubs.
2865 OpFlags = X86II::MO_DARWIN_STUB;
2866 } else if (Subtarget->isPICStyleRIPRel() &&
2867 isa<Function>(GV) &&
2868 cast<Function>(GV)->getAttributes().
2869 hasAttribute(AttributeSet::FunctionIndex,
2870 Attribute::NonLazyBind)) {
2871 // If the function is marked as non-lazy, generate an indirect call
2872 // which loads from the GOT directly. This avoids runtime overhead
2873 // at the cost of eager binding (and one extra byte of encoding).
2874 OpFlags = X86II::MO_GOTPCREL;
2875 WrapperKind = X86ISD::WrapperRIP;
2879 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2880 G->getOffset(), OpFlags);
2882 // Add a wrapper if needed.
2883 if (WrapperKind != ISD::DELETED_NODE)
2884 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2885 // Add extra indirection if needed.
2887 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2888 MachinePointerInfo::getGOT(),
2889 false, false, false, 0);
2891 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2892 unsigned char OpFlags = 0;
2894 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2895 // external symbols should go through the PLT.
2896 if (Subtarget->isTargetELF() &&
2897 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2898 OpFlags = X86II::MO_PLT;
2899 } else if (Subtarget->isPICStyleStubAny() &&
2900 (!Subtarget->getTargetTriple().isMacOSX() ||
2901 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2902 // PC-relative references to external symbols should go through $stub,
2903 // unless we're building with the leopard linker or later, which
2904 // automatically synthesizes these stubs.
2905 OpFlags = X86II::MO_DARWIN_STUB;
2908 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2912 // Returns a chain & a flag for retval copy to use.
2913 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2914 SmallVector<SDValue, 8> Ops;
2916 if (!IsSibcall && isTailCall) {
2917 Chain = DAG.getCALLSEQ_END(Chain,
2918 DAG.getIntPtrConstant(NumBytesToPop, true),
2919 DAG.getIntPtrConstant(0, true), InFlag, dl);
2920 InFlag = Chain.getValue(1);
2923 Ops.push_back(Chain);
2924 Ops.push_back(Callee);
2927 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2929 // Add argument registers to the end of the list so that they are known live
2931 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2932 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2933 RegsToPass[i].second.getValueType()));
2935 // Add a register mask operand representing the call-preserved registers.
2936 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2937 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2938 assert(Mask && "Missing call preserved mask for calling convention");
2939 Ops.push_back(DAG.getRegisterMask(Mask));
2941 if (InFlag.getNode())
2942 Ops.push_back(InFlag);
2946 //// If this is the first return lowered for this function, add the regs
2947 //// to the liveout set for the function.
2948 // This isn't right, although it's probably harmless on x86; liveouts
2949 // should be computed from returns not tail calls. Consider a void
2950 // function making a tail call to a function returning int.
2951 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2954 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2955 InFlag = Chain.getValue(1);
2957 // Create the CALLSEQ_END node.
2958 unsigned NumBytesForCalleeToPop;
2959 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2960 getTargetMachine().Options.GuaranteedTailCallOpt))
2961 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2962 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2963 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2964 SR == StackStructReturn)
2965 // If this is a call to a struct-return function, the callee
2966 // pops the hidden struct pointer, so we have to push it back.
2967 // This is common for Darwin/X86, Linux & Mingw32 targets.
2968 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2969 NumBytesForCalleeToPop = 4;
2971 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2973 // Returns a flag for retval copy to use.
2975 Chain = DAG.getCALLSEQ_END(Chain,
2976 DAG.getIntPtrConstant(NumBytesToPop, true),
2977 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2980 InFlag = Chain.getValue(1);
2983 // Handle result values, copying them out of physregs into vregs that we
2985 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2986 Ins, dl, DAG, InVals);
2989 //===----------------------------------------------------------------------===//
2990 // Fast Calling Convention (tail call) implementation
2991 //===----------------------------------------------------------------------===//
2993 // Like std call, callee cleans arguments, convention except that ECX is
2994 // reserved for storing the tail called function address. Only 2 registers are
2995 // free for argument passing (inreg). Tail call optimization is performed
2997 // * tailcallopt is enabled
2998 // * caller/callee are fastcc
2999 // On X86_64 architecture with GOT-style position independent code only local
3000 // (within module) calls are supported at the moment.
3001 // To keep the stack aligned according to platform abi the function
3002 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3003 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3004 // If a tail called function callee has more arguments than the caller the
3005 // caller needs to make sure that there is room to move the RETADDR to. This is
3006 // achieved by reserving an area the size of the argument delta right after the
3007 // original REtADDR, but before the saved framepointer or the spilled registers
3008 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3020 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3021 /// for a 16 byte align requirement.
3023 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3024 SelectionDAG& DAG) const {
3025 MachineFunction &MF = DAG.getMachineFunction();
3026 const TargetMachine &TM = MF.getTarget();
3027 const X86RegisterInfo *RegInfo =
3028 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3029 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3030 unsigned StackAlignment = TFI.getStackAlignment();
3031 uint64_t AlignMask = StackAlignment - 1;
3032 int64_t Offset = StackSize;
3033 unsigned SlotSize = RegInfo->getSlotSize();
3034 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3035 // Number smaller than 12 so just add the difference.
3036 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3038 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3039 Offset = ((~AlignMask) & Offset) + StackAlignment +
3040 (StackAlignment-SlotSize);
3045 /// MatchingStackOffset - Return true if the given stack call argument is
3046 /// already available in the same position (relatively) of the caller's
3047 /// incoming argument stack.
3049 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3050 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3051 const X86InstrInfo *TII) {
3052 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3054 if (Arg.getOpcode() == ISD::CopyFromReg) {
3055 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3056 if (!TargetRegisterInfo::isVirtualRegister(VR))
3058 MachineInstr *Def = MRI->getVRegDef(VR);
3061 if (!Flags.isByVal()) {
3062 if (!TII->isLoadFromStackSlot(Def, FI))
3065 unsigned Opcode = Def->getOpcode();
3066 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3067 Def->getOperand(1).isFI()) {
3068 FI = Def->getOperand(1).getIndex();
3069 Bytes = Flags.getByValSize();
3073 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3074 if (Flags.isByVal())
3075 // ByVal argument is passed in as a pointer but it's now being
3076 // dereferenced. e.g.
3077 // define @foo(%struct.X* %A) {
3078 // tail call @bar(%struct.X* byval %A)
3081 SDValue Ptr = Ld->getBasePtr();
3082 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3085 FI = FINode->getIndex();
3086 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3087 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3088 FI = FINode->getIndex();
3089 Bytes = Flags.getByValSize();
3093 assert(FI != INT_MAX);
3094 if (!MFI->isFixedObjectIndex(FI))
3096 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3099 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3100 /// for tail call optimization. Targets which want to do tail call
3101 /// optimization should implement this function.
3103 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3104 CallingConv::ID CalleeCC,
3106 bool isCalleeStructRet,
3107 bool isCallerStructRet,
3109 const SmallVectorImpl<ISD::OutputArg> &Outs,
3110 const SmallVectorImpl<SDValue> &OutVals,
3111 const SmallVectorImpl<ISD::InputArg> &Ins,
3112 SelectionDAG &DAG) const {
3113 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3116 // If -tailcallopt is specified, make fastcc functions tail-callable.
3117 const MachineFunction &MF = DAG.getMachineFunction();
3118 const Function *CallerF = MF.getFunction();
3120 // If the function return type is x86_fp80 and the callee return type is not,
3121 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3122 // perform a tailcall optimization here.
3123 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3126 CallingConv::ID CallerCC = CallerF->getCallingConv();
3127 bool CCMatch = CallerCC == CalleeCC;
3128 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3129 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3131 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3132 if (IsTailCallConvention(CalleeCC) && CCMatch)
3137 // Look for obvious safe cases to perform tail call optimization that do not
3138 // require ABI changes. This is what gcc calls sibcall.
3140 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3141 // emit a special epilogue.
3142 const X86RegisterInfo *RegInfo =
3143 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3144 if (RegInfo->needsStackRealignment(MF))
3147 // Also avoid sibcall optimization if either caller or callee uses struct
3148 // return semantics.
3149 if (isCalleeStructRet || isCallerStructRet)
3152 // An stdcall/thiscall caller is expected to clean up its arguments; the
3153 // callee isn't going to do that.
3154 // FIXME: this is more restrictive than needed. We could produce a tailcall
3155 // when the stack adjustment matches. For example, with a thiscall that takes
3156 // only one argument.
3157 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3158 CallerCC == CallingConv::X86_ThisCall))
3161 // Do not sibcall optimize vararg calls unless all arguments are passed via
3163 if (isVarArg && !Outs.empty()) {
3165 // Optimizing for varargs on Win64 is unlikely to be safe without
3166 // additional testing.
3167 if (IsCalleeWin64 || IsCallerWin64)
3170 SmallVector<CCValAssign, 16> ArgLocs;
3171 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3172 getTargetMachine(), ArgLocs, *DAG.getContext());
3174 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3175 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3176 if (!ArgLocs[i].isRegLoc())
3180 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3181 // stack. Therefore, if it's not used by the call it is not safe to optimize
3182 // this into a sibcall.
3183 bool Unused = false;
3184 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3191 SmallVector<CCValAssign, 16> RVLocs;
3192 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3193 getTargetMachine(), RVLocs, *DAG.getContext());
3194 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3195 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3196 CCValAssign &VA = RVLocs[i];
3197 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3202 // If the calling conventions do not match, then we'd better make sure the
3203 // results are returned in the same way as what the caller expects.
3205 SmallVector<CCValAssign, 16> RVLocs1;
3206 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3207 getTargetMachine(), RVLocs1, *DAG.getContext());
3208 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3210 SmallVector<CCValAssign, 16> RVLocs2;
3211 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3212 getTargetMachine(), RVLocs2, *DAG.getContext());
3213 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3215 if (RVLocs1.size() != RVLocs2.size())
3217 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3218 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3220 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3222 if (RVLocs1[i].isRegLoc()) {
3223 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3226 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3232 // If the callee takes no arguments then go on to check the results of the
3234 if (!Outs.empty()) {
3235 // Check if stack adjustment is needed. For now, do not do this if any
3236 // argument is passed on the stack.
3237 SmallVector<CCValAssign, 16> ArgLocs;
3238 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3239 getTargetMachine(), ArgLocs, *DAG.getContext());
3241 // Allocate shadow area for Win64
3243 CCInfo.AllocateStack(32, 8);
3245 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3246 if (CCInfo.getNextStackOffset()) {
3247 MachineFunction &MF = DAG.getMachineFunction();
3248 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3251 // Check if the arguments are already laid out in the right way as
3252 // the caller's fixed stack objects.
3253 MachineFrameInfo *MFI = MF.getFrameInfo();
3254 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3255 const X86InstrInfo *TII =
3256 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3257 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3258 CCValAssign &VA = ArgLocs[i];
3259 SDValue Arg = OutVals[i];
3260 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3261 if (VA.getLocInfo() == CCValAssign::Indirect)
3263 if (!VA.isRegLoc()) {
3264 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3271 // If the tailcall address may be in a register, then make sure it's
3272 // possible to register allocate for it. In 32-bit, the call address can
3273 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3274 // callee-saved registers are restored. These happen to be the same
3275 // registers used to pass 'inreg' arguments so watch out for those.
3276 if (!Subtarget->is64Bit() &&
3277 ((!isa<GlobalAddressSDNode>(Callee) &&
3278 !isa<ExternalSymbolSDNode>(Callee)) ||
3279 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3280 unsigned NumInRegs = 0;
3281 // In PIC we need an extra register to formulate the address computation
3283 unsigned MaxInRegs =
3284 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3286 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3287 CCValAssign &VA = ArgLocs[i];
3290 unsigned Reg = VA.getLocReg();
3293 case X86::EAX: case X86::EDX: case X86::ECX:
3294 if (++NumInRegs == MaxInRegs)
3306 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3307 const TargetLibraryInfo *libInfo) const {
3308 return X86::createFastISel(funcInfo, libInfo);
3311 //===----------------------------------------------------------------------===//
3312 // Other Lowering Hooks
3313 //===----------------------------------------------------------------------===//
3315 static bool MayFoldLoad(SDValue Op) {
3316 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3319 static bool MayFoldIntoStore(SDValue Op) {
3320 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3323 static bool isTargetShuffle(unsigned Opcode) {
3325 default: return false;
3326 case X86ISD::PSHUFD:
3327 case X86ISD::PSHUFHW:
3328 case X86ISD::PSHUFLW:
3330 case X86ISD::PALIGNR:
3331 case X86ISD::MOVLHPS:
3332 case X86ISD::MOVLHPD:
3333 case X86ISD::MOVHLPS:
3334 case X86ISD::MOVLPS:
3335 case X86ISD::MOVLPD:
3336 case X86ISD::MOVSHDUP:
3337 case X86ISD::MOVSLDUP:
3338 case X86ISD::MOVDDUP:
3341 case X86ISD::UNPCKL:
3342 case X86ISD::UNPCKH:
3343 case X86ISD::VPERMILP:
3344 case X86ISD::VPERM2X128:
3345 case X86ISD::VPERMI:
3350 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3351 SDValue V1, SelectionDAG &DAG) {
3353 default: llvm_unreachable("Unknown x86 shuffle node");
3354 case X86ISD::MOVSHDUP:
3355 case X86ISD::MOVSLDUP:
3356 case X86ISD::MOVDDUP:
3357 return DAG.getNode(Opc, dl, VT, V1);
3361 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3362 SDValue V1, unsigned TargetMask,
3363 SelectionDAG &DAG) {
3365 default: llvm_unreachable("Unknown x86 shuffle node");
3366 case X86ISD::PSHUFD:
3367 case X86ISD::PSHUFHW:
3368 case X86ISD::PSHUFLW:
3369 case X86ISD::VPERMILP:
3370 case X86ISD::VPERMI:
3371 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3375 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3376 SDValue V1, SDValue V2, unsigned TargetMask,
3377 SelectionDAG &DAG) {
3379 default: llvm_unreachable("Unknown x86 shuffle node");
3380 case X86ISD::PALIGNR:
3382 case X86ISD::VPERM2X128:
3383 return DAG.getNode(Opc, dl, VT, V1, V2,
3384 DAG.getConstant(TargetMask, MVT::i8));
3388 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3389 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3391 default: llvm_unreachable("Unknown x86 shuffle node");
3392 case X86ISD::MOVLHPS:
3393 case X86ISD::MOVLHPD:
3394 case X86ISD::MOVHLPS:
3395 case X86ISD::MOVLPS:
3396 case X86ISD::MOVLPD:
3399 case X86ISD::UNPCKL:
3400 case X86ISD::UNPCKH:
3401 return DAG.getNode(Opc, dl, VT, V1, V2);
3405 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3406 MachineFunction &MF = DAG.getMachineFunction();
3407 const X86RegisterInfo *RegInfo =
3408 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3409 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3410 int ReturnAddrIndex = FuncInfo->getRAIndex();
3412 if (ReturnAddrIndex == 0) {
3413 // Set up a frame object for the return address.
3414 unsigned SlotSize = RegInfo->getSlotSize();
3415 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3418 FuncInfo->setRAIndex(ReturnAddrIndex);
3421 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3424 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3425 bool hasSymbolicDisplacement) {
3426 // Offset should fit into 32 bit immediate field.
3427 if (!isInt<32>(Offset))
3430 // If we don't have a symbolic displacement - we don't have any extra
3432 if (!hasSymbolicDisplacement)
3435 // FIXME: Some tweaks might be needed for medium code model.
3436 if (M != CodeModel::Small && M != CodeModel::Kernel)
3439 // For small code model we assume that latest object is 16MB before end of 31
3440 // bits boundary. We may also accept pretty large negative constants knowing
3441 // that all objects are in the positive half of address space.
3442 if (M == CodeModel::Small && Offset < 16*1024*1024)
3445 // For kernel code model we know that all object resist in the negative half
3446 // of 32bits address space. We may not accept negative offsets, since they may
3447 // be just off and we may accept pretty large positive ones.
3448 if (M == CodeModel::Kernel && Offset > 0)
3454 /// isCalleePop - Determines whether the callee is required to pop its
3455 /// own arguments. Callee pop is necessary to support tail calls.
3456 bool X86::isCalleePop(CallingConv::ID CallingConv,
3457 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3461 switch (CallingConv) {
3464 case CallingConv::X86_StdCall:
3466 case CallingConv::X86_FastCall:
3468 case CallingConv::X86_ThisCall:
3470 case CallingConv::Fast:
3472 case CallingConv::GHC:
3474 case CallingConv::HiPE:
3479 /// \brief Return true if the condition is an unsigned comparison operation.
3480 static bool isX86CCUnsigned(unsigned X86CC) {
3482 default: llvm_unreachable("Invalid integer condition!");
3483 case X86::COND_E: return true;
3484 case X86::COND_G: return false;
3485 case X86::COND_GE: return false;
3486 case X86::COND_L: return false;
3487 case X86::COND_LE: return false;
3488 case X86::COND_NE: return true;
3489 case X86::COND_B: return true;
3490 case X86::COND_A: return true;
3491 case X86::COND_BE: return true;
3492 case X86::COND_AE: return true;
3494 llvm_unreachable("covered switch fell through?!");
3497 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3498 /// specific condition code, returning the condition code and the LHS/RHS of the
3499 /// comparison to make.
3500 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3501 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3503 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3504 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3505 // X > -1 -> X == 0, jump !sign.
3506 RHS = DAG.getConstant(0, RHS.getValueType());
3507 return X86::COND_NS;
3509 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3510 // X < 0 -> X == 0, jump on sign.
3513 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3515 RHS = DAG.getConstant(0, RHS.getValueType());
3516 return X86::COND_LE;
3520 switch (SetCCOpcode) {
3521 default: llvm_unreachable("Invalid integer condition!");
3522 case ISD::SETEQ: return X86::COND_E;
3523 case ISD::SETGT: return X86::COND_G;
3524 case ISD::SETGE: return X86::COND_GE;
3525 case ISD::SETLT: return X86::COND_L;
3526 case ISD::SETLE: return X86::COND_LE;
3527 case ISD::SETNE: return X86::COND_NE;
3528 case ISD::SETULT: return X86::COND_B;
3529 case ISD::SETUGT: return X86::COND_A;
3530 case ISD::SETULE: return X86::COND_BE;
3531 case ISD::SETUGE: return X86::COND_AE;
3535 // First determine if it is required or is profitable to flip the operands.
3537 // If LHS is a foldable load, but RHS is not, flip the condition.
3538 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3539 !ISD::isNON_EXTLoad(RHS.getNode())) {
3540 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3541 std::swap(LHS, RHS);
3544 switch (SetCCOpcode) {
3550 std::swap(LHS, RHS);
3554 // On a floating point condition, the flags are set as follows:
3556 // 0 | 0 | 0 | X > Y
3557 // 0 | 0 | 1 | X < Y
3558 // 1 | 0 | 0 | X == Y
3559 // 1 | 1 | 1 | unordered
3560 switch (SetCCOpcode) {
3561 default: llvm_unreachable("Condcode should be pre-legalized away");
3563 case ISD::SETEQ: return X86::COND_E;
3564 case ISD::SETOLT: // flipped
3566 case ISD::SETGT: return X86::COND_A;
3567 case ISD::SETOLE: // flipped
3569 case ISD::SETGE: return X86::COND_AE;
3570 case ISD::SETUGT: // flipped
3572 case ISD::SETLT: return X86::COND_B;
3573 case ISD::SETUGE: // flipped
3575 case ISD::SETLE: return X86::COND_BE;
3577 case ISD::SETNE: return X86::COND_NE;
3578 case ISD::SETUO: return X86::COND_P;
3579 case ISD::SETO: return X86::COND_NP;
3581 case ISD::SETUNE: return X86::COND_INVALID;
3585 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3586 /// code. Current x86 isa includes the following FP cmov instructions:
3587 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3588 static bool hasFPCMov(unsigned X86CC) {
3604 /// isFPImmLegal - Returns true if the target can instruction select the
3605 /// specified FP immediate natively. If false, the legalizer will
3606 /// materialize the FP immediate as a load from a constant pool.
3607 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3608 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3609 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3615 /// \brief Returns true if it is beneficial to convert a load of a constant
3616 /// to just the constant itself.
3617 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3619 assert(Ty->isIntegerTy());
3621 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3622 if (BitSize == 0 || BitSize > 64)
3627 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3628 /// the specified range (L, H].
3629 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3630 return (Val < 0) || (Val >= Low && Val < Hi);
3633 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3634 /// specified value.
3635 static bool isUndefOrEqual(int Val, int CmpVal) {
3636 return (Val < 0 || Val == CmpVal);
3639 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3640 /// from position Pos and ending in Pos+Size, falls within the specified
3641 /// sequential range (L, L+Pos]. or is undef.
3642 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3643 unsigned Pos, unsigned Size, int Low) {
3644 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3645 if (!isUndefOrEqual(Mask[i], Low))
3650 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3651 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3652 /// the second operand.
3653 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3654 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3655 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3656 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3657 return (Mask[0] < 2 && Mask[1] < 2);
3661 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3662 /// is suitable for input to PSHUFHW.
3663 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3664 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3667 // Lower quadword copied in order or undef.
3668 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3671 // Upper quadword shuffled.
3672 for (unsigned i = 4; i != 8; ++i)
3673 if (!isUndefOrInRange(Mask[i], 4, 8))
3676 if (VT == MVT::v16i16) {
3677 // Lower quadword copied in order or undef.
3678 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3681 // Upper quadword shuffled.
3682 for (unsigned i = 12; i != 16; ++i)
3683 if (!isUndefOrInRange(Mask[i], 12, 16))
3690 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3691 /// is suitable for input to PSHUFLW.
3692 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3693 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3696 // Upper quadword copied in order.
3697 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3700 // Lower quadword shuffled.
3701 for (unsigned i = 0; i != 4; ++i)
3702 if (!isUndefOrInRange(Mask[i], 0, 4))
3705 if (VT == MVT::v16i16) {
3706 // Upper quadword copied in order.
3707 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3710 // Lower quadword shuffled.
3711 for (unsigned i = 8; i != 12; ++i)
3712 if (!isUndefOrInRange(Mask[i], 8, 12))
3719 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3720 /// is suitable for input to PALIGNR.
3721 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3722 const X86Subtarget *Subtarget) {
3723 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3724 (VT.is256BitVector() && !Subtarget->hasInt256()))
3727 unsigned NumElts = VT.getVectorNumElements();
3728 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3729 unsigned NumLaneElts = NumElts/NumLanes;
3731 // Do not handle 64-bit element shuffles with palignr.
3732 if (NumLaneElts == 2)
3735 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3737 for (i = 0; i != NumLaneElts; ++i) {
3742 // Lane is all undef, go to next lane
3743 if (i == NumLaneElts)
3746 int Start = Mask[i+l];
3748 // Make sure its in this lane in one of the sources
3749 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3750 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3753 // If not lane 0, then we must match lane 0
3754 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3757 // Correct second source to be contiguous with first source
3758 if (Start >= (int)NumElts)
3759 Start -= NumElts - NumLaneElts;
3761 // Make sure we're shifting in the right direction.
3762 if (Start <= (int)(i+l))
3767 // Check the rest of the elements to see if they are consecutive.
3768 for (++i; i != NumLaneElts; ++i) {
3769 int Idx = Mask[i+l];
3771 // Make sure its in this lane
3772 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3773 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3776 // If not lane 0, then we must match lane 0
3777 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3780 if (Idx >= (int)NumElts)
3781 Idx -= NumElts - NumLaneElts;
3783 if (!isUndefOrEqual(Idx, Start+i))
3792 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3793 /// the two vector operands have swapped position.
3794 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3795 unsigned NumElems) {
3796 for (unsigned i = 0; i != NumElems; ++i) {
3800 else if (idx < (int)NumElems)
3801 Mask[i] = idx + NumElems;
3803 Mask[i] = idx - NumElems;
3807 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3808 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3809 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3810 /// reverse of what x86 shuffles want.
3811 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3813 unsigned NumElems = VT.getVectorNumElements();
3814 unsigned NumLanes = VT.getSizeInBits()/128;
3815 unsigned NumLaneElems = NumElems/NumLanes;
3817 if (NumLaneElems != 2 && NumLaneElems != 4)
3820 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3821 bool symetricMaskRequired =
3822 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3824 // VSHUFPSY divides the resulting vector into 4 chunks.
3825 // The sources are also splitted into 4 chunks, and each destination
3826 // chunk must come from a different source chunk.
3828 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3829 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3831 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3832 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3834 // VSHUFPDY divides the resulting vector into 4 chunks.
3835 // The sources are also splitted into 4 chunks, and each destination
3836 // chunk must come from a different source chunk.
3838 // SRC1 => X3 X2 X1 X0
3839 // SRC2 => Y3 Y2 Y1 Y0
3841 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3843 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3844 unsigned HalfLaneElems = NumLaneElems/2;
3845 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3846 for (unsigned i = 0; i != NumLaneElems; ++i) {
3847 int Idx = Mask[i+l];
3848 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3849 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3851 // For VSHUFPSY, the mask of the second half must be the same as the
3852 // first but with the appropriate offsets. This works in the same way as
3853 // VPERMILPS works with masks.
3854 if (!symetricMaskRequired || Idx < 0)
3856 if (MaskVal[i] < 0) {
3857 MaskVal[i] = Idx - l;
3860 if ((signed)(Idx - l) != MaskVal[i])
3868 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3869 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3870 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3871 if (!VT.is128BitVector())
3874 unsigned NumElems = VT.getVectorNumElements();
3879 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3880 return isUndefOrEqual(Mask[0], 6) &&
3881 isUndefOrEqual(Mask[1], 7) &&
3882 isUndefOrEqual(Mask[2], 2) &&
3883 isUndefOrEqual(Mask[3], 3);
3886 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3887 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3889 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3890 if (!VT.is128BitVector())
3893 unsigned NumElems = VT.getVectorNumElements();
3898 return isUndefOrEqual(Mask[0], 2) &&
3899 isUndefOrEqual(Mask[1], 3) &&
3900 isUndefOrEqual(Mask[2], 2) &&
3901 isUndefOrEqual(Mask[3], 3);
3904 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3905 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3906 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3907 if (!VT.is128BitVector())
3910 unsigned NumElems = VT.getVectorNumElements();
3912 if (NumElems != 2 && NumElems != 4)
3915 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3916 if (!isUndefOrEqual(Mask[i], i + NumElems))
3919 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3920 if (!isUndefOrEqual(Mask[i], i))
3926 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3927 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3928 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3929 if (!VT.is128BitVector())
3932 unsigned NumElems = VT.getVectorNumElements();
3934 if (NumElems != 2 && NumElems != 4)
3937 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3938 if (!isUndefOrEqual(Mask[i], i))
3941 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3942 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3948 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3949 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3950 /// i. e: If all but one element come from the same vector.
3951 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3952 // TODO: Deal with AVX's VINSERTPS
3953 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3956 unsigned CorrectPosV1 = 0;
3957 unsigned CorrectPosV2 = 0;
3958 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3961 else if (Mask[i] == i + 4)
3964 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3965 // We have 3 elements from one vector, and one from another.
3972 // Some special combinations that can be optimized.
3975 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3976 SelectionDAG &DAG) {
3977 MVT VT = SVOp->getSimpleValueType(0);
3980 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3983 ArrayRef<int> Mask = SVOp->getMask();
3985 // These are the special masks that may be optimized.
3986 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3987 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3988 bool MatchEvenMask = true;
3989 bool MatchOddMask = true;
3990 for (int i=0; i<8; ++i) {
3991 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3992 MatchEvenMask = false;
3993 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3994 MatchOddMask = false;
3997 if (!MatchEvenMask && !MatchOddMask)
4000 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4002 SDValue Op0 = SVOp->getOperand(0);
4003 SDValue Op1 = SVOp->getOperand(1);
4005 if (MatchEvenMask) {
4006 // Shift the second operand right to 32 bits.
4007 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4008 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4010 // Shift the first operand left to 32 bits.
4011 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4012 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4014 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4015 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4018 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4019 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4020 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4021 bool HasInt256, bool V2IsSplat = false) {
4023 assert(VT.getSizeInBits() >= 128 &&
4024 "Unsupported vector type for unpckl");
4026 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4028 unsigned NumOf256BitLanes;
4029 unsigned NumElts = VT.getVectorNumElements();
4030 if (VT.is256BitVector()) {
4031 if (NumElts != 4 && NumElts != 8 &&
4032 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4035 NumOf256BitLanes = 1;
4036 } else if (VT.is512BitVector()) {
4037 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4038 "Unsupported vector type for unpckh");
4040 NumOf256BitLanes = 2;
4043 NumOf256BitLanes = 1;
4046 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4047 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4049 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4050 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4051 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4052 int BitI = Mask[l256*NumEltsInStride+l+i];
4053 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4054 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4056 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4058 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4066 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4067 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4068 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4069 bool HasInt256, bool V2IsSplat = false) {
4070 assert(VT.getSizeInBits() >= 128 &&
4071 "Unsupported vector type for unpckh");
4073 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4075 unsigned NumOf256BitLanes;
4076 unsigned NumElts = VT.getVectorNumElements();
4077 if (VT.is256BitVector()) {
4078 if (NumElts != 4 && NumElts != 8 &&
4079 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4082 NumOf256BitLanes = 1;
4083 } else if (VT.is512BitVector()) {
4084 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4085 "Unsupported vector type for unpckh");
4087 NumOf256BitLanes = 2;
4090 NumOf256BitLanes = 1;
4093 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4094 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4096 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4097 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4098 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4099 int BitI = Mask[l256*NumEltsInStride+l+i];
4100 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4101 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4103 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4105 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4113 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4114 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4116 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4117 unsigned NumElts = VT.getVectorNumElements();
4118 bool Is256BitVec = VT.is256BitVector();
4120 if (VT.is512BitVector())
4122 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4123 "Unsupported vector type for unpckh");
4125 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4126 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4129 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4130 // FIXME: Need a better way to get rid of this, there's no latency difference
4131 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4132 // the former later. We should also remove the "_undef" special mask.
4133 if (NumElts == 4 && Is256BitVec)
4136 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4137 // independently on 128-bit lanes.
4138 unsigned NumLanes = VT.getSizeInBits()/128;
4139 unsigned NumLaneElts = NumElts/NumLanes;
4141 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4142 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4143 int BitI = Mask[l+i];
4144 int BitI1 = Mask[l+i+1];
4146 if (!isUndefOrEqual(BitI, j))
4148 if (!isUndefOrEqual(BitI1, j))
4156 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4157 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4159 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4160 unsigned NumElts = VT.getVectorNumElements();
4162 if (VT.is512BitVector())
4165 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4166 "Unsupported vector type for unpckh");
4168 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4169 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4172 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4173 // independently on 128-bit lanes.
4174 unsigned NumLanes = VT.getSizeInBits()/128;
4175 unsigned NumLaneElts = NumElts/NumLanes;
4177 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4178 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4179 int BitI = Mask[l+i];
4180 int BitI1 = Mask[l+i+1];
4181 if (!isUndefOrEqual(BitI, j))
4183 if (!isUndefOrEqual(BitI1, j))
4190 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4191 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4192 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4193 if (!VT.is512BitVector())
4196 unsigned NumElts = VT.getVectorNumElements();
4197 unsigned HalfSize = NumElts/2;
4198 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4199 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4204 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4205 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4213 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4214 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4215 /// MOVSD, and MOVD, i.e. setting the lowest element.
4216 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4217 if (VT.getVectorElementType().getSizeInBits() < 32)
4219 if (!VT.is128BitVector())
4222 unsigned NumElts = VT.getVectorNumElements();
4224 if (!isUndefOrEqual(Mask[0], NumElts))
4227 for (unsigned i = 1; i != NumElts; ++i)
4228 if (!isUndefOrEqual(Mask[i], i))
4234 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4235 /// as permutations between 128-bit chunks or halves. As an example: this
4237 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4238 /// The first half comes from the second half of V1 and the second half from the
4239 /// the second half of V2.
4240 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4241 if (!HasFp256 || !VT.is256BitVector())
4244 // The shuffle result is divided into half A and half B. In total the two
4245 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4246 // B must come from C, D, E or F.
4247 unsigned HalfSize = VT.getVectorNumElements()/2;
4248 bool MatchA = false, MatchB = false;
4250 // Check if A comes from one of C, D, E, F.
4251 for (unsigned Half = 0; Half != 4; ++Half) {
4252 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4258 // Check if B comes from one of C, D, E, F.
4259 for (unsigned Half = 0; Half != 4; ++Half) {
4260 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4266 return MatchA && MatchB;
4269 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4270 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4271 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4272 MVT VT = SVOp->getSimpleValueType(0);
4274 unsigned HalfSize = VT.getVectorNumElements()/2;
4276 unsigned FstHalf = 0, SndHalf = 0;
4277 for (unsigned i = 0; i < HalfSize; ++i) {
4278 if (SVOp->getMaskElt(i) > 0) {
4279 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4283 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4284 if (SVOp->getMaskElt(i) > 0) {
4285 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4290 return (FstHalf | (SndHalf << 4));
4293 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4294 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4295 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4299 unsigned NumElts = VT.getVectorNumElements();
4301 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4302 for (unsigned i = 0; i != NumElts; ++i) {
4305 Imm8 |= Mask[i] << (i*2);
4310 unsigned LaneSize = 4;
4311 SmallVector<int, 4> MaskVal(LaneSize, -1);
4313 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4314 for (unsigned i = 0; i != LaneSize; ++i) {
4315 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4319 if (MaskVal[i] < 0) {
4320 MaskVal[i] = Mask[i+l] - l;
4321 Imm8 |= MaskVal[i] << (i*2);
4324 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4331 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4332 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4333 /// Note that VPERMIL mask matching is different depending whether theunderlying
4334 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4335 /// to the same elements of the low, but to the higher half of the source.
4336 /// In VPERMILPD the two lanes could be shuffled independently of each other
4337 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4338 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4339 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4340 if (VT.getSizeInBits() < 256 || EltSize < 32)
4342 bool symetricMaskRequired = (EltSize == 32);
4343 unsigned NumElts = VT.getVectorNumElements();
4345 unsigned NumLanes = VT.getSizeInBits()/128;
4346 unsigned LaneSize = NumElts/NumLanes;
4347 // 2 or 4 elements in one lane
4349 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4350 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4351 for (unsigned i = 0; i != LaneSize; ++i) {
4352 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4354 if (symetricMaskRequired) {
4355 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4356 ExpectedMaskVal[i] = Mask[i+l] - l;
4359 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4367 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4368 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4369 /// element of vector 2 and the other elements to come from vector 1 in order.
4370 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4371 bool V2IsSplat = false, bool V2IsUndef = false) {
4372 if (!VT.is128BitVector())
4375 unsigned NumOps = VT.getVectorNumElements();
4376 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4379 if (!isUndefOrEqual(Mask[0], 0))
4382 for (unsigned i = 1; i != NumOps; ++i)
4383 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4384 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4385 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4391 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4392 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4393 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4394 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4395 const X86Subtarget *Subtarget) {
4396 if (!Subtarget->hasSSE3())
4399 unsigned NumElems = VT.getVectorNumElements();
4401 if ((VT.is128BitVector() && NumElems != 4) ||
4402 (VT.is256BitVector() && NumElems != 8) ||
4403 (VT.is512BitVector() && NumElems != 16))
4406 // "i+1" is the value the indexed mask element must have
4407 for (unsigned i = 0; i != NumElems; i += 2)
4408 if (!isUndefOrEqual(Mask[i], i+1) ||
4409 !isUndefOrEqual(Mask[i+1], i+1))
4415 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4416 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4417 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4418 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4419 const X86Subtarget *Subtarget) {
4420 if (!Subtarget->hasSSE3())
4423 unsigned NumElems = VT.getVectorNumElements();
4425 if ((VT.is128BitVector() && NumElems != 4) ||
4426 (VT.is256BitVector() && NumElems != 8) ||
4427 (VT.is512BitVector() && NumElems != 16))
4430 // "i" is the value the indexed mask element must have
4431 for (unsigned i = 0; i != NumElems; i += 2)
4432 if (!isUndefOrEqual(Mask[i], i) ||
4433 !isUndefOrEqual(Mask[i+1], i))
4439 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4440 /// specifies a shuffle of elements that is suitable for input to 256-bit
4441 /// version of MOVDDUP.
4442 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4443 if (!HasFp256 || !VT.is256BitVector())
4446 unsigned NumElts = VT.getVectorNumElements();
4450 for (unsigned i = 0; i != NumElts/2; ++i)
4451 if (!isUndefOrEqual(Mask[i], 0))
4453 for (unsigned i = NumElts/2; i != NumElts; ++i)
4454 if (!isUndefOrEqual(Mask[i], NumElts/2))
4459 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4460 /// specifies a shuffle of elements that is suitable for input to 128-bit
4461 /// version of MOVDDUP.
4462 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4463 if (!VT.is128BitVector())
4466 unsigned e = VT.getVectorNumElements() / 2;
4467 for (unsigned i = 0; i != e; ++i)
4468 if (!isUndefOrEqual(Mask[i], i))
4470 for (unsigned i = 0; i != e; ++i)
4471 if (!isUndefOrEqual(Mask[e+i], i))
4476 /// isVEXTRACTIndex - Return true if the specified
4477 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4478 /// suitable for instruction that extract 128 or 256 bit vectors
4479 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4480 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4481 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4484 // The index should be aligned on a vecWidth-bit boundary.
4486 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4488 MVT VT = N->getSimpleValueType(0);
4489 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4490 bool Result = (Index * ElSize) % vecWidth == 0;
4495 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4496 /// operand specifies a subvector insert that is suitable for input to
4497 /// insertion of 128 or 256-bit subvectors
4498 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4499 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4500 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4502 // The index should be aligned on a vecWidth-bit boundary.
4504 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4506 MVT VT = N->getSimpleValueType(0);
4507 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4508 bool Result = (Index * ElSize) % vecWidth == 0;
4513 bool X86::isVINSERT128Index(SDNode *N) {
4514 return isVINSERTIndex(N, 128);
4517 bool X86::isVINSERT256Index(SDNode *N) {
4518 return isVINSERTIndex(N, 256);
4521 bool X86::isVEXTRACT128Index(SDNode *N) {
4522 return isVEXTRACTIndex(N, 128);
4525 bool X86::isVEXTRACT256Index(SDNode *N) {
4526 return isVEXTRACTIndex(N, 256);
4529 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4530 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4531 /// Handles 128-bit and 256-bit.
4532 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4533 MVT VT = N->getSimpleValueType(0);
4535 assert((VT.getSizeInBits() >= 128) &&
4536 "Unsupported vector type for PSHUF/SHUFP");
4538 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4539 // independently on 128-bit lanes.
4540 unsigned NumElts = VT.getVectorNumElements();
4541 unsigned NumLanes = VT.getSizeInBits()/128;
4542 unsigned NumLaneElts = NumElts/NumLanes;
4544 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4545 "Only supports 2, 4 or 8 elements per lane");
4547 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4549 for (unsigned i = 0; i != NumElts; ++i) {
4550 int Elt = N->getMaskElt(i);
4551 if (Elt < 0) continue;
4552 Elt &= NumLaneElts - 1;
4553 unsigned ShAmt = (i << Shift) % 8;
4554 Mask |= Elt << ShAmt;
4560 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4561 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4562 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4563 MVT VT = N->getSimpleValueType(0);
4565 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4566 "Unsupported vector type for PSHUFHW");
4568 unsigned NumElts = VT.getVectorNumElements();
4571 for (unsigned l = 0; l != NumElts; l += 8) {
4572 // 8 nodes per lane, but we only care about the last 4.
4573 for (unsigned i = 0; i < 4; ++i) {
4574 int Elt = N->getMaskElt(l+i+4);
4575 if (Elt < 0) continue;
4576 Elt &= 0x3; // only 2-bits.
4577 Mask |= Elt << (i * 2);
4584 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4585 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4586 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4587 MVT VT = N->getSimpleValueType(0);
4589 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4590 "Unsupported vector type for PSHUFHW");
4592 unsigned NumElts = VT.getVectorNumElements();
4595 for (unsigned l = 0; l != NumElts; l += 8) {
4596 // 8 nodes per lane, but we only care about the first 4.
4597 for (unsigned i = 0; i < 4; ++i) {
4598 int Elt = N->getMaskElt(l+i);
4599 if (Elt < 0) continue;
4600 Elt &= 0x3; // only 2-bits
4601 Mask |= Elt << (i * 2);
4608 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4609 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4610 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4611 MVT VT = SVOp->getSimpleValueType(0);
4612 unsigned EltSize = VT.is512BitVector() ? 1 :
4613 VT.getVectorElementType().getSizeInBits() >> 3;
4615 unsigned NumElts = VT.getVectorNumElements();
4616 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4617 unsigned NumLaneElts = NumElts/NumLanes;
4621 for (i = 0; i != NumElts; ++i) {
4622 Val = SVOp->getMaskElt(i);
4626 if (Val >= (int)NumElts)
4627 Val -= NumElts - NumLaneElts;
4629 assert(Val - i > 0 && "PALIGNR imm should be positive");
4630 return (Val - i) * EltSize;
4633 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4634 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4635 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4636 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4639 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4641 MVT VecVT = N->getOperand(0).getSimpleValueType();
4642 MVT ElVT = VecVT.getVectorElementType();
4644 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4645 return Index / NumElemsPerChunk;
4648 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4649 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4650 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4651 llvm_unreachable("Illegal insert subvector for VINSERT");
4654 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4656 MVT VecVT = N->getSimpleValueType(0);
4657 MVT ElVT = VecVT.getVectorElementType();
4659 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4660 return Index / NumElemsPerChunk;
4663 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4664 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4665 /// and VINSERTI128 instructions.
4666 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4667 return getExtractVEXTRACTImmediate(N, 128);
4670 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4671 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4672 /// and VINSERTI64x4 instructions.
4673 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4674 return getExtractVEXTRACTImmediate(N, 256);
4677 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4678 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4679 /// and VINSERTI128 instructions.
4680 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4681 return getInsertVINSERTImmediate(N, 128);
4684 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4685 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4686 /// and VINSERTI64x4 instructions.
4687 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4688 return getInsertVINSERTImmediate(N, 256);
4691 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4693 bool X86::isZeroNode(SDValue Elt) {
4694 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4695 return CN->isNullValue();
4696 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4697 return CFP->getValueAPF().isPosZero();
4701 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4702 /// their permute mask.
4703 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4704 SelectionDAG &DAG) {
4705 MVT VT = SVOp->getSimpleValueType(0);
4706 unsigned NumElems = VT.getVectorNumElements();
4707 SmallVector<int, 8> MaskVec;
4709 for (unsigned i = 0; i != NumElems; ++i) {
4710 int Idx = SVOp->getMaskElt(i);
4712 if (Idx < (int)NumElems)
4717 MaskVec.push_back(Idx);
4719 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4720 SVOp->getOperand(0), &MaskVec[0]);
4723 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4724 /// match movhlps. The lower half elements should come from upper half of
4725 /// V1 (and in order), and the upper half elements should come from the upper
4726 /// half of V2 (and in order).
4727 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4728 if (!VT.is128BitVector())
4730 if (VT.getVectorNumElements() != 4)
4732 for (unsigned i = 0, e = 2; i != e; ++i)
4733 if (!isUndefOrEqual(Mask[i], i+2))
4735 for (unsigned i = 2; i != 4; ++i)
4736 if (!isUndefOrEqual(Mask[i], i+4))
4741 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4742 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4744 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4745 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4747 N = N->getOperand(0).getNode();
4748 if (!ISD::isNON_EXTLoad(N))
4751 *LD = cast<LoadSDNode>(N);
4755 // Test whether the given value is a vector value which will be legalized
4757 static bool WillBeConstantPoolLoad(SDNode *N) {
4758 if (N->getOpcode() != ISD::BUILD_VECTOR)
4761 // Check for any non-constant elements.
4762 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4763 switch (N->getOperand(i).getNode()->getOpcode()) {
4765 case ISD::ConstantFP:
4772 // Vectors of all-zeros and all-ones are materialized with special
4773 // instructions rather than being loaded.
4774 return !ISD::isBuildVectorAllZeros(N) &&
4775 !ISD::isBuildVectorAllOnes(N);
4778 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4779 /// match movlp{s|d}. The lower half elements should come from lower half of
4780 /// V1 (and in order), and the upper half elements should come from the upper
4781 /// half of V2 (and in order). And since V1 will become the source of the
4782 /// MOVLP, it must be either a vector load or a scalar load to vector.
4783 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4784 ArrayRef<int> Mask, MVT VT) {
4785 if (!VT.is128BitVector())
4788 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4790 // Is V2 is a vector load, don't do this transformation. We will try to use
4791 // load folding shufps op.
4792 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4795 unsigned NumElems = VT.getVectorNumElements();
4797 if (NumElems != 2 && NumElems != 4)
4799 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4800 if (!isUndefOrEqual(Mask[i], i))
4802 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4803 if (!isUndefOrEqual(Mask[i], i+NumElems))
4808 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4810 static bool isSplatVector(SDNode *N) {
4811 if (N->getOpcode() != ISD::BUILD_VECTOR)
4814 SDValue SplatValue = N->getOperand(0);
4815 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4816 if (N->getOperand(i) != SplatValue)
4821 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4822 /// to an zero vector.
4823 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4824 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4825 SDValue V1 = N->getOperand(0);
4826 SDValue V2 = N->getOperand(1);
4827 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4828 for (unsigned i = 0; i != NumElems; ++i) {
4829 int Idx = N->getMaskElt(i);
4830 if (Idx >= (int)NumElems) {
4831 unsigned Opc = V2.getOpcode();
4832 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4834 if (Opc != ISD::BUILD_VECTOR ||
4835 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4837 } else if (Idx >= 0) {
4838 unsigned Opc = V1.getOpcode();
4839 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4841 if (Opc != ISD::BUILD_VECTOR ||
4842 !X86::isZeroNode(V1.getOperand(Idx)))
4849 /// getZeroVector - Returns a vector of specified type with all zero elements.
4851 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4852 SelectionDAG &DAG, SDLoc dl) {
4853 assert(VT.isVector() && "Expected a vector type");
4855 // Always build SSE zero vectors as <4 x i32> bitcasted
4856 // to their dest type. This ensures they get CSE'd.
4858 if (VT.is128BitVector()) { // SSE
4859 if (Subtarget->hasSSE2()) { // SSE2
4860 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4861 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4863 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4864 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4866 } else if (VT.is256BitVector()) { // AVX
4867 if (Subtarget->hasInt256()) { // AVX2
4868 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4869 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4870 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4872 // 256-bit logic and arithmetic instructions in AVX are all
4873 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4874 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4875 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4876 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4878 } else if (VT.is512BitVector()) { // AVX-512
4879 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4880 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4881 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4882 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4883 } else if (VT.getScalarType() == MVT::i1) {
4884 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4885 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4886 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4887 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4889 llvm_unreachable("Unexpected vector type");
4891 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4894 /// getOnesVector - Returns a vector of specified type with all bits set.
4895 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4896 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4897 /// Then bitcast to their original type, ensuring they get CSE'd.
4898 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4900 assert(VT.isVector() && "Expected a vector type");
4902 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4904 if (VT.is256BitVector()) {
4905 if (HasInt256) { // AVX2
4906 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4907 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4909 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4910 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4912 } else if (VT.is128BitVector()) {
4913 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4915 llvm_unreachable("Unexpected vector type");
4917 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4920 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4921 /// that point to V2 points to its first element.
4922 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4923 for (unsigned i = 0; i != NumElems; ++i) {
4924 if (Mask[i] > (int)NumElems) {
4930 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4931 /// operation of specified width.
4932 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4934 unsigned NumElems = VT.getVectorNumElements();
4935 SmallVector<int, 8> Mask;
4936 Mask.push_back(NumElems);
4937 for (unsigned i = 1; i != NumElems; ++i)
4939 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4942 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4943 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4945 unsigned NumElems = VT.getVectorNumElements();
4946 SmallVector<int, 8> Mask;
4947 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4949 Mask.push_back(i + NumElems);
4951 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4954 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4955 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4957 unsigned NumElems = VT.getVectorNumElements();
4958 SmallVector<int, 8> Mask;
4959 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4960 Mask.push_back(i + Half);
4961 Mask.push_back(i + NumElems + Half);
4963 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4966 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4967 // a generic shuffle instruction because the target has no such instructions.
4968 // Generate shuffles which repeat i16 and i8 several times until they can be
4969 // represented by v4f32 and then be manipulated by target suported shuffles.
4970 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4971 MVT VT = V.getSimpleValueType();
4972 int NumElems = VT.getVectorNumElements();
4975 while (NumElems > 4) {
4976 if (EltNo < NumElems/2) {
4977 V = getUnpackl(DAG, dl, VT, V, V);
4979 V = getUnpackh(DAG, dl, VT, V, V);
4980 EltNo -= NumElems/2;
4987 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4988 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4989 MVT VT = V.getSimpleValueType();
4992 if (VT.is128BitVector()) {
4993 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4994 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4995 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4997 } else if (VT.is256BitVector()) {
4998 // To use VPERMILPS to splat scalars, the second half of indicies must
4999 // refer to the higher part, which is a duplication of the lower one,
5000 // because VPERMILPS can only handle in-lane permutations.
5001 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5002 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5004 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5005 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5008 llvm_unreachable("Vector size not supported");
5010 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5013 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5014 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5015 MVT SrcVT = SV->getSimpleValueType(0);
5016 SDValue V1 = SV->getOperand(0);
5019 int EltNo = SV->getSplatIndex();
5020 int NumElems = SrcVT.getVectorNumElements();
5021 bool Is256BitVec = SrcVT.is256BitVector();
5023 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5024 "Unknown how to promote splat for type");
5026 // Extract the 128-bit part containing the splat element and update
5027 // the splat element index when it refers to the higher register.
5029 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5030 if (EltNo >= NumElems/2)
5031 EltNo -= NumElems/2;
5034 // All i16 and i8 vector types can't be used directly by a generic shuffle
5035 // instruction because the target has no such instruction. Generate shuffles
5036 // which repeat i16 and i8 several times until they fit in i32, and then can
5037 // be manipulated by target suported shuffles.
5038 MVT EltVT = SrcVT.getVectorElementType();
5039 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5040 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5042 // Recreate the 256-bit vector and place the same 128-bit vector
5043 // into the low and high part. This is necessary because we want
5044 // to use VPERM* to shuffle the vectors
5046 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5049 return getLegalSplat(DAG, V1, EltNo);
5052 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5053 /// vector of zero or undef vector. This produces a shuffle where the low
5054 /// element of V2 is swizzled into the zero/undef vector, landing at element
5055 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5056 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5058 const X86Subtarget *Subtarget,
5059 SelectionDAG &DAG) {
5060 MVT VT = V2.getSimpleValueType();
5062 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5063 unsigned NumElems = VT.getVectorNumElements();
5064 SmallVector<int, 16> MaskVec;
5065 for (unsigned i = 0; i != NumElems; ++i)
5066 // If this is the insertion idx, put the low elt of V2 here.
5067 MaskVec.push_back(i == Idx ? NumElems : i);
5068 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5071 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5072 /// target specific opcode. Returns true if the Mask could be calculated.
5073 /// Sets IsUnary to true if only uses one source.
5074 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5075 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5076 unsigned NumElems = VT.getVectorNumElements();
5080 switch(N->getOpcode()) {
5082 ImmN = N->getOperand(N->getNumOperands()-1);
5083 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5085 case X86ISD::UNPCKH:
5086 DecodeUNPCKHMask(VT, Mask);
5088 case X86ISD::UNPCKL:
5089 DecodeUNPCKLMask(VT, Mask);
5091 case X86ISD::MOVHLPS:
5092 DecodeMOVHLPSMask(NumElems, Mask);
5094 case X86ISD::MOVLHPS:
5095 DecodeMOVLHPSMask(NumElems, Mask);
5097 case X86ISD::PALIGNR:
5098 ImmN = N->getOperand(N->getNumOperands()-1);
5099 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5101 case X86ISD::PSHUFD:
5102 case X86ISD::VPERMILP:
5103 ImmN = N->getOperand(N->getNumOperands()-1);
5104 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5107 case X86ISD::PSHUFHW:
5108 ImmN = N->getOperand(N->getNumOperands()-1);
5109 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5112 case X86ISD::PSHUFLW:
5113 ImmN = N->getOperand(N->getNumOperands()-1);
5114 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5117 case X86ISD::VPERMI:
5118 ImmN = N->getOperand(N->getNumOperands()-1);
5119 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5123 case X86ISD::MOVSD: {
5124 // The index 0 always comes from the first element of the second source,
5125 // this is why MOVSS and MOVSD are used in the first place. The other
5126 // elements come from the other positions of the first source vector
5127 Mask.push_back(NumElems);
5128 for (unsigned i = 1; i != NumElems; ++i) {
5133 case X86ISD::VPERM2X128:
5134 ImmN = N->getOperand(N->getNumOperands()-1);
5135 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5136 if (Mask.empty()) return false;
5138 case X86ISD::MOVDDUP:
5139 case X86ISD::MOVLHPD:
5140 case X86ISD::MOVLPD:
5141 case X86ISD::MOVLPS:
5142 case X86ISD::MOVSHDUP:
5143 case X86ISD::MOVSLDUP:
5144 // Not yet implemented
5146 default: llvm_unreachable("unknown target shuffle node");
5152 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5153 /// element of the result of the vector shuffle.
5154 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5157 return SDValue(); // Limit search depth.
5159 SDValue V = SDValue(N, 0);
5160 EVT VT = V.getValueType();
5161 unsigned Opcode = V.getOpcode();
5163 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5164 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5165 int Elt = SV->getMaskElt(Index);
5168 return DAG.getUNDEF(VT.getVectorElementType());
5170 unsigned NumElems = VT.getVectorNumElements();
5171 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5172 : SV->getOperand(1);
5173 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5176 // Recurse into target specific vector shuffles to find scalars.
5177 if (isTargetShuffle(Opcode)) {
5178 MVT ShufVT = V.getSimpleValueType();
5179 unsigned NumElems = ShufVT.getVectorNumElements();
5180 SmallVector<int, 16> ShuffleMask;
5183 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5186 int Elt = ShuffleMask[Index];
5188 return DAG.getUNDEF(ShufVT.getVectorElementType());
5190 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5192 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5196 // Actual nodes that may contain scalar elements
5197 if (Opcode == ISD::BITCAST) {
5198 V = V.getOperand(0);
5199 EVT SrcVT = V.getValueType();
5200 unsigned NumElems = VT.getVectorNumElements();
5202 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5206 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5207 return (Index == 0) ? V.getOperand(0)
5208 : DAG.getUNDEF(VT.getVectorElementType());
5210 if (V.getOpcode() == ISD::BUILD_VECTOR)
5211 return V.getOperand(Index);
5216 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5217 /// shuffle operation which come from a consecutively from a zero. The
5218 /// search can start in two different directions, from left or right.
5219 /// We count undefs as zeros until PreferredNum is reached.
5220 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5221 unsigned NumElems, bool ZerosFromLeft,
5223 unsigned PreferredNum = -1U) {
5224 unsigned NumZeros = 0;
5225 for (unsigned i = 0; i != NumElems; ++i) {
5226 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5227 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5231 if (X86::isZeroNode(Elt))
5233 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5234 NumZeros = std::min(NumZeros + 1, PreferredNum);
5242 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5243 /// correspond consecutively to elements from one of the vector operands,
5244 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5246 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5247 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5248 unsigned NumElems, unsigned &OpNum) {
5249 bool SeenV1 = false;
5250 bool SeenV2 = false;
5252 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5253 int Idx = SVOp->getMaskElt(i);
5254 // Ignore undef indicies
5258 if (Idx < (int)NumElems)
5263 // Only accept consecutive elements from the same vector
5264 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5268 OpNum = SeenV1 ? 0 : 1;
5272 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5273 /// logical left shift of a vector.
5274 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5275 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5277 SVOp->getSimpleValueType(0).getVectorNumElements();
5278 unsigned NumZeros = getNumOfConsecutiveZeros(
5279 SVOp, NumElems, false /* check zeros from right */, DAG,
5280 SVOp->getMaskElt(0));
5286 // Considering the elements in the mask that are not consecutive zeros,
5287 // check if they consecutively come from only one of the source vectors.
5289 // V1 = {X, A, B, C} 0
5291 // vector_shuffle V1, V2 <1, 2, 3, X>
5293 if (!isShuffleMaskConsecutive(SVOp,
5294 0, // Mask Start Index
5295 NumElems-NumZeros, // Mask End Index(exclusive)
5296 NumZeros, // Where to start looking in the src vector
5297 NumElems, // Number of elements in vector
5298 OpSrc)) // Which source operand ?
5303 ShVal = SVOp->getOperand(OpSrc);
5307 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5308 /// logical left shift of a vector.
5309 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5310 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5312 SVOp->getSimpleValueType(0).getVectorNumElements();
5313 unsigned NumZeros = getNumOfConsecutiveZeros(
5314 SVOp, NumElems, true /* check zeros from left */, DAG,
5315 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5321 // Considering the elements in the mask that are not consecutive zeros,
5322 // check if they consecutively come from only one of the source vectors.
5324 // 0 { A, B, X, X } = V2
5326 // vector_shuffle V1, V2 <X, X, 4, 5>
5328 if (!isShuffleMaskConsecutive(SVOp,
5329 NumZeros, // Mask Start Index
5330 NumElems, // Mask End Index(exclusive)
5331 0, // Where to start looking in the src vector
5332 NumElems, // Number of elements in vector
5333 OpSrc)) // Which source operand ?
5338 ShVal = SVOp->getOperand(OpSrc);
5342 /// isVectorShift - Returns true if the shuffle can be implemented as a
5343 /// logical left or right shift of a vector.
5344 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5345 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5346 // Although the logic below support any bitwidth size, there are no
5347 // shift instructions which handle more than 128-bit vectors.
5348 if (!SVOp->getSimpleValueType(0).is128BitVector())
5351 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5352 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5358 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5360 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5361 unsigned NumNonZero, unsigned NumZero,
5363 const X86Subtarget* Subtarget,
5364 const TargetLowering &TLI) {
5371 for (unsigned i = 0; i < 16; ++i) {
5372 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5373 if (ThisIsNonZero && First) {
5375 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5377 V = DAG.getUNDEF(MVT::v8i16);
5382 SDValue ThisElt, LastElt;
5383 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5384 if (LastIsNonZero) {
5385 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5386 MVT::i16, Op.getOperand(i-1));
5388 if (ThisIsNonZero) {
5389 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5390 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5391 ThisElt, DAG.getConstant(8, MVT::i8));
5393 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5397 if (ThisElt.getNode())
5398 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5399 DAG.getIntPtrConstant(i/2));
5403 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5406 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5408 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5409 unsigned NumNonZero, unsigned NumZero,
5411 const X86Subtarget* Subtarget,
5412 const TargetLowering &TLI) {
5419 for (unsigned i = 0; i < 8; ++i) {
5420 bool isNonZero = (NonZeros & (1 << i)) != 0;
5424 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5426 V = DAG.getUNDEF(MVT::v8i16);
5429 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5430 MVT::v8i16, V, Op.getOperand(i),
5431 DAG.getIntPtrConstant(i));
5438 /// getVShift - Return a vector logical shift node.
5440 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5441 unsigned NumBits, SelectionDAG &DAG,
5442 const TargetLowering &TLI, SDLoc dl) {
5443 assert(VT.is128BitVector() && "Unknown type for VShift");
5444 EVT ShVT = MVT::v2i64;
5445 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5446 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5447 return DAG.getNode(ISD::BITCAST, dl, VT,
5448 DAG.getNode(Opc, dl, ShVT, SrcOp,
5449 DAG.getConstant(NumBits,
5450 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5454 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5456 // Check if the scalar load can be widened into a vector load. And if
5457 // the address is "base + cst" see if the cst can be "absorbed" into
5458 // the shuffle mask.
5459 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5460 SDValue Ptr = LD->getBasePtr();
5461 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5463 EVT PVT = LD->getValueType(0);
5464 if (PVT != MVT::i32 && PVT != MVT::f32)
5469 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5470 FI = FINode->getIndex();
5472 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5473 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5474 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5475 Offset = Ptr.getConstantOperandVal(1);
5476 Ptr = Ptr.getOperand(0);
5481 // FIXME: 256-bit vector instructions don't require a strict alignment,
5482 // improve this code to support it better.
5483 unsigned RequiredAlign = VT.getSizeInBits()/8;
5484 SDValue Chain = LD->getChain();
5485 // Make sure the stack object alignment is at least 16 or 32.
5486 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5487 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5488 if (MFI->isFixedObjectIndex(FI)) {
5489 // Can't change the alignment. FIXME: It's possible to compute
5490 // the exact stack offset and reference FI + adjust offset instead.
5491 // If someone *really* cares about this. That's the way to implement it.
5494 MFI->setObjectAlignment(FI, RequiredAlign);
5498 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5499 // Ptr + (Offset & ~15).
5502 if ((Offset % RequiredAlign) & 3)
5504 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5506 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5507 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5509 int EltNo = (Offset - StartOffset) >> 2;
5510 unsigned NumElems = VT.getVectorNumElements();
5512 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5513 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5514 LD->getPointerInfo().getWithOffset(StartOffset),
5515 false, false, false, 0);
5517 SmallVector<int, 8> Mask;
5518 for (unsigned i = 0; i != NumElems; ++i)
5519 Mask.push_back(EltNo);
5521 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5527 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5528 /// vector of type 'VT', see if the elements can be replaced by a single large
5529 /// load which has the same value as a build_vector whose operands are 'elts'.
5531 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5533 /// FIXME: we'd also like to handle the case where the last elements are zero
5534 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5535 /// There's even a handy isZeroNode for that purpose.
5536 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5537 SDLoc &DL, SelectionDAG &DAG,
5538 bool isAfterLegalize) {
5539 EVT EltVT = VT.getVectorElementType();
5540 unsigned NumElems = Elts.size();
5542 LoadSDNode *LDBase = nullptr;
5543 unsigned LastLoadedElt = -1U;
5545 // For each element in the initializer, see if we've found a load or an undef.
5546 // If we don't find an initial load element, or later load elements are
5547 // non-consecutive, bail out.
5548 for (unsigned i = 0; i < NumElems; ++i) {
5549 SDValue Elt = Elts[i];
5551 if (!Elt.getNode() ||
5552 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5555 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5557 LDBase = cast<LoadSDNode>(Elt.getNode());
5561 if (Elt.getOpcode() == ISD::UNDEF)
5564 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5565 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5570 // If we have found an entire vector of loads and undefs, then return a large
5571 // load of the entire vector width starting at the base pointer. If we found
5572 // consecutive loads for the low half, generate a vzext_load node.
5573 if (LastLoadedElt == NumElems - 1) {
5575 if (isAfterLegalize &&
5576 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5579 SDValue NewLd = SDValue();
5581 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5582 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5583 LDBase->getPointerInfo(),
5584 LDBase->isVolatile(), LDBase->isNonTemporal(),
5585 LDBase->isInvariant(), 0);
5586 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5587 LDBase->getPointerInfo(),
5588 LDBase->isVolatile(), LDBase->isNonTemporal(),
5589 LDBase->isInvariant(), LDBase->getAlignment());
5591 if (LDBase->hasAnyUseOfValue(1)) {
5592 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5594 SDValue(NewLd.getNode(), 1));
5595 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5596 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5597 SDValue(NewLd.getNode(), 1));
5602 if (NumElems == 4 && LastLoadedElt == 1 &&
5603 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5604 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5605 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5607 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5608 LDBase->getPointerInfo(),
5609 LDBase->getAlignment(),
5610 false/*isVolatile*/, true/*ReadMem*/,
5613 // Make sure the newly-created LOAD is in the same position as LDBase in
5614 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5615 // update uses of LDBase's output chain to use the TokenFactor.
5616 if (LDBase->hasAnyUseOfValue(1)) {
5617 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5618 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5619 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5620 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5621 SDValue(ResNode.getNode(), 1));
5624 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5629 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5630 /// to generate a splat value for the following cases:
5631 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5632 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5633 /// a scalar load, or a constant.
5634 /// The VBROADCAST node is returned when a pattern is found,
5635 /// or SDValue() otherwise.
5636 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5637 SelectionDAG &DAG) {
5638 if (!Subtarget->hasFp256())
5641 MVT VT = Op.getSimpleValueType();
5644 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5645 "Unsupported vector type for broadcast.");
5650 switch (Op.getOpcode()) {
5652 // Unknown pattern found.
5655 case ISD::BUILD_VECTOR: {
5656 // The BUILD_VECTOR node must be a splat.
5657 if (!isSplatVector(Op.getNode()))
5660 Ld = Op.getOperand(0);
5661 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5662 Ld.getOpcode() == ISD::ConstantFP);
5664 // The suspected load node has several users. Make sure that all
5665 // of its users are from the BUILD_VECTOR node.
5666 // Constants may have multiple users.
5667 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5672 case ISD::VECTOR_SHUFFLE: {
5673 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5675 // Shuffles must have a splat mask where the first element is
5677 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5680 SDValue Sc = Op.getOperand(0);
5681 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5682 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5684 if (!Subtarget->hasInt256())
5687 // Use the register form of the broadcast instruction available on AVX2.
5688 if (VT.getSizeInBits() >= 256)
5689 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5690 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5693 Ld = Sc.getOperand(0);
5694 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5695 Ld.getOpcode() == ISD::ConstantFP);
5697 // The scalar_to_vector node and the suspected
5698 // load node must have exactly one user.
5699 // Constants may have multiple users.
5701 // AVX-512 has register version of the broadcast
5702 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5703 Ld.getValueType().getSizeInBits() >= 32;
5704 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5711 bool IsGE256 = (VT.getSizeInBits() >= 256);
5713 // Handle the broadcasting a single constant scalar from the constant pool
5714 // into a vector. On Sandybridge it is still better to load a constant vector
5715 // from the constant pool and not to broadcast it from a scalar.
5716 if (ConstSplatVal && Subtarget->hasInt256()) {
5717 EVT CVT = Ld.getValueType();
5718 assert(!CVT.isVector() && "Must not broadcast a vector type");
5719 unsigned ScalarSize = CVT.getSizeInBits();
5721 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5722 const Constant *C = nullptr;
5723 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5724 C = CI->getConstantIntValue();
5725 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5726 C = CF->getConstantFPValue();
5728 assert(C && "Invalid constant type");
5730 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5731 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5732 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5733 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5734 MachinePointerInfo::getConstantPool(),
5735 false, false, false, Alignment);
5737 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5741 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5742 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5744 // Handle AVX2 in-register broadcasts.
5745 if (!IsLoad && Subtarget->hasInt256() &&
5746 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5747 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5749 // The scalar source must be a normal load.
5753 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5754 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5756 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5757 // double since there is no vbroadcastsd xmm
5758 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5759 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5760 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5763 // Unsupported broadcast.
5767 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5768 /// underlying vector and index.
5770 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5772 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5774 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5775 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5778 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5780 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5782 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5783 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5786 // In this case the vector is the extract_subvector expression and the index
5787 // is 2, as specified by the shuffle.
5788 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5789 SDValue ShuffleVec = SVOp->getOperand(0);
5790 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5791 assert(ShuffleVecVT.getVectorElementType() ==
5792 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5794 int ShuffleIdx = SVOp->getMaskElt(Idx);
5795 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5796 ExtractedFromVec = ShuffleVec;
5802 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5803 MVT VT = Op.getSimpleValueType();
5805 // Skip if insert_vec_elt is not supported.
5806 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5807 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5811 unsigned NumElems = Op.getNumOperands();
5815 SmallVector<unsigned, 4> InsertIndices;
5816 SmallVector<int, 8> Mask(NumElems, -1);
5818 for (unsigned i = 0; i != NumElems; ++i) {
5819 unsigned Opc = Op.getOperand(i).getOpcode();
5821 if (Opc == ISD::UNDEF)
5824 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5825 // Quit if more than 1 elements need inserting.
5826 if (InsertIndices.size() > 1)
5829 InsertIndices.push_back(i);
5833 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5834 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5835 // Quit if non-constant index.
5836 if (!isa<ConstantSDNode>(ExtIdx))
5838 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5840 // Quit if extracted from vector of different type.
5841 if (ExtractedFromVec.getValueType() != VT)
5844 if (!VecIn1.getNode())
5845 VecIn1 = ExtractedFromVec;
5846 else if (VecIn1 != ExtractedFromVec) {
5847 if (!VecIn2.getNode())
5848 VecIn2 = ExtractedFromVec;
5849 else if (VecIn2 != ExtractedFromVec)
5850 // Quit if more than 2 vectors to shuffle
5854 if (ExtractedFromVec == VecIn1)
5856 else if (ExtractedFromVec == VecIn2)
5857 Mask[i] = Idx + NumElems;
5860 if (!VecIn1.getNode())
5863 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5864 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5865 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5866 unsigned Idx = InsertIndices[i];
5867 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5868 DAG.getIntPtrConstant(Idx));
5874 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5876 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5878 MVT VT = Op.getSimpleValueType();
5879 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5880 "Unexpected type in LowerBUILD_VECTORvXi1!");
5883 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5884 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5885 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5886 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5889 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5890 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5891 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5892 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5895 bool AllContants = true;
5896 uint64_t Immediate = 0;
5897 int NonConstIdx = -1;
5898 bool IsSplat = true;
5899 unsigned NumNonConsts = 0;
5900 unsigned NumConsts = 0;
5901 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5902 SDValue In = Op.getOperand(idx);
5903 if (In.getOpcode() == ISD::UNDEF)
5905 if (!isa<ConstantSDNode>(In)) {
5906 AllContants = false;
5912 if (cast<ConstantSDNode>(In)->getZExtValue())
5913 Immediate |= (1ULL << idx);
5915 if (In != Op.getOperand(0))
5920 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5921 DAG.getConstant(Immediate, MVT::i16));
5922 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5923 DAG.getIntPtrConstant(0));
5926 if (NumNonConsts == 1 && NonConstIdx != 0) {
5929 SDValue VecAsImm = DAG.getConstant(Immediate,
5930 MVT::getIntegerVT(VT.getSizeInBits()));
5931 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5934 DstVec = DAG.getUNDEF(VT);
5935 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5936 Op.getOperand(NonConstIdx),
5937 DAG.getIntPtrConstant(NonConstIdx));
5939 if (!IsSplat && (NonConstIdx != 0))
5940 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5941 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5944 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5945 DAG.getConstant(-1, SelectVT),
5946 DAG.getConstant(0, SelectVT));
5948 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5949 DAG.getConstant((Immediate | 1), SelectVT),
5950 DAG.getConstant(Immediate, SelectVT));
5951 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5955 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5958 MVT VT = Op.getSimpleValueType();
5959 MVT ExtVT = VT.getVectorElementType();
5960 unsigned NumElems = Op.getNumOperands();
5962 // Generate vectors for predicate vectors.
5963 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5964 return LowerBUILD_VECTORvXi1(Op, DAG);
5966 // Vectors containing all zeros can be matched by pxor and xorps later
5967 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5968 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5969 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5970 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5973 return getZeroVector(VT, Subtarget, DAG, dl);
5976 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5977 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5978 // vpcmpeqd on 256-bit vectors.
5979 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5980 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5983 if (!VT.is512BitVector())
5984 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5987 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5988 if (Broadcast.getNode())
5991 unsigned EVTBits = ExtVT.getSizeInBits();
5993 unsigned NumZero = 0;
5994 unsigned NumNonZero = 0;
5995 unsigned NonZeros = 0;
5996 bool IsAllConstants = true;
5997 SmallSet<SDValue, 8> Values;
5998 for (unsigned i = 0; i < NumElems; ++i) {
5999 SDValue Elt = Op.getOperand(i);
6000 if (Elt.getOpcode() == ISD::UNDEF)
6003 if (Elt.getOpcode() != ISD::Constant &&
6004 Elt.getOpcode() != ISD::ConstantFP)
6005 IsAllConstants = false;
6006 if (X86::isZeroNode(Elt))
6009 NonZeros |= (1 << i);
6014 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6015 if (NumNonZero == 0)
6016 return DAG.getUNDEF(VT);
6018 // Special case for single non-zero, non-undef, element.
6019 if (NumNonZero == 1) {
6020 unsigned Idx = countTrailingZeros(NonZeros);
6021 SDValue Item = Op.getOperand(Idx);
6023 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6024 // the value are obviously zero, truncate the value to i32 and do the
6025 // insertion that way. Only do this if the value is non-constant or if the
6026 // value is a constant being inserted into element 0. It is cheaper to do
6027 // a constant pool load than it is to do a movd + shuffle.
6028 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6029 (!IsAllConstants || Idx == 0)) {
6030 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6032 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6033 EVT VecVT = MVT::v4i32;
6034 unsigned VecElts = 4;
6036 // Truncate the value (which may itself be a constant) to i32, and
6037 // convert it to a vector with movd (S2V+shuffle to zero extend).
6038 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6039 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6040 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6042 // Now we have our 32-bit value zero extended in the low element of
6043 // a vector. If Idx != 0, swizzle it into place.
6045 SmallVector<int, 4> Mask;
6046 Mask.push_back(Idx);
6047 for (unsigned i = 1; i != VecElts; ++i)
6049 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6052 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6056 // If we have a constant or non-constant insertion into the low element of
6057 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6058 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6059 // depending on what the source datatype is.
6062 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6064 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6065 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6066 if (VT.is256BitVector() || VT.is512BitVector()) {
6067 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6068 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6069 Item, DAG.getIntPtrConstant(0));
6071 assert(VT.is128BitVector() && "Expected an SSE value type!");
6072 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6073 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6074 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6077 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6078 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6079 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6080 if (VT.is256BitVector()) {
6081 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6082 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6084 assert(VT.is128BitVector() && "Expected an SSE value type!");
6085 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6087 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6091 // Is it a vector logical left shift?
6092 if (NumElems == 2 && Idx == 1 &&
6093 X86::isZeroNode(Op.getOperand(0)) &&
6094 !X86::isZeroNode(Op.getOperand(1))) {
6095 unsigned NumBits = VT.getSizeInBits();
6096 return getVShift(true, VT,
6097 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6098 VT, Op.getOperand(1)),
6099 NumBits/2, DAG, *this, dl);
6102 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6105 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6106 // is a non-constant being inserted into an element other than the low one,
6107 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6108 // movd/movss) to move this into the low element, then shuffle it into
6110 if (EVTBits == 32) {
6111 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6113 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6114 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6115 SmallVector<int, 8> MaskVec;
6116 for (unsigned i = 0; i != NumElems; ++i)
6117 MaskVec.push_back(i == Idx ? 0 : 1);
6118 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6122 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6123 if (Values.size() == 1) {
6124 if (EVTBits == 32) {
6125 // Instead of a shuffle like this:
6126 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6127 // Check if it's possible to issue this instead.
6128 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6129 unsigned Idx = countTrailingZeros(NonZeros);
6130 SDValue Item = Op.getOperand(Idx);
6131 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6132 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6137 // A vector full of immediates; various special cases are already
6138 // handled, so this is best done with a single constant-pool load.
6142 // For AVX-length vectors, build the individual 128-bit pieces and use
6143 // shuffles to put them in place.
6144 if (VT.is256BitVector() || VT.is512BitVector()) {
6145 SmallVector<SDValue, 64> V;
6146 for (unsigned i = 0; i != NumElems; ++i)
6147 V.push_back(Op.getOperand(i));
6149 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6151 // Build both the lower and upper subvector.
6152 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6153 makeArrayRef(&V[0], NumElems/2));
6154 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6155 makeArrayRef(&V[NumElems / 2], NumElems/2));
6157 // Recreate the wider vector with the lower and upper part.
6158 if (VT.is256BitVector())
6159 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6160 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6163 // Let legalizer expand 2-wide build_vectors.
6164 if (EVTBits == 64) {
6165 if (NumNonZero == 1) {
6166 // One half is zero or undef.
6167 unsigned Idx = countTrailingZeros(NonZeros);
6168 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6169 Op.getOperand(Idx));
6170 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6175 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6176 if (EVTBits == 8 && NumElems == 16) {
6177 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6179 if (V.getNode()) return V;
6182 if (EVTBits == 16 && NumElems == 8) {
6183 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6185 if (V.getNode()) return V;
6188 // If element VT is == 32 bits, turn it into a number of shuffles.
6189 SmallVector<SDValue, 8> V(NumElems);
6190 if (NumElems == 4 && NumZero > 0) {
6191 for (unsigned i = 0; i < 4; ++i) {
6192 bool isZero = !(NonZeros & (1 << i));
6194 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6196 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6199 for (unsigned i = 0; i < 2; ++i) {
6200 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6203 V[i] = V[i*2]; // Must be a zero vector.
6206 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6209 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6212 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6217 bool Reverse1 = (NonZeros & 0x3) == 2;
6218 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6222 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6223 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6225 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6228 if (Values.size() > 1 && VT.is128BitVector()) {
6229 // Check for a build vector of consecutive loads.
6230 for (unsigned i = 0; i < NumElems; ++i)
6231 V[i] = Op.getOperand(i);
6233 // Check for elements which are consecutive loads.
6234 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6238 // Check for a build vector from mostly shuffle plus few inserting.
6239 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6243 // For SSE 4.1, use insertps to put the high elements into the low element.
6244 if (getSubtarget()->hasSSE41()) {
6246 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6247 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6249 Result = DAG.getUNDEF(VT);
6251 for (unsigned i = 1; i < NumElems; ++i) {
6252 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6253 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6254 Op.getOperand(i), DAG.getIntPtrConstant(i));
6259 // Otherwise, expand into a number of unpckl*, start by extending each of
6260 // our (non-undef) elements to the full vector width with the element in the
6261 // bottom slot of the vector (which generates no code for SSE).
6262 for (unsigned i = 0; i < NumElems; ++i) {
6263 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6264 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6266 V[i] = DAG.getUNDEF(VT);
6269 // Next, we iteratively mix elements, e.g. for v4f32:
6270 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6271 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6272 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6273 unsigned EltStride = NumElems >> 1;
6274 while (EltStride != 0) {
6275 for (unsigned i = 0; i < EltStride; ++i) {
6276 // If V[i+EltStride] is undef and this is the first round of mixing,
6277 // then it is safe to just drop this shuffle: V[i] is already in the
6278 // right place, the one element (since it's the first round) being
6279 // inserted as undef can be dropped. This isn't safe for successive
6280 // rounds because they will permute elements within both vectors.
6281 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6282 EltStride == NumElems/2)
6285 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6294 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6295 // to create 256-bit vectors from two other 128-bit ones.
6296 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6298 MVT ResVT = Op.getSimpleValueType();
6300 assert((ResVT.is256BitVector() ||
6301 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6303 SDValue V1 = Op.getOperand(0);
6304 SDValue V2 = Op.getOperand(1);
6305 unsigned NumElems = ResVT.getVectorNumElements();
6306 if(ResVT.is256BitVector())
6307 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6309 if (Op.getNumOperands() == 4) {
6310 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6311 ResVT.getVectorNumElements()/2);
6312 SDValue V3 = Op.getOperand(2);
6313 SDValue V4 = Op.getOperand(3);
6314 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6315 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6317 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6320 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6321 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6322 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6323 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6324 Op.getNumOperands() == 4)));
6326 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6327 // from two other 128-bit ones.
6329 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6330 return LowerAVXCONCAT_VECTORS(Op, DAG);
6333 // Try to lower a shuffle node into a simple blend instruction.
6335 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6336 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6337 SDValue V1 = SVOp->getOperand(0);
6338 SDValue V2 = SVOp->getOperand(1);
6340 MVT VT = SVOp->getSimpleValueType(0);
6341 MVT EltVT = VT.getVectorElementType();
6342 unsigned NumElems = VT.getVectorNumElements();
6344 // There is no blend with immediate in AVX-512.
6345 if (VT.is512BitVector())
6348 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6350 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6353 // Check the mask for BLEND and build the value.
6354 unsigned MaskValue = 0;
6355 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6356 unsigned NumLanes = (NumElems-1)/8 + 1;
6357 unsigned NumElemsInLane = NumElems / NumLanes;
6359 // Blend for v16i16 should be symetric for the both lanes.
6360 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6362 int SndLaneEltIdx = (NumLanes == 2) ?
6363 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6364 int EltIdx = SVOp->getMaskElt(i);
6366 if ((EltIdx < 0 || EltIdx == (int)i) &&
6367 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6370 if (((unsigned)EltIdx == (i + NumElems)) &&
6371 (SndLaneEltIdx < 0 ||
6372 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6373 MaskValue |= (1<<i);
6378 // Convert i32 vectors to floating point if it is not AVX2.
6379 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6381 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6382 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6384 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6385 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6388 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6389 DAG.getConstant(MaskValue, MVT::i32));
6390 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6393 /// In vector type \p VT, return true if the element at index \p InputIdx
6394 /// falls on a different 128-bit lane than \p OutputIdx.
6395 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6396 unsigned OutputIdx) {
6397 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6398 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6401 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6402 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6403 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6404 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6406 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6407 SelectionDAG &DAG) {
6408 MVT VT = V1.getSimpleValueType();
6409 assert(VT.is128BitVector() || VT.is256BitVector());
6411 MVT EltVT = VT.getVectorElementType();
6412 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6413 unsigned NumElts = VT.getVectorNumElements();
6415 SmallVector<SDValue, 32> PshufbMask;
6416 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6417 int InputIdx = MaskVals[OutputIdx];
6418 unsigned InputByteIdx;
6420 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6421 InputByteIdx = 0x80;
6423 // Cross lane is not allowed.
6424 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6426 InputByteIdx = InputIdx * EltSizeInBytes;
6427 // Index is an byte offset within the 128-bit lane.
6428 InputByteIdx &= 0xf;
6431 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6432 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6433 if (InputByteIdx != 0x80)
6438 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6440 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6441 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6442 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6445 // v8i16 shuffles - Prefer shuffles in the following order:
6446 // 1. [all] pshuflw, pshufhw, optional move
6447 // 2. [ssse3] 1 x pshufb
6448 // 3. [ssse3] 2 x pshufb + 1 x por
6449 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6451 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6452 SelectionDAG &DAG) {
6453 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6454 SDValue V1 = SVOp->getOperand(0);
6455 SDValue V2 = SVOp->getOperand(1);
6457 SmallVector<int, 8> MaskVals;
6459 // Determine if more than 1 of the words in each of the low and high quadwords
6460 // of the result come from the same quadword of one of the two inputs. Undef
6461 // mask values count as coming from any quadword, for better codegen.
6463 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6464 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6465 unsigned LoQuad[] = { 0, 0, 0, 0 };
6466 unsigned HiQuad[] = { 0, 0, 0, 0 };
6467 // Indices of quads used.
6468 std::bitset<4> InputQuads;
6469 for (unsigned i = 0; i < 8; ++i) {
6470 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6471 int EltIdx = SVOp->getMaskElt(i);
6472 MaskVals.push_back(EltIdx);
6481 InputQuads.set(EltIdx / 4);
6484 int BestLoQuad = -1;
6485 unsigned MaxQuad = 1;
6486 for (unsigned i = 0; i < 4; ++i) {
6487 if (LoQuad[i] > MaxQuad) {
6489 MaxQuad = LoQuad[i];
6493 int BestHiQuad = -1;
6495 for (unsigned i = 0; i < 4; ++i) {
6496 if (HiQuad[i] > MaxQuad) {
6498 MaxQuad = HiQuad[i];
6502 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6503 // of the two input vectors, shuffle them into one input vector so only a
6504 // single pshufb instruction is necessary. If there are more than 2 input
6505 // quads, disable the next transformation since it does not help SSSE3.
6506 bool V1Used = InputQuads[0] || InputQuads[1];
6507 bool V2Used = InputQuads[2] || InputQuads[3];
6508 if (Subtarget->hasSSSE3()) {
6509 if (InputQuads.count() == 2 && V1Used && V2Used) {
6510 BestLoQuad = InputQuads[0] ? 0 : 1;
6511 BestHiQuad = InputQuads[2] ? 2 : 3;
6513 if (InputQuads.count() > 2) {
6519 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6520 // the shuffle mask. If a quad is scored as -1, that means that it contains
6521 // words from all 4 input quadwords.
6523 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6525 BestLoQuad < 0 ? 0 : BestLoQuad,
6526 BestHiQuad < 0 ? 1 : BestHiQuad
6528 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6529 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6530 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6531 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6533 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6534 // source words for the shuffle, to aid later transformations.
6535 bool AllWordsInNewV = true;
6536 bool InOrder[2] = { true, true };
6537 for (unsigned i = 0; i != 8; ++i) {
6538 int idx = MaskVals[i];
6540 InOrder[i/4] = false;
6541 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6543 AllWordsInNewV = false;
6547 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6548 if (AllWordsInNewV) {
6549 for (int i = 0; i != 8; ++i) {
6550 int idx = MaskVals[i];
6553 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6554 if ((idx != i) && idx < 4)
6556 if ((idx != i) && idx > 3)
6565 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6566 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6567 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6568 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6569 unsigned TargetMask = 0;
6570 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6571 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6572 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6573 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6574 getShufflePSHUFLWImmediate(SVOp);
6575 V1 = NewV.getOperand(0);
6576 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6580 // Promote splats to a larger type which usually leads to more efficient code.
6581 // FIXME: Is this true if pshufb is available?
6582 if (SVOp->isSplat())
6583 return PromoteSplat(SVOp, DAG);
6585 // If we have SSSE3, and all words of the result are from 1 input vector,
6586 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6587 // is present, fall back to case 4.
6588 if (Subtarget->hasSSSE3()) {
6589 SmallVector<SDValue,16> pshufbMask;
6591 // If we have elements from both input vectors, set the high bit of the
6592 // shuffle mask element to zero out elements that come from V2 in the V1
6593 // mask, and elements that come from V1 in the V2 mask, so that the two
6594 // results can be OR'd together.
6595 bool TwoInputs = V1Used && V2Used;
6596 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6598 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6600 // Calculate the shuffle mask for the second input, shuffle it, and
6601 // OR it with the first shuffled input.
6602 CommuteVectorShuffleMask(MaskVals, 8);
6603 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6604 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6605 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6608 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6609 // and update MaskVals with new element order.
6610 std::bitset<8> InOrder;
6611 if (BestLoQuad >= 0) {
6612 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6613 for (int i = 0; i != 4; ++i) {
6614 int idx = MaskVals[i];
6617 } else if ((idx / 4) == BestLoQuad) {
6622 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6625 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6626 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6627 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6629 getShufflePSHUFLWImmediate(SVOp), DAG);
6633 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6634 // and update MaskVals with the new element order.
6635 if (BestHiQuad >= 0) {
6636 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6637 for (unsigned i = 4; i != 8; ++i) {
6638 int idx = MaskVals[i];
6641 } else if ((idx / 4) == BestHiQuad) {
6642 MaskV[i] = (idx & 3) + 4;
6646 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6649 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6650 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6651 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6653 getShufflePSHUFHWImmediate(SVOp), DAG);
6657 // In case BestHi & BestLo were both -1, which means each quadword has a word
6658 // from each of the four input quadwords, calculate the InOrder bitvector now
6659 // before falling through to the insert/extract cleanup.
6660 if (BestLoQuad == -1 && BestHiQuad == -1) {
6662 for (int i = 0; i != 8; ++i)
6663 if (MaskVals[i] < 0 || MaskVals[i] == i)
6667 // The other elements are put in the right place using pextrw and pinsrw.
6668 for (unsigned i = 0; i != 8; ++i) {
6671 int EltIdx = MaskVals[i];
6674 SDValue ExtOp = (EltIdx < 8) ?
6675 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6676 DAG.getIntPtrConstant(EltIdx)) :
6677 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6678 DAG.getIntPtrConstant(EltIdx - 8));
6679 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6680 DAG.getIntPtrConstant(i));
6685 /// \brief v16i16 shuffles
6687 /// FIXME: We only support generation of a single pshufb currently. We can
6688 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6689 /// well (e.g 2 x pshufb + 1 x por).
6691 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6692 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6693 SDValue V1 = SVOp->getOperand(0);
6694 SDValue V2 = SVOp->getOperand(1);
6697 if (V2.getOpcode() != ISD::UNDEF)
6700 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6701 return getPSHUFB(MaskVals, V1, dl, DAG);
6704 // v16i8 shuffles - Prefer shuffles in the following order:
6705 // 1. [ssse3] 1 x pshufb
6706 // 2. [ssse3] 2 x pshufb + 1 x por
6707 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6708 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6709 const X86Subtarget* Subtarget,
6710 SelectionDAG &DAG) {
6711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6712 SDValue V1 = SVOp->getOperand(0);
6713 SDValue V2 = SVOp->getOperand(1);
6715 ArrayRef<int> MaskVals = SVOp->getMask();
6717 // Promote splats to a larger type which usually leads to more efficient code.
6718 // FIXME: Is this true if pshufb is available?
6719 if (SVOp->isSplat())
6720 return PromoteSplat(SVOp, DAG);
6722 // If we have SSSE3, case 1 is generated when all result bytes come from
6723 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6724 // present, fall back to case 3.
6726 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6727 if (Subtarget->hasSSSE3()) {
6728 SmallVector<SDValue,16> pshufbMask;
6730 // If all result elements are from one input vector, then only translate
6731 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6733 // Otherwise, we have elements from both input vectors, and must zero out
6734 // elements that come from V2 in the first mask, and V1 in the second mask
6735 // so that we can OR them together.
6736 for (unsigned i = 0; i != 16; ++i) {
6737 int EltIdx = MaskVals[i];
6738 if (EltIdx < 0 || EltIdx >= 16)
6740 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6742 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6743 DAG.getNode(ISD::BUILD_VECTOR, dl,
6744 MVT::v16i8, pshufbMask));
6746 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6747 // the 2nd operand if it's undefined or zero.
6748 if (V2.getOpcode() == ISD::UNDEF ||
6749 ISD::isBuildVectorAllZeros(V2.getNode()))
6752 // Calculate the shuffle mask for the second input, shuffle it, and
6753 // OR it with the first shuffled input.
6755 for (unsigned i = 0; i != 16; ++i) {
6756 int EltIdx = MaskVals[i];
6757 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6758 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6760 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6761 DAG.getNode(ISD::BUILD_VECTOR, dl,
6762 MVT::v16i8, pshufbMask));
6763 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6766 // No SSSE3 - Calculate in place words and then fix all out of place words
6767 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6768 // the 16 different words that comprise the two doublequadword input vectors.
6769 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6770 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6772 for (int i = 0; i != 8; ++i) {
6773 int Elt0 = MaskVals[i*2];
6774 int Elt1 = MaskVals[i*2+1];
6776 // This word of the result is all undef, skip it.
6777 if (Elt0 < 0 && Elt1 < 0)
6780 // This word of the result is already in the correct place, skip it.
6781 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6784 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6785 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6788 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6789 // using a single extract together, load it and store it.
6790 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6791 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6792 DAG.getIntPtrConstant(Elt1 / 2));
6793 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6794 DAG.getIntPtrConstant(i));
6798 // If Elt1 is defined, extract it from the appropriate source. If the
6799 // source byte is not also odd, shift the extracted word left 8 bits
6800 // otherwise clear the bottom 8 bits if we need to do an or.
6802 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6803 DAG.getIntPtrConstant(Elt1 / 2));
6804 if ((Elt1 & 1) == 0)
6805 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6807 TLI.getShiftAmountTy(InsElt.getValueType())));
6809 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6810 DAG.getConstant(0xFF00, MVT::i16));
6812 // If Elt0 is defined, extract it from the appropriate source. If the
6813 // source byte is not also even, shift the extracted word right 8 bits. If
6814 // Elt1 was also defined, OR the extracted values together before
6815 // inserting them in the result.
6817 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6818 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6819 if ((Elt0 & 1) != 0)
6820 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6822 TLI.getShiftAmountTy(InsElt0.getValueType())));
6824 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6825 DAG.getConstant(0x00FF, MVT::i16));
6826 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6829 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6830 DAG.getIntPtrConstant(i));
6832 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6835 // v32i8 shuffles - Translate to VPSHUFB if possible.
6837 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6838 const X86Subtarget *Subtarget,
6839 SelectionDAG &DAG) {
6840 MVT VT = SVOp->getSimpleValueType(0);
6841 SDValue V1 = SVOp->getOperand(0);
6842 SDValue V2 = SVOp->getOperand(1);
6844 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6846 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6847 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6848 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6850 // VPSHUFB may be generated if
6851 // (1) one of input vector is undefined or zeroinitializer.
6852 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6853 // And (2) the mask indexes don't cross the 128-bit lane.
6854 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6855 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6858 if (V1IsAllZero && !V2IsAllZero) {
6859 CommuteVectorShuffleMask(MaskVals, 32);
6862 return getPSHUFB(MaskVals, V1, dl, DAG);
6865 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6866 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6867 /// done when every pair / quad of shuffle mask elements point to elements in
6868 /// the right sequence. e.g.
6869 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6871 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6872 SelectionDAG &DAG) {
6873 MVT VT = SVOp->getSimpleValueType(0);
6875 unsigned NumElems = VT.getVectorNumElements();
6878 switch (VT.SimpleTy) {
6879 default: llvm_unreachable("Unexpected!");
6880 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6881 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6882 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6883 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6884 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6885 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6888 SmallVector<int, 8> MaskVec;
6889 for (unsigned i = 0; i != NumElems; i += Scale) {
6891 for (unsigned j = 0; j != Scale; ++j) {
6892 int EltIdx = SVOp->getMaskElt(i+j);
6896 StartIdx = (EltIdx / Scale);
6897 if (EltIdx != (int)(StartIdx*Scale + j))
6900 MaskVec.push_back(StartIdx);
6903 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6904 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6905 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6908 /// getVZextMovL - Return a zero-extending vector move low node.
6910 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6911 SDValue SrcOp, SelectionDAG &DAG,
6912 const X86Subtarget *Subtarget, SDLoc dl) {
6913 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6914 LoadSDNode *LD = nullptr;
6915 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6916 LD = dyn_cast<LoadSDNode>(SrcOp);
6918 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6920 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6921 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6922 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6923 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6924 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6926 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6927 return DAG.getNode(ISD::BITCAST, dl, VT,
6928 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6929 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6937 return DAG.getNode(ISD::BITCAST, dl, VT,
6938 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6939 DAG.getNode(ISD::BITCAST, dl,
6943 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6944 /// which could not be matched by any known target speficic shuffle
6946 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6948 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6949 if (NewOp.getNode())
6952 MVT VT = SVOp->getSimpleValueType(0);
6954 unsigned NumElems = VT.getVectorNumElements();
6955 unsigned NumLaneElems = NumElems / 2;
6958 MVT EltVT = VT.getVectorElementType();
6959 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6962 SmallVector<int, 16> Mask;
6963 for (unsigned l = 0; l < 2; ++l) {
6964 // Build a shuffle mask for the output, discovering on the fly which
6965 // input vectors to use as shuffle operands (recorded in InputUsed).
6966 // If building a suitable shuffle vector proves too hard, then bail
6967 // out with UseBuildVector set.
6968 bool UseBuildVector = false;
6969 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6970 unsigned LaneStart = l * NumLaneElems;
6971 for (unsigned i = 0; i != NumLaneElems; ++i) {
6972 // The mask element. This indexes into the input.
6973 int Idx = SVOp->getMaskElt(i+LaneStart);
6975 // the mask element does not index into any input vector.
6980 // The input vector this mask element indexes into.
6981 int Input = Idx / NumLaneElems;
6983 // Turn the index into an offset from the start of the input vector.
6984 Idx -= Input * NumLaneElems;
6986 // Find or create a shuffle vector operand to hold this input.
6988 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6989 if (InputUsed[OpNo] == Input)
6990 // This input vector is already an operand.
6992 if (InputUsed[OpNo] < 0) {
6993 // Create a new operand for this input vector.
6994 InputUsed[OpNo] = Input;
6999 if (OpNo >= array_lengthof(InputUsed)) {
7000 // More than two input vectors used! Give up on trying to create a
7001 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7002 UseBuildVector = true;
7006 // Add the mask index for the new shuffle vector.
7007 Mask.push_back(Idx + OpNo * NumLaneElems);
7010 if (UseBuildVector) {
7011 SmallVector<SDValue, 16> SVOps;
7012 for (unsigned i = 0; i != NumLaneElems; ++i) {
7013 // The mask element. This indexes into the input.
7014 int Idx = SVOp->getMaskElt(i+LaneStart);
7016 SVOps.push_back(DAG.getUNDEF(EltVT));
7020 // The input vector this mask element indexes into.
7021 int Input = Idx / NumElems;
7023 // Turn the index into an offset from the start of the input vector.
7024 Idx -= Input * NumElems;
7026 // Extract the vector element by hand.
7027 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7028 SVOp->getOperand(Input),
7029 DAG.getIntPtrConstant(Idx)));
7032 // Construct the output using a BUILD_VECTOR.
7033 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7034 } else if (InputUsed[0] < 0) {
7035 // No input vectors were used! The result is undefined.
7036 Output[l] = DAG.getUNDEF(NVT);
7038 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7039 (InputUsed[0] % 2) * NumLaneElems,
7041 // If only one input was used, use an undefined vector for the other.
7042 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7043 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7044 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7045 // At least one input vector was used. Create a new shuffle vector.
7046 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7052 // Concatenate the result back
7053 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7056 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7057 /// 4 elements, and match them with several different shuffle types.
7059 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7060 SDValue V1 = SVOp->getOperand(0);
7061 SDValue V2 = SVOp->getOperand(1);
7063 MVT VT = SVOp->getSimpleValueType(0);
7065 assert(VT.is128BitVector() && "Unsupported vector size");
7067 std::pair<int, int> Locs[4];
7068 int Mask1[] = { -1, -1, -1, -1 };
7069 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7073 for (unsigned i = 0; i != 4; ++i) {
7074 int Idx = PermMask[i];
7076 Locs[i] = std::make_pair(-1, -1);
7078 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7080 Locs[i] = std::make_pair(0, NumLo);
7084 Locs[i] = std::make_pair(1, NumHi);
7086 Mask1[2+NumHi] = Idx;
7092 if (NumLo <= 2 && NumHi <= 2) {
7093 // If no more than two elements come from either vector. This can be
7094 // implemented with two shuffles. First shuffle gather the elements.
7095 // The second shuffle, which takes the first shuffle as both of its
7096 // vector operands, put the elements into the right order.
7097 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7099 int Mask2[] = { -1, -1, -1, -1 };
7101 for (unsigned i = 0; i != 4; ++i)
7102 if (Locs[i].first != -1) {
7103 unsigned Idx = (i < 2) ? 0 : 4;
7104 Idx += Locs[i].first * 2 + Locs[i].second;
7108 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7111 if (NumLo == 3 || NumHi == 3) {
7112 // Otherwise, we must have three elements from one vector, call it X, and
7113 // one element from the other, call it Y. First, use a shufps to build an
7114 // intermediate vector with the one element from Y and the element from X
7115 // that will be in the same half in the final destination (the indexes don't
7116 // matter). Then, use a shufps to build the final vector, taking the half
7117 // containing the element from Y from the intermediate, and the other half
7120 // Normalize it so the 3 elements come from V1.
7121 CommuteVectorShuffleMask(PermMask, 4);
7125 // Find the element from V2.
7127 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7128 int Val = PermMask[HiIndex];
7135 Mask1[0] = PermMask[HiIndex];
7137 Mask1[2] = PermMask[HiIndex^1];
7139 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7142 Mask1[0] = PermMask[0];
7143 Mask1[1] = PermMask[1];
7144 Mask1[2] = HiIndex & 1 ? 6 : 4;
7145 Mask1[3] = HiIndex & 1 ? 4 : 6;
7146 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7149 Mask1[0] = HiIndex & 1 ? 2 : 0;
7150 Mask1[1] = HiIndex & 1 ? 0 : 2;
7151 Mask1[2] = PermMask[2];
7152 Mask1[3] = PermMask[3];
7157 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7160 // Break it into (shuffle shuffle_hi, shuffle_lo).
7161 int LoMask[] = { -1, -1, -1, -1 };
7162 int HiMask[] = { -1, -1, -1, -1 };
7164 int *MaskPtr = LoMask;
7165 unsigned MaskIdx = 0;
7168 for (unsigned i = 0; i != 4; ++i) {
7175 int Idx = PermMask[i];
7177 Locs[i] = std::make_pair(-1, -1);
7178 } else if (Idx < 4) {
7179 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7180 MaskPtr[LoIdx] = Idx;
7183 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7184 MaskPtr[HiIdx] = Idx;
7189 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7190 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7191 int MaskOps[] = { -1, -1, -1, -1 };
7192 for (unsigned i = 0; i != 4; ++i)
7193 if (Locs[i].first != -1)
7194 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7195 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7198 static bool MayFoldVectorLoad(SDValue V) {
7199 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7200 V = V.getOperand(0);
7202 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7203 V = V.getOperand(0);
7204 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7205 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7206 // BUILD_VECTOR (load), undef
7207 V = V.getOperand(0);
7209 return MayFoldLoad(V);
7213 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7214 MVT VT = Op.getSimpleValueType();
7216 // Canonizalize to v2f64.
7217 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7218 return DAG.getNode(ISD::BITCAST, dl, VT,
7219 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7224 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7226 SDValue V1 = Op.getOperand(0);
7227 SDValue V2 = Op.getOperand(1);
7228 MVT VT = Op.getSimpleValueType();
7230 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7232 if (HasSSE2 && VT == MVT::v2f64)
7233 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7235 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7236 return DAG.getNode(ISD::BITCAST, dl, VT,
7237 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7238 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7239 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7243 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7244 SDValue V1 = Op.getOperand(0);
7245 SDValue V2 = Op.getOperand(1);
7246 MVT VT = Op.getSimpleValueType();
7248 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7249 "unsupported shuffle type");
7251 if (V2.getOpcode() == ISD::UNDEF)
7255 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7259 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7260 SDValue V1 = Op.getOperand(0);
7261 SDValue V2 = Op.getOperand(1);
7262 MVT VT = Op.getSimpleValueType();
7263 unsigned NumElems = VT.getVectorNumElements();
7265 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7266 // operand of these instructions is only memory, so check if there's a
7267 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7269 bool CanFoldLoad = false;
7271 // Trivial case, when V2 comes from a load.
7272 if (MayFoldVectorLoad(V2))
7275 // When V1 is a load, it can be folded later into a store in isel, example:
7276 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7278 // (MOVLPSmr addr:$src1, VR128:$src2)
7279 // So, recognize this potential and also use MOVLPS or MOVLPD
7280 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7283 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7285 if (HasSSE2 && NumElems == 2)
7286 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7289 // If we don't care about the second element, proceed to use movss.
7290 if (SVOp->getMaskElt(1) != -1)
7291 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7294 // movl and movlp will both match v2i64, but v2i64 is never matched by
7295 // movl earlier because we make it strict to avoid messing with the movlp load
7296 // folding logic (see the code above getMOVLP call). Match it here then,
7297 // this is horrible, but will stay like this until we move all shuffle
7298 // matching to x86 specific nodes. Note that for the 1st condition all
7299 // types are matched with movsd.
7301 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7302 // as to remove this logic from here, as much as possible
7303 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7304 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7305 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7308 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7310 // Invert the operand order and use SHUFPS to match it.
7311 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7312 getShuffleSHUFImmediate(SVOp), DAG);
7315 // It is only safe to call this function if isINSERTPSMask is true for
7316 // this shufflevector mask.
7317 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7318 SelectionDAG &DAG) {
7319 // Generate an insertps instruction when inserting an f32 from memory onto a
7320 // v4f32 or when copying a member from one v4f32 to another.
7321 // We also use it for transferring i32 from one register to another,
7322 // since it simply copies the same bits.
7323 // If we're transfering an i32 from memory to a specific element in a
7324 // register, we output a generic DAG that will match the PINSRD
7326 // TODO: Optimize for AVX cases too (VINSERTPS)
7327 MVT VT = SVOp->getSimpleValueType(0);
7328 MVT EVT = VT.getVectorElementType();
7329 SDValue V1 = SVOp->getOperand(0);
7330 SDValue V2 = SVOp->getOperand(1);
7331 auto Mask = SVOp->getMask();
7332 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7333 "unsupported vector type for insertps/pinsrd");
7335 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7336 [](const int &i) { return i < 4; });
7344 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7345 [](const int &i) { return i < 4; }) -
7350 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7351 [](const int &i) { return i >= 4; }) -
7355 if (MayFoldLoad(From)) {
7356 // Trivial case, when From comes from a load and is only used by the
7357 // shuffle. Make it use insertps from the vector that we need from that
7359 SDValue Addr = From.getOperand(1);
7361 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7362 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7363 Addr.getSimpleValueType()));
7365 LoadSDNode *Load = cast<LoadSDNode>(From);
7367 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7368 DAG.getMachineFunction().getMachineMemOperand(
7369 Load->getMemOperand(), 0, EVT.getStoreSize()));
7371 if (EVT == MVT::f32) {
7372 // Create this as a scalar to vector to match the instruction pattern.
7373 SDValue LoadScalarToVector =
7374 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7375 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7376 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7378 } else { // EVT == MVT::i32
7379 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7380 // instruction, to match the PINSRD instruction, which loads an i32 to a
7381 // certain vector element.
7382 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7383 DAG.getConstant(DestIndex, MVT::i32));
7387 // Vector-element-to-vector
7388 unsigned SrcIndex = Mask[DestIndex] % 4;
7389 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7390 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7393 // Reduce a vector shuffle to zext.
7394 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7395 SelectionDAG &DAG) {
7396 // PMOVZX is only available from SSE41.
7397 if (!Subtarget->hasSSE41())
7400 MVT VT = Op.getSimpleValueType();
7402 // Only AVX2 support 256-bit vector integer extending.
7403 if (!Subtarget->hasInt256() && VT.is256BitVector())
7406 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7408 SDValue V1 = Op.getOperand(0);
7409 SDValue V2 = Op.getOperand(1);
7410 unsigned NumElems = VT.getVectorNumElements();
7412 // Extending is an unary operation and the element type of the source vector
7413 // won't be equal to or larger than i64.
7414 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7415 VT.getVectorElementType() == MVT::i64)
7418 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7419 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7420 while ((1U << Shift) < NumElems) {
7421 if (SVOp->getMaskElt(1U << Shift) == 1)
7424 // The maximal ratio is 8, i.e. from i8 to i64.
7429 // Check the shuffle mask.
7430 unsigned Mask = (1U << Shift) - 1;
7431 for (unsigned i = 0; i != NumElems; ++i) {
7432 int EltIdx = SVOp->getMaskElt(i);
7433 if ((i & Mask) != 0 && EltIdx != -1)
7435 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7439 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7440 MVT NeVT = MVT::getIntegerVT(NBits);
7441 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7443 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7446 // Simplify the operand as it's prepared to be fed into shuffle.
7447 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7448 if (V1.getOpcode() == ISD::BITCAST &&
7449 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7450 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7451 V1.getOperand(0).getOperand(0)
7452 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7453 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7454 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7455 ConstantSDNode *CIdx =
7456 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7457 // If it's foldable, i.e. normal load with single use, we will let code
7458 // selection to fold it. Otherwise, we will short the conversion sequence.
7459 if (CIdx && CIdx->getZExtValue() == 0 &&
7460 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7461 MVT FullVT = V.getSimpleValueType();
7462 MVT V1VT = V1.getSimpleValueType();
7463 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7464 // The "ext_vec_elt" node is wider than the result node.
7465 // In this case we should extract subvector from V.
7466 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7467 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7468 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7469 FullVT.getVectorNumElements()/Ratio);
7470 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7471 DAG.getIntPtrConstant(0));
7473 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7477 return DAG.getNode(ISD::BITCAST, DL, VT,
7478 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7482 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7483 SelectionDAG &DAG) {
7484 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7485 MVT VT = Op.getSimpleValueType();
7487 SDValue V1 = Op.getOperand(0);
7488 SDValue V2 = Op.getOperand(1);
7490 if (isZeroShuffle(SVOp))
7491 return getZeroVector(VT, Subtarget, DAG, dl);
7493 // Handle splat operations
7494 if (SVOp->isSplat()) {
7495 // Use vbroadcast whenever the splat comes from a foldable load
7496 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7497 if (Broadcast.getNode())
7501 // Check integer expanding shuffles.
7502 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7503 if (NewOp.getNode())
7506 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7508 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7509 VT == MVT::v16i16 || VT == MVT::v32i8) {
7510 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7511 if (NewOp.getNode())
7512 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7513 } else if ((VT == MVT::v4i32 ||
7514 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7515 // FIXME: Figure out a cleaner way to do this.
7516 // Try to make use of movq to zero out the top part.
7517 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7518 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7519 if (NewOp.getNode()) {
7520 MVT NewVT = NewOp.getSimpleValueType();
7521 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7522 NewVT, true, false))
7523 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7524 DAG, Subtarget, dl);
7526 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7527 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7528 if (NewOp.getNode()) {
7529 MVT NewVT = NewOp.getSimpleValueType();
7530 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7531 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7532 DAG, Subtarget, dl);
7540 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7541 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7542 SDValue V1 = Op.getOperand(0);
7543 SDValue V2 = Op.getOperand(1);
7544 MVT VT = Op.getSimpleValueType();
7546 unsigned NumElems = VT.getVectorNumElements();
7547 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7548 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7549 bool V1IsSplat = false;
7550 bool V2IsSplat = false;
7551 bool HasSSE2 = Subtarget->hasSSE2();
7552 bool HasFp256 = Subtarget->hasFp256();
7553 bool HasInt256 = Subtarget->hasInt256();
7554 MachineFunction &MF = DAG.getMachineFunction();
7555 bool OptForSize = MF.getFunction()->getAttributes().
7556 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7558 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7560 if (V1IsUndef && V2IsUndef)
7561 return DAG.getUNDEF(VT);
7563 // When we create a shuffle node we put the UNDEF node to second operand,
7564 // but in some cases the first operand may be transformed to UNDEF.
7565 // In this case we should just commute the node.
7567 return CommuteVectorShuffle(SVOp, DAG);
7569 // Vector shuffle lowering takes 3 steps:
7571 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7572 // narrowing and commutation of operands should be handled.
7573 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7575 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7576 // so the shuffle can be broken into other shuffles and the legalizer can
7577 // try the lowering again.
7579 // The general idea is that no vector_shuffle operation should be left to
7580 // be matched during isel, all of them must be converted to a target specific
7583 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7584 // narrowing and commutation of operands should be handled. The actual code
7585 // doesn't include all of those, work in progress...
7586 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7587 if (NewOp.getNode())
7590 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7592 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7593 // unpckh_undef). Only use pshufd if speed is more important than size.
7594 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7595 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7596 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7597 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7599 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7600 V2IsUndef && MayFoldVectorLoad(V1))
7601 return getMOVDDup(Op, dl, V1, DAG);
7603 if (isMOVHLPS_v_undef_Mask(M, VT))
7604 return getMOVHighToLow(Op, dl, DAG);
7606 // Use to match splats
7607 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7608 (VT == MVT::v2f64 || VT == MVT::v2i64))
7609 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7611 if (isPSHUFDMask(M, VT)) {
7612 // The actual implementation will match the mask in the if above and then
7613 // during isel it can match several different instructions, not only pshufd
7614 // as its name says, sad but true, emulate the behavior for now...
7615 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7616 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7618 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7620 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7621 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7623 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7624 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7627 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7631 if (isPALIGNRMask(M, VT, Subtarget))
7632 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7633 getShufflePALIGNRImmediate(SVOp),
7636 // Check if this can be converted into a logical shift.
7637 bool isLeft = false;
7640 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7641 if (isShift && ShVal.hasOneUse()) {
7642 // If the shifted value has multiple uses, it may be cheaper to use
7643 // v_set0 + movlhps or movhlps, etc.
7644 MVT EltVT = VT.getVectorElementType();
7645 ShAmt *= EltVT.getSizeInBits();
7646 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7649 if (isMOVLMask(M, VT)) {
7650 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7651 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7652 if (!isMOVLPMask(M, VT)) {
7653 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7654 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7656 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7657 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7661 // FIXME: fold these into legal mask.
7662 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7663 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7665 if (isMOVHLPSMask(M, VT))
7666 return getMOVHighToLow(Op, dl, DAG);
7668 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7669 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7671 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7672 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7674 if (isMOVLPMask(M, VT))
7675 return getMOVLP(Op, dl, DAG, HasSSE2);
7677 if (ShouldXformToMOVHLPS(M, VT) ||
7678 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7679 return CommuteVectorShuffle(SVOp, DAG);
7682 // No better options. Use a vshldq / vsrldq.
7683 MVT EltVT = VT.getVectorElementType();
7684 ShAmt *= EltVT.getSizeInBits();
7685 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7688 bool Commuted = false;
7689 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7690 // 1,1,1,1 -> v8i16 though.
7691 V1IsSplat = isSplatVector(V1.getNode());
7692 V2IsSplat = isSplatVector(V2.getNode());
7694 // Canonicalize the splat or undef, if present, to be on the RHS.
7695 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7696 CommuteVectorShuffleMask(M, NumElems);
7698 std::swap(V1IsSplat, V2IsSplat);
7702 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7703 // Shuffling low element of v1 into undef, just return v1.
7706 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7707 // the instruction selector will not match, so get a canonical MOVL with
7708 // swapped operands to undo the commute.
7709 return getMOVL(DAG, dl, VT, V2, V1);
7712 if (isUNPCKLMask(M, VT, HasInt256))
7713 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7715 if (isUNPCKHMask(M, VT, HasInt256))
7716 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7719 // Normalize mask so all entries that point to V2 points to its first
7720 // element then try to match unpck{h|l} again. If match, return a
7721 // new vector_shuffle with the corrected mask.p
7722 SmallVector<int, 8> NewMask(M.begin(), M.end());
7723 NormalizeMask(NewMask, NumElems);
7724 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7725 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7726 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7727 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7731 // Commute is back and try unpck* again.
7732 // FIXME: this seems wrong.
7733 CommuteVectorShuffleMask(M, NumElems);
7735 std::swap(V1IsSplat, V2IsSplat);
7737 if (isUNPCKLMask(M, VT, HasInt256))
7738 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7740 if (isUNPCKHMask(M, VT, HasInt256))
7741 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7744 // Normalize the node to match x86 shuffle ops if needed
7745 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7746 return CommuteVectorShuffle(SVOp, DAG);
7748 // The checks below are all present in isShuffleMaskLegal, but they are
7749 // inlined here right now to enable us to directly emit target specific
7750 // nodes, and remove one by one until they don't return Op anymore.
7752 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7753 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7754 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7755 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7758 if (isPSHUFHWMask(M, VT, HasInt256))
7759 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7760 getShufflePSHUFHWImmediate(SVOp),
7763 if (isPSHUFLWMask(M, VT, HasInt256))
7764 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7765 getShufflePSHUFLWImmediate(SVOp),
7768 if (isSHUFPMask(M, VT))
7769 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7770 getShuffleSHUFImmediate(SVOp), DAG);
7772 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7773 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7774 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7775 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7777 //===--------------------------------------------------------------------===//
7778 // Generate target specific nodes for 128 or 256-bit shuffles only
7779 // supported in the AVX instruction set.
7782 // Handle VMOVDDUPY permutations
7783 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7784 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7786 // Handle VPERMILPS/D* permutations
7787 if (isVPERMILPMask(M, VT)) {
7788 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7789 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7790 getShuffleSHUFImmediate(SVOp), DAG);
7791 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7792 getShuffleSHUFImmediate(SVOp), DAG);
7796 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7797 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7798 Idx*(NumElems/2), DAG, dl);
7800 // Handle VPERM2F128/VPERM2I128 permutations
7801 if (isVPERM2X128Mask(M, VT, HasFp256))
7802 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7803 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7805 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7806 if (BlendOp.getNode())
7809 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7810 return getINSERTPS(SVOp, dl, DAG);
7813 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7814 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7816 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7817 VT.is512BitVector()) {
7818 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7819 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7820 SmallVector<SDValue, 16> permclMask;
7821 for (unsigned i = 0; i != NumElems; ++i) {
7822 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7825 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7827 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7828 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7829 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7830 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7831 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7834 //===--------------------------------------------------------------------===//
7835 // Since no target specific shuffle was selected for this generic one,
7836 // lower it into other known shuffles. FIXME: this isn't true yet, but
7837 // this is the plan.
7840 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7841 if (VT == MVT::v8i16) {
7842 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7843 if (NewOp.getNode())
7847 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7848 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7849 if (NewOp.getNode())
7853 if (VT == MVT::v16i8) {
7854 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7855 if (NewOp.getNode())
7859 if (VT == MVT::v32i8) {
7860 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7861 if (NewOp.getNode())
7865 // Handle all 128-bit wide vectors with 4 elements, and match them with
7866 // several different shuffle types.
7867 if (NumElems == 4 && VT.is128BitVector())
7868 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7870 // Handle general 256-bit shuffles
7871 if (VT.is256BitVector())
7872 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7877 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7878 MVT VT = Op.getSimpleValueType();
7881 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7884 if (VT.getSizeInBits() == 8) {
7885 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7886 Op.getOperand(0), Op.getOperand(1));
7887 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7888 DAG.getValueType(VT));
7889 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7892 if (VT.getSizeInBits() == 16) {
7893 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7894 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7896 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7897 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7898 DAG.getNode(ISD::BITCAST, dl,
7902 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7903 Op.getOperand(0), Op.getOperand(1));
7904 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7905 DAG.getValueType(VT));
7906 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7909 if (VT == MVT::f32) {
7910 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7911 // the result back to FR32 register. It's only worth matching if the
7912 // result has a single use which is a store or a bitcast to i32. And in
7913 // the case of a store, it's not worth it if the index is a constant 0,
7914 // because a MOVSSmr can be used instead, which is smaller and faster.
7915 if (!Op.hasOneUse())
7917 SDNode *User = *Op.getNode()->use_begin();
7918 if ((User->getOpcode() != ISD::STORE ||
7919 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7920 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7921 (User->getOpcode() != ISD::BITCAST ||
7922 User->getValueType(0) != MVT::i32))
7924 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7925 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7928 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7931 if (VT == MVT::i32 || VT == MVT::i64) {
7932 // ExtractPS/pextrq works with constant index.
7933 if (isa<ConstantSDNode>(Op.getOperand(1)))
7939 /// Extract one bit from mask vector, like v16i1 or v8i1.
7940 /// AVX-512 feature.
7942 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7943 SDValue Vec = Op.getOperand(0);
7945 MVT VecVT = Vec.getSimpleValueType();
7946 SDValue Idx = Op.getOperand(1);
7947 MVT EltVT = Op.getSimpleValueType();
7949 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7951 // variable index can't be handled in mask registers,
7952 // extend vector to VR512
7953 if (!isa<ConstantSDNode>(Idx)) {
7954 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7955 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7956 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7957 ExtVT.getVectorElementType(), Ext, Idx);
7958 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7961 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7962 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7963 unsigned MaxSift = rc->getSize()*8 - 1;
7964 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7965 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7966 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7967 DAG.getConstant(MaxSift, MVT::i8));
7968 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7969 DAG.getIntPtrConstant(0));
7973 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7974 SelectionDAG &DAG) const {
7976 SDValue Vec = Op.getOperand(0);
7977 MVT VecVT = Vec.getSimpleValueType();
7978 SDValue Idx = Op.getOperand(1);
7980 if (Op.getSimpleValueType() == MVT::i1)
7981 return ExtractBitFromMaskVector(Op, DAG);
7983 if (!isa<ConstantSDNode>(Idx)) {
7984 if (VecVT.is512BitVector() ||
7985 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7986 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7989 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7990 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7991 MaskEltVT.getSizeInBits());
7993 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7994 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7995 getZeroVector(MaskVT, Subtarget, DAG, dl),
7996 Idx, DAG.getConstant(0, getPointerTy()));
7997 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7998 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7999 Perm, DAG.getConstant(0, getPointerTy()));
8004 // If this is a 256-bit vector result, first extract the 128-bit vector and
8005 // then extract the element from the 128-bit vector.
8006 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8008 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8009 // Get the 128-bit vector.
8010 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8011 MVT EltVT = VecVT.getVectorElementType();
8013 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8015 //if (IdxVal >= NumElems/2)
8016 // IdxVal -= NumElems/2;
8017 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8018 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8019 DAG.getConstant(IdxVal, MVT::i32));
8022 assert(VecVT.is128BitVector() && "Unexpected vector length");
8024 if (Subtarget->hasSSE41()) {
8025 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8030 MVT VT = Op.getSimpleValueType();
8031 // TODO: handle v16i8.
8032 if (VT.getSizeInBits() == 16) {
8033 SDValue Vec = Op.getOperand(0);
8034 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8036 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8037 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8038 DAG.getNode(ISD::BITCAST, dl,
8041 // Transform it so it match pextrw which produces a 32-bit result.
8042 MVT EltVT = MVT::i32;
8043 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8044 Op.getOperand(0), Op.getOperand(1));
8045 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8046 DAG.getValueType(VT));
8047 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8050 if (VT.getSizeInBits() == 32) {
8051 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8055 // SHUFPS the element to the lowest double word, then movss.
8056 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8057 MVT VVT = Op.getOperand(0).getSimpleValueType();
8058 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8059 DAG.getUNDEF(VVT), Mask);
8060 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8061 DAG.getIntPtrConstant(0));
8064 if (VT.getSizeInBits() == 64) {
8065 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8066 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8067 // to match extract_elt for f64.
8068 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8072 // UNPCKHPD the element to the lowest double word, then movsd.
8073 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8074 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8075 int Mask[2] = { 1, -1 };
8076 MVT VVT = Op.getOperand(0).getSimpleValueType();
8077 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8078 DAG.getUNDEF(VVT), Mask);
8079 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8080 DAG.getIntPtrConstant(0));
8086 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8087 MVT VT = Op.getSimpleValueType();
8088 MVT EltVT = VT.getVectorElementType();
8091 SDValue N0 = Op.getOperand(0);
8092 SDValue N1 = Op.getOperand(1);
8093 SDValue N2 = Op.getOperand(2);
8095 if (!VT.is128BitVector())
8098 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8099 isa<ConstantSDNode>(N2)) {
8101 if (VT == MVT::v8i16)
8102 Opc = X86ISD::PINSRW;
8103 else if (VT == MVT::v16i8)
8104 Opc = X86ISD::PINSRB;
8106 Opc = X86ISD::PINSRB;
8108 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8110 if (N1.getValueType() != MVT::i32)
8111 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8112 if (N2.getValueType() != MVT::i32)
8113 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8114 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8117 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8118 // Bits [7:6] of the constant are the source select. This will always be
8119 // zero here. The DAG Combiner may combine an extract_elt index into these
8120 // bits. For example (insert (extract, 3), 2) could be matched by putting
8121 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8122 // Bits [5:4] of the constant are the destination select. This is the
8123 // value of the incoming immediate.
8124 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8125 // combine either bitwise AND or insert of float 0.0 to set these bits.
8126 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8127 // Create this as a scalar to vector..
8128 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8129 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8132 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8133 // PINSR* works with constant index.
8139 /// Insert one bit to mask vector, like v16i1 or v8i1.
8140 /// AVX-512 feature.
8142 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8144 SDValue Vec = Op.getOperand(0);
8145 SDValue Elt = Op.getOperand(1);
8146 SDValue Idx = Op.getOperand(2);
8147 MVT VecVT = Vec.getSimpleValueType();
8149 if (!isa<ConstantSDNode>(Idx)) {
8150 // Non constant index. Extend source and destination,
8151 // insert element and then truncate the result.
8152 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8153 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8154 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8155 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8156 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8157 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8160 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8161 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8162 if (Vec.getOpcode() == ISD::UNDEF)
8163 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8164 DAG.getConstant(IdxVal, MVT::i8));
8165 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8166 unsigned MaxSift = rc->getSize()*8 - 1;
8167 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8168 DAG.getConstant(MaxSift, MVT::i8));
8169 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8170 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8171 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8174 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8175 MVT VT = Op.getSimpleValueType();
8176 MVT EltVT = VT.getVectorElementType();
8178 if (EltVT == MVT::i1)
8179 return InsertBitToMaskVector(Op, DAG);
8182 SDValue N0 = Op.getOperand(0);
8183 SDValue N1 = Op.getOperand(1);
8184 SDValue N2 = Op.getOperand(2);
8186 // If this is a 256-bit vector result, first extract the 128-bit vector,
8187 // insert the element into the extracted half and then place it back.
8188 if (VT.is256BitVector() || VT.is512BitVector()) {
8189 if (!isa<ConstantSDNode>(N2))
8192 // Get the desired 128-bit vector half.
8193 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8194 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8196 // Insert the element into the desired half.
8197 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8198 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8200 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8201 DAG.getConstant(IdxIn128, MVT::i32));
8203 // Insert the changed part back to the 256-bit vector
8204 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8207 if (Subtarget->hasSSE41())
8208 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8210 if (EltVT == MVT::i8)
8213 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8214 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8215 // as its second argument.
8216 if (N1.getValueType() != MVT::i32)
8217 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8218 if (N2.getValueType() != MVT::i32)
8219 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8220 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8225 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8227 MVT OpVT = Op.getSimpleValueType();
8229 // If this is a 256-bit vector result, first insert into a 128-bit
8230 // vector and then insert into the 256-bit vector.
8231 if (!OpVT.is128BitVector()) {
8232 // Insert into a 128-bit vector.
8233 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8234 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8235 OpVT.getVectorNumElements() / SizeFactor);
8237 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8239 // Insert the 128-bit vector.
8240 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8243 if (OpVT == MVT::v1i64 &&
8244 Op.getOperand(0).getValueType() == MVT::i64)
8245 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8247 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8248 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8249 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8250 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8253 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8254 // a simple subregister reference or explicit instructions to grab
8255 // upper bits of a vector.
8256 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8257 SelectionDAG &DAG) {
8259 SDValue In = Op.getOperand(0);
8260 SDValue Idx = Op.getOperand(1);
8261 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8262 MVT ResVT = Op.getSimpleValueType();
8263 MVT InVT = In.getSimpleValueType();
8265 if (Subtarget->hasFp256()) {
8266 if (ResVT.is128BitVector() &&
8267 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8268 isa<ConstantSDNode>(Idx)) {
8269 return Extract128BitVector(In, IdxVal, DAG, dl);
8271 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8272 isa<ConstantSDNode>(Idx)) {
8273 return Extract256BitVector(In, IdxVal, DAG, dl);
8279 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8280 // simple superregister reference or explicit instructions to insert
8281 // the upper bits of a vector.
8282 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8283 SelectionDAG &DAG) {
8284 if (Subtarget->hasFp256()) {
8285 SDLoc dl(Op.getNode());
8286 SDValue Vec = Op.getNode()->getOperand(0);
8287 SDValue SubVec = Op.getNode()->getOperand(1);
8288 SDValue Idx = Op.getNode()->getOperand(2);
8290 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8291 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8292 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8293 isa<ConstantSDNode>(Idx)) {
8294 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8295 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8298 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8299 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8300 isa<ConstantSDNode>(Idx)) {
8301 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8302 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8308 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8309 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8310 // one of the above mentioned nodes. It has to be wrapped because otherwise
8311 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8312 // be used to form addressing mode. These wrapped nodes will be selected
8315 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8316 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8318 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8320 unsigned char OpFlag = 0;
8321 unsigned WrapperKind = X86ISD::Wrapper;
8322 CodeModel::Model M = getTargetMachine().getCodeModel();
8324 if (Subtarget->isPICStyleRIPRel() &&
8325 (M == CodeModel::Small || M == CodeModel::Kernel))
8326 WrapperKind = X86ISD::WrapperRIP;
8327 else if (Subtarget->isPICStyleGOT())
8328 OpFlag = X86II::MO_GOTOFF;
8329 else if (Subtarget->isPICStyleStubPIC())
8330 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8332 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8334 CP->getOffset(), OpFlag);
8336 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8337 // With PIC, the address is actually $g + Offset.
8339 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8340 DAG.getNode(X86ISD::GlobalBaseReg,
8341 SDLoc(), getPointerTy()),
8348 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8349 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8351 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8353 unsigned char OpFlag = 0;
8354 unsigned WrapperKind = X86ISD::Wrapper;
8355 CodeModel::Model M = getTargetMachine().getCodeModel();
8357 if (Subtarget->isPICStyleRIPRel() &&
8358 (M == CodeModel::Small || M == CodeModel::Kernel))
8359 WrapperKind = X86ISD::WrapperRIP;
8360 else if (Subtarget->isPICStyleGOT())
8361 OpFlag = X86II::MO_GOTOFF;
8362 else if (Subtarget->isPICStyleStubPIC())
8363 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8365 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8368 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8370 // With PIC, the address is actually $g + Offset.
8372 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8373 DAG.getNode(X86ISD::GlobalBaseReg,
8374 SDLoc(), getPointerTy()),
8381 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8382 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8384 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8386 unsigned char OpFlag = 0;
8387 unsigned WrapperKind = X86ISD::Wrapper;
8388 CodeModel::Model M = getTargetMachine().getCodeModel();
8390 if (Subtarget->isPICStyleRIPRel() &&
8391 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8392 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8393 OpFlag = X86II::MO_GOTPCREL;
8394 WrapperKind = X86ISD::WrapperRIP;
8395 } else if (Subtarget->isPICStyleGOT()) {
8396 OpFlag = X86II::MO_GOT;
8397 } else if (Subtarget->isPICStyleStubPIC()) {
8398 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8399 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8400 OpFlag = X86II::MO_DARWIN_NONLAZY;
8403 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8406 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8408 // With PIC, the address is actually $g + Offset.
8409 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8410 !Subtarget->is64Bit()) {
8411 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8412 DAG.getNode(X86ISD::GlobalBaseReg,
8413 SDLoc(), getPointerTy()),
8417 // For symbols that require a load from a stub to get the address, emit the
8419 if (isGlobalStubReference(OpFlag))
8420 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8421 MachinePointerInfo::getGOT(), false, false, false, 0);
8427 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8428 // Create the TargetBlockAddressAddress node.
8429 unsigned char OpFlags =
8430 Subtarget->ClassifyBlockAddressReference();
8431 CodeModel::Model M = getTargetMachine().getCodeModel();
8432 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8433 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8435 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8438 if (Subtarget->isPICStyleRIPRel() &&
8439 (M == CodeModel::Small || M == CodeModel::Kernel))
8440 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8442 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8444 // With PIC, the address is actually $g + Offset.
8445 if (isGlobalRelativeToPICBase(OpFlags)) {
8446 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8447 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8455 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8456 int64_t Offset, SelectionDAG &DAG) const {
8457 // Create the TargetGlobalAddress node, folding in the constant
8458 // offset if it is legal.
8459 unsigned char OpFlags =
8460 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8461 CodeModel::Model M = getTargetMachine().getCodeModel();
8463 if (OpFlags == X86II::MO_NO_FLAG &&
8464 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8465 // A direct static reference to a global.
8466 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8469 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8472 if (Subtarget->isPICStyleRIPRel() &&
8473 (M == CodeModel::Small || M == CodeModel::Kernel))
8474 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8476 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8478 // With PIC, the address is actually $g + Offset.
8479 if (isGlobalRelativeToPICBase(OpFlags)) {
8480 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8481 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8485 // For globals that require a load from a stub to get the address, emit the
8487 if (isGlobalStubReference(OpFlags))
8488 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8489 MachinePointerInfo::getGOT(), false, false, false, 0);
8491 // If there was a non-zero offset that we didn't fold, create an explicit
8494 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8495 DAG.getConstant(Offset, getPointerTy()));
8501 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8502 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8503 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8504 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8508 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8509 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8510 unsigned char OperandFlags, bool LocalDynamic = false) {
8511 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8512 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8514 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8515 GA->getValueType(0),
8519 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8523 SDValue Ops[] = { Chain, TGA, *InFlag };
8524 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8526 SDValue Ops[] = { Chain, TGA };
8527 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8530 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8531 MFI->setAdjustsStack(true);
8533 SDValue Flag = Chain.getValue(1);
8534 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8537 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8539 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8542 SDLoc dl(GA); // ? function entry point might be better
8543 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8544 DAG.getNode(X86ISD::GlobalBaseReg,
8545 SDLoc(), PtrVT), InFlag);
8546 InFlag = Chain.getValue(1);
8548 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8551 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8553 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8555 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8556 X86::RAX, X86II::MO_TLSGD);
8559 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8565 // Get the start address of the TLS block for this module.
8566 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8567 .getInfo<X86MachineFunctionInfo>();
8568 MFI->incNumLocalDynamicTLSAccesses();
8572 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8573 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8576 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8577 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8578 InFlag = Chain.getValue(1);
8579 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8580 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8583 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8587 unsigned char OperandFlags = X86II::MO_DTPOFF;
8588 unsigned WrapperKind = X86ISD::Wrapper;
8589 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8590 GA->getValueType(0),
8591 GA->getOffset(), OperandFlags);
8592 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8594 // Add x@dtpoff with the base.
8595 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8598 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8599 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8600 const EVT PtrVT, TLSModel::Model model,
8601 bool is64Bit, bool isPIC) {
8604 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8605 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8606 is64Bit ? 257 : 256));
8608 SDValue ThreadPointer =
8609 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8610 MachinePointerInfo(Ptr), false, false, false, 0);
8612 unsigned char OperandFlags = 0;
8613 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8615 unsigned WrapperKind = X86ISD::Wrapper;
8616 if (model == TLSModel::LocalExec) {
8617 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8618 } else if (model == TLSModel::InitialExec) {
8620 OperandFlags = X86II::MO_GOTTPOFF;
8621 WrapperKind = X86ISD::WrapperRIP;
8623 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8626 llvm_unreachable("Unexpected model");
8629 // emit "addl x@ntpoff,%eax" (local exec)
8630 // or "addl x@indntpoff,%eax" (initial exec)
8631 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8633 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8634 GA->getOffset(), OperandFlags);
8635 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8637 if (model == TLSModel::InitialExec) {
8638 if (isPIC && !is64Bit) {
8639 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8640 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8644 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8645 MachinePointerInfo::getGOT(), false, false, false, 0);
8648 // The address of the thread local variable is the add of the thread
8649 // pointer with the offset of the variable.
8650 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8654 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8656 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8657 const GlobalValue *GV = GA->getGlobal();
8659 if (Subtarget->isTargetELF()) {
8660 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8663 case TLSModel::GeneralDynamic:
8664 if (Subtarget->is64Bit())
8665 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8666 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8667 case TLSModel::LocalDynamic:
8668 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8669 Subtarget->is64Bit());
8670 case TLSModel::InitialExec:
8671 case TLSModel::LocalExec:
8672 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8673 Subtarget->is64Bit(),
8674 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8676 llvm_unreachable("Unknown TLS model.");
8679 if (Subtarget->isTargetDarwin()) {
8680 // Darwin only has one model of TLS. Lower to that.
8681 unsigned char OpFlag = 0;
8682 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8683 X86ISD::WrapperRIP : X86ISD::Wrapper;
8685 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8687 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8688 !Subtarget->is64Bit();
8690 OpFlag = X86II::MO_TLVP_PIC_BASE;
8692 OpFlag = X86II::MO_TLVP;
8694 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8695 GA->getValueType(0),
8696 GA->getOffset(), OpFlag);
8697 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8699 // With PIC32, the address is actually $g + Offset.
8701 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8702 DAG.getNode(X86ISD::GlobalBaseReg,
8703 SDLoc(), getPointerTy()),
8706 // Lowering the machine isd will make sure everything is in the right
8708 SDValue Chain = DAG.getEntryNode();
8709 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8710 SDValue Args[] = { Chain, Offset };
8711 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8713 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8714 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8715 MFI->setAdjustsStack(true);
8717 // And our return value (tls address) is in the standard call return value
8719 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8720 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8724 if (Subtarget->isTargetKnownWindowsMSVC() ||
8725 Subtarget->isTargetWindowsGNU()) {
8726 // Just use the implicit TLS architecture
8727 // Need to generate someting similar to:
8728 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8730 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8731 // mov rcx, qword [rdx+rcx*8]
8732 // mov eax, .tls$:tlsvar
8733 // [rax+rcx] contains the address
8734 // Windows 64bit: gs:0x58
8735 // Windows 32bit: fs:__tls_array
8737 // If GV is an alias then use the aliasee for determining
8738 // thread-localness.
8739 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8740 GV = GA->getAliasedGlobal();
8742 SDValue Chain = DAG.getEntryNode();
8744 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8745 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8746 // use its literal value of 0x2C.
8747 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8748 ? Type::getInt8PtrTy(*DAG.getContext(),
8750 : Type::getInt32PtrTy(*DAG.getContext(),
8754 Subtarget->is64Bit()
8755 ? DAG.getIntPtrConstant(0x58)
8756 : (Subtarget->isTargetWindowsGNU()
8757 ? DAG.getIntPtrConstant(0x2C)
8758 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8760 SDValue ThreadPointer =
8761 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8762 MachinePointerInfo(Ptr), false, false, false, 0);
8764 // Load the _tls_index variable
8765 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8766 if (Subtarget->is64Bit())
8767 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8768 IDX, MachinePointerInfo(), MVT::i32,
8771 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8772 false, false, false, 0);
8774 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8776 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8778 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8779 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8780 false, false, false, 0);
8782 // Get the offset of start of .tls section
8783 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8784 GA->getValueType(0),
8785 GA->getOffset(), X86II::MO_SECREL);
8786 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8788 // The address of the thread local variable is the add of the thread
8789 // pointer with the offset of the variable.
8790 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8793 llvm_unreachable("TLS not implemented for this target.");
8796 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8797 /// and take a 2 x i32 value to shift plus a shift amount.
8798 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8799 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8800 MVT VT = Op.getSimpleValueType();
8801 unsigned VTBits = VT.getSizeInBits();
8803 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8804 SDValue ShOpLo = Op.getOperand(0);
8805 SDValue ShOpHi = Op.getOperand(1);
8806 SDValue ShAmt = Op.getOperand(2);
8807 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8808 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8810 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8811 DAG.getConstant(VTBits - 1, MVT::i8));
8812 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8813 DAG.getConstant(VTBits - 1, MVT::i8))
8814 : DAG.getConstant(0, VT);
8817 if (Op.getOpcode() == ISD::SHL_PARTS) {
8818 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8819 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8821 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8822 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8825 // If the shift amount is larger or equal than the width of a part we can't
8826 // rely on the results of shld/shrd. Insert a test and select the appropriate
8827 // values for large shift amounts.
8828 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8829 DAG.getConstant(VTBits, MVT::i8));
8830 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8831 AndNode, DAG.getConstant(0, MVT::i8));
8834 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8835 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8836 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8838 if (Op.getOpcode() == ISD::SHL_PARTS) {
8839 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8840 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8842 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8843 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8846 SDValue Ops[2] = { Lo, Hi };
8847 return DAG.getMergeValues(Ops, dl);
8850 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8851 SelectionDAG &DAG) const {
8852 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8854 if (SrcVT.isVector())
8857 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8858 "Unknown SINT_TO_FP to lower!");
8860 // These are really Legal; return the operand so the caller accepts it as
8862 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8864 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8865 Subtarget->is64Bit()) {
8870 unsigned Size = SrcVT.getSizeInBits()/8;
8871 MachineFunction &MF = DAG.getMachineFunction();
8872 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8873 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8874 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8876 MachinePointerInfo::getFixedStack(SSFI),
8878 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8881 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8883 SelectionDAG &DAG) const {
8887 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8889 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8891 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8893 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8895 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8896 MachineMemOperand *MMO;
8898 int SSFI = FI->getIndex();
8900 DAG.getMachineFunction()
8901 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8902 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8904 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8905 StackSlot = StackSlot.getOperand(1);
8907 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8908 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8910 Tys, Ops, SrcVT, MMO);
8913 Chain = Result.getValue(1);
8914 SDValue InFlag = Result.getValue(2);
8916 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8917 // shouldn't be necessary except that RFP cannot be live across
8918 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8919 MachineFunction &MF = DAG.getMachineFunction();
8920 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8921 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8922 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8923 Tys = DAG.getVTList(MVT::Other);
8925 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8927 MachineMemOperand *MMO =
8928 DAG.getMachineFunction()
8929 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8930 MachineMemOperand::MOStore, SSFISize, SSFISize);
8932 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8933 Ops, Op.getValueType(), MMO);
8934 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8935 MachinePointerInfo::getFixedStack(SSFI),
8936 false, false, false, 0);
8942 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8943 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8944 SelectionDAG &DAG) const {
8945 // This algorithm is not obvious. Here it is what we're trying to output:
8948 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8949 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8953 pshufd $0x4e, %xmm0, %xmm1
8959 LLVMContext *Context = DAG.getContext();
8961 // Build some magic constants.
8962 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8963 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8964 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8966 SmallVector<Constant*,2> CV1;
8968 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8969 APInt(64, 0x4330000000000000ULL))));
8971 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8972 APInt(64, 0x4530000000000000ULL))));
8973 Constant *C1 = ConstantVector::get(CV1);
8974 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8976 // Load the 64-bit value into an XMM register.
8977 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8979 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8980 MachinePointerInfo::getConstantPool(),
8981 false, false, false, 16);
8982 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8983 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8986 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8987 MachinePointerInfo::getConstantPool(),
8988 false, false, false, 16);
8989 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8990 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8993 if (Subtarget->hasSSE3()) {
8994 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8995 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8997 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8998 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9000 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9001 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9005 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9006 DAG.getIntPtrConstant(0));
9009 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9010 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9011 SelectionDAG &DAG) const {
9013 // FP constant to bias correct the final result.
9014 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9017 // Load the 32-bit value into an XMM register.
9018 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9021 // Zero out the upper parts of the register.
9022 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9024 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9025 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9026 DAG.getIntPtrConstant(0));
9028 // Or the load with the bias.
9029 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9030 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9031 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9033 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9034 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9035 MVT::v2f64, Bias)));
9036 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9037 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9038 DAG.getIntPtrConstant(0));
9040 // Subtract the bias.
9041 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9043 // Handle final rounding.
9044 EVT DestVT = Op.getValueType();
9046 if (DestVT.bitsLT(MVT::f64))
9047 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9048 DAG.getIntPtrConstant(0));
9049 if (DestVT.bitsGT(MVT::f64))
9050 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9052 // Handle final rounding.
9056 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9057 SelectionDAG &DAG) const {
9058 SDValue N0 = Op.getOperand(0);
9059 MVT SVT = N0.getSimpleValueType();
9062 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9063 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9064 "Custom UINT_TO_FP is not supported!");
9066 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9067 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9068 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9071 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9072 SelectionDAG &DAG) const {
9073 SDValue N0 = Op.getOperand(0);
9076 if (Op.getValueType().isVector())
9077 return lowerUINT_TO_FP_vec(Op, DAG);
9079 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9080 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9081 // the optimization here.
9082 if (DAG.SignBitIsZero(N0))
9083 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9085 MVT SrcVT = N0.getSimpleValueType();
9086 MVT DstVT = Op.getSimpleValueType();
9087 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9088 return LowerUINT_TO_FP_i64(Op, DAG);
9089 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9090 return LowerUINT_TO_FP_i32(Op, DAG);
9091 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9094 // Make a 64-bit buffer, and use it to build an FILD.
9095 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9096 if (SrcVT == MVT::i32) {
9097 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9098 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9099 getPointerTy(), StackSlot, WordOff);
9100 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9101 StackSlot, MachinePointerInfo(),
9103 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9104 OffsetSlot, MachinePointerInfo(),
9106 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9110 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9111 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9112 StackSlot, MachinePointerInfo(),
9114 // For i64 source, we need to add the appropriate power of 2 if the input
9115 // was negative. This is the same as the optimization in
9116 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9117 // we must be careful to do the computation in x87 extended precision, not
9118 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9119 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9120 MachineMemOperand *MMO =
9121 DAG.getMachineFunction()
9122 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9123 MachineMemOperand::MOLoad, 8, 8);
9125 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9126 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9127 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9130 APInt FF(32, 0x5F800000ULL);
9132 // Check whether the sign bit is set.
9133 SDValue SignSet = DAG.getSetCC(dl,
9134 getSetCCResultType(*DAG.getContext(), MVT::i64),
9135 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9138 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9139 SDValue FudgePtr = DAG.getConstantPool(
9140 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9143 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9144 SDValue Zero = DAG.getIntPtrConstant(0);
9145 SDValue Four = DAG.getIntPtrConstant(4);
9146 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9148 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9150 // Load the value out, extending it from f32 to f80.
9151 // FIXME: Avoid the extend by constructing the right constant pool?
9152 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9153 FudgePtr, MachinePointerInfo::getConstantPool(),
9154 MVT::f32, false, false, 4);
9155 // Extend everything to 80 bits to force it to be done on x87.
9156 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9157 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9160 std::pair<SDValue,SDValue>
9161 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9162 bool IsSigned, bool IsReplace) const {
9165 EVT DstTy = Op.getValueType();
9167 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9168 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9172 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9173 DstTy.getSimpleVT() >= MVT::i16 &&
9174 "Unknown FP_TO_INT to lower!");
9176 // These are really Legal.
9177 if (DstTy == MVT::i32 &&
9178 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9179 return std::make_pair(SDValue(), SDValue());
9180 if (Subtarget->is64Bit() &&
9181 DstTy == MVT::i64 &&
9182 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9183 return std::make_pair(SDValue(), SDValue());
9185 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9186 // stack slot, or into the FTOL runtime function.
9187 MachineFunction &MF = DAG.getMachineFunction();
9188 unsigned MemSize = DstTy.getSizeInBits()/8;
9189 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9190 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9193 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9194 Opc = X86ISD::WIN_FTOL;
9196 switch (DstTy.getSimpleVT().SimpleTy) {
9197 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9198 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9199 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9200 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9203 SDValue Chain = DAG.getEntryNode();
9204 SDValue Value = Op.getOperand(0);
9205 EVT TheVT = Op.getOperand(0).getValueType();
9206 // FIXME This causes a redundant load/store if the SSE-class value is already
9207 // in memory, such as if it is on the callstack.
9208 if (isScalarFPTypeInSSEReg(TheVT)) {
9209 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9210 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9211 MachinePointerInfo::getFixedStack(SSFI),
9213 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9215 Chain, StackSlot, DAG.getValueType(TheVT)
9218 MachineMemOperand *MMO =
9219 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9220 MachineMemOperand::MOLoad, MemSize, MemSize);
9221 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9222 Chain = Value.getValue(1);
9223 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9224 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9227 MachineMemOperand *MMO =
9228 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9229 MachineMemOperand::MOStore, MemSize, MemSize);
9231 if (Opc != X86ISD::WIN_FTOL) {
9232 // Build the FP_TO_INT*_IN_MEM
9233 SDValue Ops[] = { Chain, Value, StackSlot };
9234 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9236 return std::make_pair(FIST, StackSlot);
9238 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9239 DAG.getVTList(MVT::Other, MVT::Glue),
9241 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9242 MVT::i32, ftol.getValue(1));
9243 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9244 MVT::i32, eax.getValue(2));
9245 SDValue Ops[] = { eax, edx };
9246 SDValue pair = IsReplace
9247 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9248 : DAG.getMergeValues(Ops, DL);
9249 return std::make_pair(pair, SDValue());
9253 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9254 const X86Subtarget *Subtarget) {
9255 MVT VT = Op->getSimpleValueType(0);
9256 SDValue In = Op->getOperand(0);
9257 MVT InVT = In.getSimpleValueType();
9260 // Optimize vectors in AVX mode:
9263 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9264 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9265 // Concat upper and lower parts.
9268 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9269 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9270 // Concat upper and lower parts.
9273 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9274 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9275 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9278 if (Subtarget->hasInt256())
9279 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9281 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9282 SDValue Undef = DAG.getUNDEF(InVT);
9283 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9284 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9285 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9287 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9288 VT.getVectorNumElements()/2);
9290 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9291 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9293 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9296 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9297 SelectionDAG &DAG) {
9298 MVT VT = Op->getSimpleValueType(0);
9299 SDValue In = Op->getOperand(0);
9300 MVT InVT = In.getSimpleValueType();
9302 unsigned int NumElts = VT.getVectorNumElements();
9303 if (NumElts != 8 && NumElts != 16)
9306 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9307 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9309 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9310 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9311 // Now we have only mask extension
9312 assert(InVT.getVectorElementType() == MVT::i1);
9313 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9314 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9315 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9316 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9317 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9318 MachinePointerInfo::getConstantPool(),
9319 false, false, false, Alignment);
9321 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9322 if (VT.is512BitVector())
9324 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9327 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9328 SelectionDAG &DAG) {
9329 if (Subtarget->hasFp256()) {
9330 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9338 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9339 SelectionDAG &DAG) {
9341 MVT VT = Op.getSimpleValueType();
9342 SDValue In = Op.getOperand(0);
9343 MVT SVT = In.getSimpleValueType();
9345 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9346 return LowerZERO_EXTEND_AVX512(Op, DAG);
9348 if (Subtarget->hasFp256()) {
9349 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9354 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9355 VT.getVectorNumElements() != SVT.getVectorNumElements());
9359 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9361 MVT VT = Op.getSimpleValueType();
9362 SDValue In = Op.getOperand(0);
9363 MVT InVT = In.getSimpleValueType();
9365 if (VT == MVT::i1) {
9366 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9367 "Invalid scalar TRUNCATE operation");
9368 if (InVT == MVT::i32)
9370 if (InVT.getSizeInBits() == 64)
9371 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9372 else if (InVT.getSizeInBits() < 32)
9373 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9374 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9376 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9377 "Invalid TRUNCATE operation");
9379 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9380 if (VT.getVectorElementType().getSizeInBits() >=8)
9381 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9383 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9384 unsigned NumElts = InVT.getVectorNumElements();
9385 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9386 if (InVT.getSizeInBits() < 512) {
9387 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9388 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9392 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9393 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9394 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9395 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9396 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9397 MachinePointerInfo::getConstantPool(),
9398 false, false, false, Alignment);
9399 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9400 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9401 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9404 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9405 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9406 if (Subtarget->hasInt256()) {
9407 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9408 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9409 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9411 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9412 DAG.getIntPtrConstant(0));
9415 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9416 DAG.getIntPtrConstant(0));
9417 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9418 DAG.getIntPtrConstant(2));
9419 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9420 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9421 static const int ShufMask[] = {0, 2, 4, 6};
9422 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9425 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9426 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9427 if (Subtarget->hasInt256()) {
9428 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9430 SmallVector<SDValue,32> pshufbMask;
9431 for (unsigned i = 0; i < 2; ++i) {
9432 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9433 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9434 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9435 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9436 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9437 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9438 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9439 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9440 for (unsigned j = 0; j < 8; ++j)
9441 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9443 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9444 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9445 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9447 static const int ShufMask[] = {0, 2, -1, -1};
9448 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9450 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9451 DAG.getIntPtrConstant(0));
9452 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9455 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9456 DAG.getIntPtrConstant(0));
9458 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9459 DAG.getIntPtrConstant(4));
9461 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9462 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9465 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9466 -1, -1, -1, -1, -1, -1, -1, -1};
9468 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9469 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9470 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9472 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9473 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9475 // The MOVLHPS Mask:
9476 static const int ShufMask2[] = {0, 1, 4, 5};
9477 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9478 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9481 // Handle truncation of V256 to V128 using shuffles.
9482 if (!VT.is128BitVector() || !InVT.is256BitVector())
9485 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9487 unsigned NumElems = VT.getVectorNumElements();
9488 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9490 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9491 // Prepare truncation shuffle mask
9492 for (unsigned i = 0; i != NumElems; ++i)
9494 SDValue V = DAG.getVectorShuffle(NVT, DL,
9495 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9496 DAG.getUNDEF(NVT), &MaskVec[0]);
9497 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9498 DAG.getIntPtrConstant(0));
9501 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9502 SelectionDAG &DAG) const {
9503 assert(!Op.getSimpleValueType().isVector());
9505 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9506 /*IsSigned=*/ true, /*IsReplace=*/ false);
9507 SDValue FIST = Vals.first, StackSlot = Vals.second;
9508 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9509 if (!FIST.getNode()) return Op;
9511 if (StackSlot.getNode())
9513 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9514 FIST, StackSlot, MachinePointerInfo(),
9515 false, false, false, 0);
9517 // The node is the result.
9521 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9522 SelectionDAG &DAG) const {
9523 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9524 /*IsSigned=*/ false, /*IsReplace=*/ false);
9525 SDValue FIST = Vals.first, StackSlot = Vals.second;
9526 assert(FIST.getNode() && "Unexpected failure");
9528 if (StackSlot.getNode())
9530 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9531 FIST, StackSlot, MachinePointerInfo(),
9532 false, false, false, 0);
9534 // The node is the result.
9538 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9540 MVT VT = Op.getSimpleValueType();
9541 SDValue In = Op.getOperand(0);
9542 MVT SVT = In.getSimpleValueType();
9544 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9546 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9547 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9548 In, DAG.getUNDEF(SVT)));
9551 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9552 LLVMContext *Context = DAG.getContext();
9554 MVT VT = Op.getSimpleValueType();
9556 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9557 if (VT.isVector()) {
9558 EltVT = VT.getVectorElementType();
9559 NumElts = VT.getVectorNumElements();
9562 if (EltVT == MVT::f64)
9563 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9564 APInt(64, ~(1ULL << 63))));
9566 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9567 APInt(32, ~(1U << 31))));
9568 C = ConstantVector::getSplat(NumElts, C);
9569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9570 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9571 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9572 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9573 MachinePointerInfo::getConstantPool(),
9574 false, false, false, Alignment);
9575 if (VT.isVector()) {
9576 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9577 return DAG.getNode(ISD::BITCAST, dl, VT,
9578 DAG.getNode(ISD::AND, dl, ANDVT,
9579 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9581 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9583 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9586 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9587 LLVMContext *Context = DAG.getContext();
9589 MVT VT = Op.getSimpleValueType();
9591 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9592 if (VT.isVector()) {
9593 EltVT = VT.getVectorElementType();
9594 NumElts = VT.getVectorNumElements();
9597 if (EltVT == MVT::f64)
9598 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9599 APInt(64, 1ULL << 63)));
9601 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9602 APInt(32, 1U << 31)));
9603 C = ConstantVector::getSplat(NumElts, C);
9604 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9605 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9606 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9607 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9608 MachinePointerInfo::getConstantPool(),
9609 false, false, false, Alignment);
9610 if (VT.isVector()) {
9611 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9612 return DAG.getNode(ISD::BITCAST, dl, VT,
9613 DAG.getNode(ISD::XOR, dl, XORVT,
9614 DAG.getNode(ISD::BITCAST, dl, XORVT,
9616 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9619 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9622 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9623 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9624 LLVMContext *Context = DAG.getContext();
9625 SDValue Op0 = Op.getOperand(0);
9626 SDValue Op1 = Op.getOperand(1);
9628 MVT VT = Op.getSimpleValueType();
9629 MVT SrcVT = Op1.getSimpleValueType();
9631 // If second operand is smaller, extend it first.
9632 if (SrcVT.bitsLT(VT)) {
9633 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9636 // And if it is bigger, shrink it first.
9637 if (SrcVT.bitsGT(VT)) {
9638 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9642 // At this point the operands and the result should have the same
9643 // type, and that won't be f80 since that is not custom lowered.
9645 // First get the sign bit of second operand.
9646 SmallVector<Constant*,4> CV;
9647 if (SrcVT == MVT::f64) {
9648 const fltSemantics &Sem = APFloat::IEEEdouble;
9649 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9650 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9652 const fltSemantics &Sem = APFloat::IEEEsingle;
9653 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9654 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9655 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9656 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9658 Constant *C = ConstantVector::get(CV);
9659 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9660 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9661 MachinePointerInfo::getConstantPool(),
9662 false, false, false, 16);
9663 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9665 // Shift sign bit right or left if the two operands have different types.
9666 if (SrcVT.bitsGT(VT)) {
9667 // Op0 is MVT::f32, Op1 is MVT::f64.
9668 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9669 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9670 DAG.getConstant(32, MVT::i32));
9671 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9672 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9673 DAG.getIntPtrConstant(0));
9676 // Clear first operand sign bit.
9678 if (VT == MVT::f64) {
9679 const fltSemantics &Sem = APFloat::IEEEdouble;
9680 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9681 APInt(64, ~(1ULL << 63)))));
9682 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9684 const fltSemantics &Sem = APFloat::IEEEsingle;
9685 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9686 APInt(32, ~(1U << 31)))));
9687 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9688 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9689 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9691 C = ConstantVector::get(CV);
9692 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9693 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9694 MachinePointerInfo::getConstantPool(),
9695 false, false, false, 16);
9696 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9698 // Or the value with the sign bit.
9699 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9702 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9703 SDValue N0 = Op.getOperand(0);
9705 MVT VT = Op.getSimpleValueType();
9707 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9708 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9709 DAG.getConstant(1, VT));
9710 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9713 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9715 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9716 SelectionDAG &DAG) {
9717 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9719 if (!Subtarget->hasSSE41())
9722 if (!Op->hasOneUse())
9725 SDNode *N = Op.getNode();
9728 SmallVector<SDValue, 8> Opnds;
9729 DenseMap<SDValue, unsigned> VecInMap;
9730 SmallVector<SDValue, 8> VecIns;
9731 EVT VT = MVT::Other;
9733 // Recognize a special case where a vector is casted into wide integer to
9735 Opnds.push_back(N->getOperand(0));
9736 Opnds.push_back(N->getOperand(1));
9738 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9739 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9740 // BFS traverse all OR'd operands.
9741 if (I->getOpcode() == ISD::OR) {
9742 Opnds.push_back(I->getOperand(0));
9743 Opnds.push_back(I->getOperand(1));
9744 // Re-evaluate the number of nodes to be traversed.
9745 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9749 // Quit if a non-EXTRACT_VECTOR_ELT
9750 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9753 // Quit if without a constant index.
9754 SDValue Idx = I->getOperand(1);
9755 if (!isa<ConstantSDNode>(Idx))
9758 SDValue ExtractedFromVec = I->getOperand(0);
9759 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9760 if (M == VecInMap.end()) {
9761 VT = ExtractedFromVec.getValueType();
9762 // Quit if not 128/256-bit vector.
9763 if (!VT.is128BitVector() && !VT.is256BitVector())
9765 // Quit if not the same type.
9766 if (VecInMap.begin() != VecInMap.end() &&
9767 VT != VecInMap.begin()->first.getValueType())
9769 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9770 VecIns.push_back(ExtractedFromVec);
9772 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9775 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9776 "Not extracted from 128-/256-bit vector.");
9778 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9780 for (DenseMap<SDValue, unsigned>::const_iterator
9781 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9782 // Quit if not all elements are used.
9783 if (I->second != FullMask)
9787 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9789 // Cast all vectors into TestVT for PTEST.
9790 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9791 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9793 // If more than one full vectors are evaluated, OR them first before PTEST.
9794 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9795 // Each iteration will OR 2 nodes and append the result until there is only
9796 // 1 node left, i.e. the final OR'd value of all vectors.
9797 SDValue LHS = VecIns[Slot];
9798 SDValue RHS = VecIns[Slot + 1];
9799 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9802 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9803 VecIns.back(), VecIns.back());
9806 /// \brief return true if \c Op has a use that doesn't just read flags.
9807 static bool hasNonFlagsUse(SDValue Op) {
9808 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9811 unsigned UOpNo = UI.getOperandNo();
9812 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9813 // Look pass truncate.
9814 UOpNo = User->use_begin().getOperandNo();
9815 User = *User->use_begin();
9818 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9819 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9825 /// Emit nodes that will be selected as "test Op0,Op0", or something
9827 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9828 SelectionDAG &DAG) const {
9829 if (Op.getValueType() == MVT::i1)
9830 // KORTEST instruction should be selected
9831 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9832 DAG.getConstant(0, Op.getValueType()));
9834 // CF and OF aren't always set the way we want. Determine which
9835 // of these we need.
9836 bool NeedCF = false;
9837 bool NeedOF = false;
9840 case X86::COND_A: case X86::COND_AE:
9841 case X86::COND_B: case X86::COND_BE:
9844 case X86::COND_G: case X86::COND_GE:
9845 case X86::COND_L: case X86::COND_LE:
9846 case X86::COND_O: case X86::COND_NO:
9850 // See if we can use the EFLAGS value from the operand instead of
9851 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9852 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9853 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9854 // Emit a CMP with 0, which is the TEST pattern.
9855 //if (Op.getValueType() == MVT::i1)
9856 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9857 // DAG.getConstant(0, MVT::i1));
9858 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9859 DAG.getConstant(0, Op.getValueType()));
9861 unsigned Opcode = 0;
9862 unsigned NumOperands = 0;
9864 // Truncate operations may prevent the merge of the SETCC instruction
9865 // and the arithmetic instruction before it. Attempt to truncate the operands
9866 // of the arithmetic instruction and use a reduced bit-width instruction.
9867 bool NeedTruncation = false;
9868 SDValue ArithOp = Op;
9869 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9870 SDValue Arith = Op->getOperand(0);
9871 // Both the trunc and the arithmetic op need to have one user each.
9872 if (Arith->hasOneUse())
9873 switch (Arith.getOpcode()) {
9880 NeedTruncation = true;
9886 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9887 // which may be the result of a CAST. We use the variable 'Op', which is the
9888 // non-casted variable when we check for possible users.
9889 switch (ArithOp.getOpcode()) {
9891 // Due to an isel shortcoming, be conservative if this add is likely to be
9892 // selected as part of a load-modify-store instruction. When the root node
9893 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9894 // uses of other nodes in the match, such as the ADD in this case. This
9895 // leads to the ADD being left around and reselected, with the result being
9896 // two adds in the output. Alas, even if none our users are stores, that
9897 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9898 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9899 // climbing the DAG back to the root, and it doesn't seem to be worth the
9901 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9902 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9903 if (UI->getOpcode() != ISD::CopyToReg &&
9904 UI->getOpcode() != ISD::SETCC &&
9905 UI->getOpcode() != ISD::STORE)
9908 if (ConstantSDNode *C =
9909 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9910 // An add of one will be selected as an INC.
9911 if (C->getAPIntValue() == 1) {
9912 Opcode = X86ISD::INC;
9917 // An add of negative one (subtract of one) will be selected as a DEC.
9918 if (C->getAPIntValue().isAllOnesValue()) {
9919 Opcode = X86ISD::DEC;
9925 // Otherwise use a regular EFLAGS-setting add.
9926 Opcode = X86ISD::ADD;
9931 // If we have a constant logical shift that's only used in a comparison
9932 // against zero turn it into an equivalent AND. This allows turning it into
9933 // a TEST instruction later.
9934 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9935 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9936 EVT VT = Op.getValueType();
9937 unsigned BitWidth = VT.getSizeInBits();
9938 unsigned ShAmt = Op->getConstantOperandVal(1);
9939 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9941 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9942 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9943 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9944 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9946 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9947 DAG.getConstant(Mask, VT));
9948 DAG.ReplaceAllUsesWith(Op, New);
9954 // If the primary and result isn't used, don't bother using X86ISD::AND,
9955 // because a TEST instruction will be better.
9956 if (!hasNonFlagsUse(Op))
9962 // Due to the ISEL shortcoming noted above, be conservative if this op is
9963 // likely to be selected as part of a load-modify-store instruction.
9964 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9965 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9966 if (UI->getOpcode() == ISD::STORE)
9969 // Otherwise use a regular EFLAGS-setting instruction.
9970 switch (ArithOp.getOpcode()) {
9971 default: llvm_unreachable("unexpected operator!");
9972 case ISD::SUB: Opcode = X86ISD::SUB; break;
9973 case ISD::XOR: Opcode = X86ISD::XOR; break;
9974 case ISD::AND: Opcode = X86ISD::AND; break;
9976 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9977 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9978 if (EFLAGS.getNode())
9981 Opcode = X86ISD::OR;
9995 return SDValue(Op.getNode(), 1);
10001 // If we found that truncation is beneficial, perform the truncation and
10003 if (NeedTruncation) {
10004 EVT VT = Op.getValueType();
10005 SDValue WideVal = Op->getOperand(0);
10006 EVT WideVT = WideVal.getValueType();
10007 unsigned ConvertedOp = 0;
10008 // Use a target machine opcode to prevent further DAGCombine
10009 // optimizations that may separate the arithmetic operations
10010 // from the setcc node.
10011 switch (WideVal.getOpcode()) {
10013 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10014 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10015 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10016 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10017 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10021 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10022 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10023 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10024 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10025 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10031 // Emit a CMP with 0, which is the TEST pattern.
10032 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10033 DAG.getConstant(0, Op.getValueType()));
10035 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10036 SmallVector<SDValue, 4> Ops;
10037 for (unsigned i = 0; i != NumOperands; ++i)
10038 Ops.push_back(Op.getOperand(i));
10040 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10041 DAG.ReplaceAllUsesWith(Op, New);
10042 return SDValue(New.getNode(), 1);
10045 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10047 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10048 SDLoc dl, SelectionDAG &DAG) const {
10049 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10050 if (C->getAPIntValue() == 0)
10051 return EmitTest(Op0, X86CC, dl, DAG);
10053 if (Op0.getValueType() == MVT::i1)
10054 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10057 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10058 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10059 // Do the comparison at i32 if it's smaller, besides the Atom case.
10060 // This avoids subregister aliasing issues. Keep the smaller reference
10061 // if we're optimizing for size, however, as that'll allow better folding
10062 // of memory operations.
10063 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10064 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10065 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10066 !Subtarget->isAtom()) {
10067 unsigned ExtendOp =
10068 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10069 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10070 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10072 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10073 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10074 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10076 return SDValue(Sub.getNode(), 1);
10078 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10081 /// Convert a comparison if required by the subtarget.
10082 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10083 SelectionDAG &DAG) const {
10084 // If the subtarget does not support the FUCOMI instruction, floating-point
10085 // comparisons have to be converted.
10086 if (Subtarget->hasCMov() ||
10087 Cmp.getOpcode() != X86ISD::CMP ||
10088 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10089 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10092 // The instruction selector will select an FUCOM instruction instead of
10093 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10094 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10095 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10097 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10098 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10099 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10100 DAG.getConstant(8, MVT::i8));
10101 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10102 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10105 static bool isAllOnes(SDValue V) {
10106 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10107 return C && C->isAllOnesValue();
10110 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10111 /// if it's possible.
10112 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10113 SDLoc dl, SelectionDAG &DAG) const {
10114 SDValue Op0 = And.getOperand(0);
10115 SDValue Op1 = And.getOperand(1);
10116 if (Op0.getOpcode() == ISD::TRUNCATE)
10117 Op0 = Op0.getOperand(0);
10118 if (Op1.getOpcode() == ISD::TRUNCATE)
10119 Op1 = Op1.getOperand(0);
10122 if (Op1.getOpcode() == ISD::SHL)
10123 std::swap(Op0, Op1);
10124 if (Op0.getOpcode() == ISD::SHL) {
10125 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10126 if (And00C->getZExtValue() == 1) {
10127 // If we looked past a truncate, check that it's only truncating away
10129 unsigned BitWidth = Op0.getValueSizeInBits();
10130 unsigned AndBitWidth = And.getValueSizeInBits();
10131 if (BitWidth > AndBitWidth) {
10133 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10134 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10138 RHS = Op0.getOperand(1);
10140 } else if (Op1.getOpcode() == ISD::Constant) {
10141 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10142 uint64_t AndRHSVal = AndRHS->getZExtValue();
10143 SDValue AndLHS = Op0;
10145 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10146 LHS = AndLHS.getOperand(0);
10147 RHS = AndLHS.getOperand(1);
10150 // Use BT if the immediate can't be encoded in a TEST instruction.
10151 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10153 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10157 if (LHS.getNode()) {
10158 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10159 // instruction. Since the shift amount is in-range-or-undefined, we know
10160 // that doing a bittest on the i32 value is ok. We extend to i32 because
10161 // the encoding for the i16 version is larger than the i32 version.
10162 // Also promote i16 to i32 for performance / code size reason.
10163 if (LHS.getValueType() == MVT::i8 ||
10164 LHS.getValueType() == MVT::i16)
10165 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10167 // If the operand types disagree, extend the shift amount to match. Since
10168 // BT ignores high bits (like shifts) we can use anyextend.
10169 if (LHS.getValueType() != RHS.getValueType())
10170 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10172 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10173 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10174 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10175 DAG.getConstant(Cond, MVT::i8), BT);
10181 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10183 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10188 // SSE Condition code mapping:
10197 switch (SetCCOpcode) {
10198 default: llvm_unreachable("Unexpected SETCC condition");
10200 case ISD::SETEQ: SSECC = 0; break;
10202 case ISD::SETGT: Swap = true; // Fallthrough
10204 case ISD::SETOLT: SSECC = 1; break;
10206 case ISD::SETGE: Swap = true; // Fallthrough
10208 case ISD::SETOLE: SSECC = 2; break;
10209 case ISD::SETUO: SSECC = 3; break;
10211 case ISD::SETNE: SSECC = 4; break;
10212 case ISD::SETULE: Swap = true; // Fallthrough
10213 case ISD::SETUGE: SSECC = 5; break;
10214 case ISD::SETULT: Swap = true; // Fallthrough
10215 case ISD::SETUGT: SSECC = 6; break;
10216 case ISD::SETO: SSECC = 7; break;
10218 case ISD::SETONE: SSECC = 8; break;
10221 std::swap(Op0, Op1);
10226 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10227 // ones, and then concatenate the result back.
10228 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10229 MVT VT = Op.getSimpleValueType();
10231 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10232 "Unsupported value type for operation");
10234 unsigned NumElems = VT.getVectorNumElements();
10236 SDValue CC = Op.getOperand(2);
10238 // Extract the LHS vectors
10239 SDValue LHS = Op.getOperand(0);
10240 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10241 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10243 // Extract the RHS vectors
10244 SDValue RHS = Op.getOperand(1);
10245 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10246 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10248 // Issue the operation on the smaller types and concatenate the result back
10249 MVT EltVT = VT.getVectorElementType();
10250 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10251 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10252 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10253 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10256 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10257 const X86Subtarget *Subtarget) {
10258 SDValue Op0 = Op.getOperand(0);
10259 SDValue Op1 = Op.getOperand(1);
10260 SDValue CC = Op.getOperand(2);
10261 MVT VT = Op.getSimpleValueType();
10264 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10265 Op.getValueType().getScalarType() == MVT::i1 &&
10266 "Cannot set masked compare for this operation");
10268 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10270 bool Unsigned = false;
10273 switch (SetCCOpcode) {
10274 default: llvm_unreachable("Unexpected SETCC condition");
10275 case ISD::SETNE: SSECC = 4; break;
10276 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10277 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10278 case ISD::SETLT: Swap = true; //fall-through
10279 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10280 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10281 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10282 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10283 case ISD::SETULE: Unsigned = true; //fall-through
10284 case ISD::SETLE: SSECC = 2; break;
10288 std::swap(Op0, Op1);
10290 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10291 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10292 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10293 DAG.getConstant(SSECC, MVT::i8));
10296 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10297 /// operand \p Op1. If non-trivial (for example because it's not constant)
10298 /// return an empty value.
10299 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10301 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10305 MVT VT = Op1.getSimpleValueType();
10306 MVT EVT = VT.getVectorElementType();
10307 unsigned n = VT.getVectorNumElements();
10308 SmallVector<SDValue, 8> ULTOp1;
10310 for (unsigned i = 0; i < n; ++i) {
10311 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10312 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10315 // Avoid underflow.
10316 APInt Val = Elt->getAPIntValue();
10320 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10323 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10326 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10327 SelectionDAG &DAG) {
10328 SDValue Op0 = Op.getOperand(0);
10329 SDValue Op1 = Op.getOperand(1);
10330 SDValue CC = Op.getOperand(2);
10331 MVT VT = Op.getSimpleValueType();
10332 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10333 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10338 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10339 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10342 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10343 unsigned Opc = X86ISD::CMPP;
10344 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10345 assert(VT.getVectorNumElements() <= 16);
10346 Opc = X86ISD::CMPM;
10348 // In the two special cases we can't handle, emit two comparisons.
10351 unsigned CombineOpc;
10352 if (SetCCOpcode == ISD::SETUEQ) {
10353 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10355 assert(SetCCOpcode == ISD::SETONE);
10356 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10359 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10360 DAG.getConstant(CC0, MVT::i8));
10361 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10362 DAG.getConstant(CC1, MVT::i8));
10363 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10365 // Handle all other FP comparisons here.
10366 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10367 DAG.getConstant(SSECC, MVT::i8));
10370 // Break 256-bit integer vector compare into smaller ones.
10371 if (VT.is256BitVector() && !Subtarget->hasInt256())
10372 return Lower256IntVSETCC(Op, DAG);
10374 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10375 EVT OpVT = Op1.getValueType();
10376 if (Subtarget->hasAVX512()) {
10377 if (Op1.getValueType().is512BitVector() ||
10378 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10379 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10381 // In AVX-512 architecture setcc returns mask with i1 elements,
10382 // But there is no compare instruction for i8 and i16 elements.
10383 // We are not talking about 512-bit operands in this case, these
10384 // types are illegal.
10386 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10387 OpVT.getVectorElementType().getSizeInBits() >= 8))
10388 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10389 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10392 // We are handling one of the integer comparisons here. Since SSE only has
10393 // GT and EQ comparisons for integer, swapping operands and multiple
10394 // operations may be required for some comparisons.
10396 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10397 bool Subus = false;
10399 switch (SetCCOpcode) {
10400 default: llvm_unreachable("Unexpected SETCC condition");
10401 case ISD::SETNE: Invert = true;
10402 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10403 case ISD::SETLT: Swap = true;
10404 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10405 case ISD::SETGE: Swap = true;
10406 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10407 Invert = true; break;
10408 case ISD::SETULT: Swap = true;
10409 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10410 FlipSigns = true; break;
10411 case ISD::SETUGE: Swap = true;
10412 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10413 FlipSigns = true; Invert = true; break;
10416 // Special case: Use min/max operations for SETULE/SETUGE
10417 MVT VET = VT.getVectorElementType();
10419 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10420 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10423 switch (SetCCOpcode) {
10425 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10426 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10429 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10432 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10433 if (!MinMax && hasSubus) {
10434 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10436 // t = psubus Op0, Op1
10437 // pcmpeq t, <0..0>
10438 switch (SetCCOpcode) {
10440 case ISD::SETULT: {
10441 // If the comparison is against a constant we can turn this into a
10442 // setule. With psubus, setule does not require a swap. This is
10443 // beneficial because the constant in the register is no longer
10444 // destructed as the destination so it can be hoisted out of a loop.
10445 // Only do this pre-AVX since vpcmp* is no longer destructive.
10446 if (Subtarget->hasAVX())
10448 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10449 if (ULEOp1.getNode()) {
10451 Subus = true; Invert = false; Swap = false;
10455 // Psubus is better than flip-sign because it requires no inversion.
10456 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10457 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10461 Opc = X86ISD::SUBUS;
10467 std::swap(Op0, Op1);
10469 // Check that the operation in question is available (most are plain SSE2,
10470 // but PCMPGTQ and PCMPEQQ have different requirements).
10471 if (VT == MVT::v2i64) {
10472 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10473 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10475 // First cast everything to the right type.
10476 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10477 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10479 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10480 // bits of the inputs before performing those operations. The lower
10481 // compare is always unsigned.
10484 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10486 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10487 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10488 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10489 Sign, Zero, Sign, Zero);
10491 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10492 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10494 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10495 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10496 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10498 // Create masks for only the low parts/high parts of the 64 bit integers.
10499 static const int MaskHi[] = { 1, 1, 3, 3 };
10500 static const int MaskLo[] = { 0, 0, 2, 2 };
10501 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10502 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10503 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10505 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10506 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10509 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10511 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10514 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10515 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10516 // pcmpeqd + pshufd + pand.
10517 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10519 // First cast everything to the right type.
10520 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10521 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10524 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10526 // Make sure the lower and upper halves are both all-ones.
10527 static const int Mask[] = { 1, 0, 3, 2 };
10528 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10529 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10532 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10534 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10538 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10539 // bits of the inputs before performing those operations.
10541 EVT EltVT = VT.getVectorElementType();
10542 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10543 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10544 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10547 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10549 // If the logical-not of the result is required, perform that now.
10551 Result = DAG.getNOT(dl, Result, VT);
10554 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10557 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10558 getZeroVector(VT, Subtarget, DAG, dl));
10563 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10565 MVT VT = Op.getSimpleValueType();
10567 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10569 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10570 && "SetCC type must be 8-bit or 1-bit integer");
10571 SDValue Op0 = Op.getOperand(0);
10572 SDValue Op1 = Op.getOperand(1);
10574 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10576 // Optimize to BT if possible.
10577 // Lower (X & (1 << N)) == 0 to BT(X, N).
10578 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10579 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10580 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10581 Op1.getOpcode() == ISD::Constant &&
10582 cast<ConstantSDNode>(Op1)->isNullValue() &&
10583 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10584 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10585 if (NewSetCC.getNode())
10589 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10591 if (Op1.getOpcode() == ISD::Constant &&
10592 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10593 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10594 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10596 // If the input is a setcc, then reuse the input setcc or use a new one with
10597 // the inverted condition.
10598 if (Op0.getOpcode() == X86ISD::SETCC) {
10599 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10600 bool Invert = (CC == ISD::SETNE) ^
10601 cast<ConstantSDNode>(Op1)->isNullValue();
10605 CCode = X86::GetOppositeBranchCondition(CCode);
10606 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10607 DAG.getConstant(CCode, MVT::i8),
10608 Op0.getOperand(1));
10610 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10614 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10615 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10616 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10618 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10619 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10622 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10623 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10624 if (X86CC == X86::COND_INVALID)
10627 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10628 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10629 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10630 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10632 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10636 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10637 static bool isX86LogicalCmp(SDValue Op) {
10638 unsigned Opc = Op.getNode()->getOpcode();
10639 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10640 Opc == X86ISD::SAHF)
10642 if (Op.getResNo() == 1 &&
10643 (Opc == X86ISD::ADD ||
10644 Opc == X86ISD::SUB ||
10645 Opc == X86ISD::ADC ||
10646 Opc == X86ISD::SBB ||
10647 Opc == X86ISD::SMUL ||
10648 Opc == X86ISD::UMUL ||
10649 Opc == X86ISD::INC ||
10650 Opc == X86ISD::DEC ||
10651 Opc == X86ISD::OR ||
10652 Opc == X86ISD::XOR ||
10653 Opc == X86ISD::AND))
10656 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10662 static bool isZero(SDValue V) {
10663 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10664 return C && C->isNullValue();
10667 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10668 if (V.getOpcode() != ISD::TRUNCATE)
10671 SDValue VOp0 = V.getOperand(0);
10672 unsigned InBits = VOp0.getValueSizeInBits();
10673 unsigned Bits = V.getValueSizeInBits();
10674 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10677 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10678 bool addTest = true;
10679 SDValue Cond = Op.getOperand(0);
10680 SDValue Op1 = Op.getOperand(1);
10681 SDValue Op2 = Op.getOperand(2);
10683 EVT VT = Op1.getValueType();
10686 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10687 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10688 // sequence later on.
10689 if (Cond.getOpcode() == ISD::SETCC &&
10690 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10691 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10692 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10693 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10694 int SSECC = translateX86FSETCC(
10695 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10698 if (Subtarget->hasAVX512()) {
10699 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10700 DAG.getConstant(SSECC, MVT::i8));
10701 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10703 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10704 DAG.getConstant(SSECC, MVT::i8));
10705 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10706 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10707 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10711 if (Cond.getOpcode() == ISD::SETCC) {
10712 SDValue NewCond = LowerSETCC(Cond, DAG);
10713 if (NewCond.getNode())
10717 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10718 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10719 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10720 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10721 if (Cond.getOpcode() == X86ISD::SETCC &&
10722 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10723 isZero(Cond.getOperand(1).getOperand(1))) {
10724 SDValue Cmp = Cond.getOperand(1);
10726 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10728 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10729 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10730 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10732 SDValue CmpOp0 = Cmp.getOperand(0);
10733 // Apply further optimizations for special cases
10734 // (select (x != 0), -1, 0) -> neg & sbb
10735 // (select (x == 0), 0, -1) -> neg & sbb
10736 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10737 if (YC->isNullValue() &&
10738 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10739 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10740 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10741 DAG.getConstant(0, CmpOp0.getValueType()),
10743 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10744 DAG.getConstant(X86::COND_B, MVT::i8),
10745 SDValue(Neg.getNode(), 1));
10749 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10750 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10751 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10753 SDValue Res = // Res = 0 or -1.
10754 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10755 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10757 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10758 Res = DAG.getNOT(DL, Res, Res.getValueType());
10760 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10761 if (!N2C || !N2C->isNullValue())
10762 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10767 // Look past (and (setcc_carry (cmp ...)), 1).
10768 if (Cond.getOpcode() == ISD::AND &&
10769 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10770 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10771 if (C && C->getAPIntValue() == 1)
10772 Cond = Cond.getOperand(0);
10775 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10776 // setting operand in place of the X86ISD::SETCC.
10777 unsigned CondOpcode = Cond.getOpcode();
10778 if (CondOpcode == X86ISD::SETCC ||
10779 CondOpcode == X86ISD::SETCC_CARRY) {
10780 CC = Cond.getOperand(0);
10782 SDValue Cmp = Cond.getOperand(1);
10783 unsigned Opc = Cmp.getOpcode();
10784 MVT VT = Op.getSimpleValueType();
10786 bool IllegalFPCMov = false;
10787 if (VT.isFloatingPoint() && !VT.isVector() &&
10788 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10789 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10791 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10792 Opc == X86ISD::BT) { // FIXME
10796 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10797 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10798 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10799 Cond.getOperand(0).getValueType() != MVT::i8)) {
10800 SDValue LHS = Cond.getOperand(0);
10801 SDValue RHS = Cond.getOperand(1);
10802 unsigned X86Opcode;
10805 switch (CondOpcode) {
10806 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10807 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10808 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10809 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10810 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10811 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10812 default: llvm_unreachable("unexpected overflowing operator");
10814 if (CondOpcode == ISD::UMULO)
10815 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10818 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10820 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10822 if (CondOpcode == ISD::UMULO)
10823 Cond = X86Op.getValue(2);
10825 Cond = X86Op.getValue(1);
10827 CC = DAG.getConstant(X86Cond, MVT::i8);
10832 // Look pass the truncate if the high bits are known zero.
10833 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10834 Cond = Cond.getOperand(0);
10836 // We know the result of AND is compared against zero. Try to match
10838 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10839 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10840 if (NewSetCC.getNode()) {
10841 CC = NewSetCC.getOperand(0);
10842 Cond = NewSetCC.getOperand(1);
10849 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10850 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10853 // a < b ? -1 : 0 -> RES = ~setcc_carry
10854 // a < b ? 0 : -1 -> RES = setcc_carry
10855 // a >= b ? -1 : 0 -> RES = setcc_carry
10856 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10857 if (Cond.getOpcode() == X86ISD::SUB) {
10858 Cond = ConvertCmpIfNecessary(Cond, DAG);
10859 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10861 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10862 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10863 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10864 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10865 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10866 return DAG.getNOT(DL, Res, Res.getValueType());
10871 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10872 // widen the cmov and push the truncate through. This avoids introducing a new
10873 // branch during isel and doesn't add any extensions.
10874 if (Op.getValueType() == MVT::i8 &&
10875 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10876 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10877 if (T1.getValueType() == T2.getValueType() &&
10878 // Blacklist CopyFromReg to avoid partial register stalls.
10879 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10880 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10881 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10882 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10886 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10887 // condition is true.
10888 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10889 SDValue Ops[] = { Op2, Op1, CC, Cond };
10890 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10893 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10894 MVT VT = Op->getSimpleValueType(0);
10895 SDValue In = Op->getOperand(0);
10896 MVT InVT = In.getSimpleValueType();
10899 unsigned int NumElts = VT.getVectorNumElements();
10900 if (NumElts != 8 && NumElts != 16)
10903 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10904 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10906 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10907 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10909 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10910 Constant *C = ConstantInt::get(*DAG.getContext(),
10911 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10913 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10914 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10915 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10916 MachinePointerInfo::getConstantPool(),
10917 false, false, false, Alignment);
10918 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10919 if (VT.is512BitVector())
10921 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10924 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10925 SelectionDAG &DAG) {
10926 MVT VT = Op->getSimpleValueType(0);
10927 SDValue In = Op->getOperand(0);
10928 MVT InVT = In.getSimpleValueType();
10931 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10932 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10934 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10935 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10936 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10939 if (Subtarget->hasInt256())
10940 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10942 // Optimize vectors in AVX mode
10943 // Sign extend v8i16 to v8i32 and
10946 // Divide input vector into two parts
10947 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10948 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10949 // concat the vectors to original VT
10951 unsigned NumElems = InVT.getVectorNumElements();
10952 SDValue Undef = DAG.getUNDEF(InVT);
10954 SmallVector<int,8> ShufMask1(NumElems, -1);
10955 for (unsigned i = 0; i != NumElems/2; ++i)
10958 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10960 SmallVector<int,8> ShufMask2(NumElems, -1);
10961 for (unsigned i = 0; i != NumElems/2; ++i)
10962 ShufMask2[i] = i + NumElems/2;
10964 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10966 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10967 VT.getVectorNumElements()/2);
10969 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10970 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10972 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10975 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10976 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10977 // from the AND / OR.
10978 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10979 Opc = Op.getOpcode();
10980 if (Opc != ISD::OR && Opc != ISD::AND)
10982 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10983 Op.getOperand(0).hasOneUse() &&
10984 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10985 Op.getOperand(1).hasOneUse());
10988 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10989 // 1 and that the SETCC node has a single use.
10990 static bool isXor1OfSetCC(SDValue Op) {
10991 if (Op.getOpcode() != ISD::XOR)
10993 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10994 if (N1C && N1C->getAPIntValue() == 1) {
10995 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10996 Op.getOperand(0).hasOneUse();
11001 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11002 bool addTest = true;
11003 SDValue Chain = Op.getOperand(0);
11004 SDValue Cond = Op.getOperand(1);
11005 SDValue Dest = Op.getOperand(2);
11008 bool Inverted = false;
11010 if (Cond.getOpcode() == ISD::SETCC) {
11011 // Check for setcc([su]{add,sub,mul}o == 0).
11012 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11013 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11014 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11015 Cond.getOperand(0).getResNo() == 1 &&
11016 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11017 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11018 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11019 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11020 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11021 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11023 Cond = Cond.getOperand(0);
11025 SDValue NewCond = LowerSETCC(Cond, DAG);
11026 if (NewCond.getNode())
11031 // FIXME: LowerXALUO doesn't handle these!!
11032 else if (Cond.getOpcode() == X86ISD::ADD ||
11033 Cond.getOpcode() == X86ISD::SUB ||
11034 Cond.getOpcode() == X86ISD::SMUL ||
11035 Cond.getOpcode() == X86ISD::UMUL)
11036 Cond = LowerXALUO(Cond, DAG);
11039 // Look pass (and (setcc_carry (cmp ...)), 1).
11040 if (Cond.getOpcode() == ISD::AND &&
11041 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11042 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11043 if (C && C->getAPIntValue() == 1)
11044 Cond = Cond.getOperand(0);
11047 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11048 // setting operand in place of the X86ISD::SETCC.
11049 unsigned CondOpcode = Cond.getOpcode();
11050 if (CondOpcode == X86ISD::SETCC ||
11051 CondOpcode == X86ISD::SETCC_CARRY) {
11052 CC = Cond.getOperand(0);
11054 SDValue Cmp = Cond.getOperand(1);
11055 unsigned Opc = Cmp.getOpcode();
11056 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11057 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11061 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11065 // These can only come from an arithmetic instruction with overflow,
11066 // e.g. SADDO, UADDO.
11067 Cond = Cond.getNode()->getOperand(1);
11073 CondOpcode = Cond.getOpcode();
11074 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11075 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11076 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11077 Cond.getOperand(0).getValueType() != MVT::i8)) {
11078 SDValue LHS = Cond.getOperand(0);
11079 SDValue RHS = Cond.getOperand(1);
11080 unsigned X86Opcode;
11083 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11084 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11086 switch (CondOpcode) {
11087 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11089 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11091 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11094 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11095 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11097 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11099 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11102 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11103 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11104 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11105 default: llvm_unreachable("unexpected overflowing operator");
11108 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11109 if (CondOpcode == ISD::UMULO)
11110 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11113 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11115 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11117 if (CondOpcode == ISD::UMULO)
11118 Cond = X86Op.getValue(2);
11120 Cond = X86Op.getValue(1);
11122 CC = DAG.getConstant(X86Cond, MVT::i8);
11126 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11127 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11128 if (CondOpc == ISD::OR) {
11129 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11130 // two branches instead of an explicit OR instruction with a
11132 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11133 isX86LogicalCmp(Cmp)) {
11134 CC = Cond.getOperand(0).getOperand(0);
11135 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11136 Chain, Dest, CC, Cmp);
11137 CC = Cond.getOperand(1).getOperand(0);
11141 } else { // ISD::AND
11142 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11143 // two branches instead of an explicit AND instruction with a
11144 // separate test. However, we only do this if this block doesn't
11145 // have a fall-through edge, because this requires an explicit
11146 // jmp when the condition is false.
11147 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11148 isX86LogicalCmp(Cmp) &&
11149 Op.getNode()->hasOneUse()) {
11150 X86::CondCode CCode =
11151 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11152 CCode = X86::GetOppositeBranchCondition(CCode);
11153 CC = DAG.getConstant(CCode, MVT::i8);
11154 SDNode *User = *Op.getNode()->use_begin();
11155 // Look for an unconditional branch following this conditional branch.
11156 // We need this because we need to reverse the successors in order
11157 // to implement FCMP_OEQ.
11158 if (User->getOpcode() == ISD::BR) {
11159 SDValue FalseBB = User->getOperand(1);
11161 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11162 assert(NewBR == User);
11166 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11167 Chain, Dest, CC, Cmp);
11168 X86::CondCode CCode =
11169 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11170 CCode = X86::GetOppositeBranchCondition(CCode);
11171 CC = DAG.getConstant(CCode, MVT::i8);
11177 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11178 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11179 // It should be transformed during dag combiner except when the condition
11180 // is set by a arithmetics with overflow node.
11181 X86::CondCode CCode =
11182 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11183 CCode = X86::GetOppositeBranchCondition(CCode);
11184 CC = DAG.getConstant(CCode, MVT::i8);
11185 Cond = Cond.getOperand(0).getOperand(1);
11187 } else if (Cond.getOpcode() == ISD::SETCC &&
11188 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11189 // For FCMP_OEQ, we can emit
11190 // two branches instead of an explicit AND instruction with a
11191 // separate test. However, we only do this if this block doesn't
11192 // have a fall-through edge, because this requires an explicit
11193 // jmp when the condition is false.
11194 if (Op.getNode()->hasOneUse()) {
11195 SDNode *User = *Op.getNode()->use_begin();
11196 // Look for an unconditional branch following this conditional branch.
11197 // We need this because we need to reverse the successors in order
11198 // to implement FCMP_OEQ.
11199 if (User->getOpcode() == ISD::BR) {
11200 SDValue FalseBB = User->getOperand(1);
11202 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11203 assert(NewBR == User);
11207 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11208 Cond.getOperand(0), Cond.getOperand(1));
11209 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11210 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11211 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11212 Chain, Dest, CC, Cmp);
11213 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11218 } else if (Cond.getOpcode() == ISD::SETCC &&
11219 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11220 // For FCMP_UNE, we can emit
11221 // two branches instead of an explicit AND instruction with a
11222 // separate test. However, we only do this if this block doesn't
11223 // have a fall-through edge, because this requires an explicit
11224 // jmp when the condition is false.
11225 if (Op.getNode()->hasOneUse()) {
11226 SDNode *User = *Op.getNode()->use_begin();
11227 // Look for an unconditional branch following this conditional branch.
11228 // We need this because we need to reverse the successors in order
11229 // to implement FCMP_UNE.
11230 if (User->getOpcode() == ISD::BR) {
11231 SDValue FalseBB = User->getOperand(1);
11233 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11234 assert(NewBR == User);
11237 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11238 Cond.getOperand(0), Cond.getOperand(1));
11239 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11240 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11241 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11242 Chain, Dest, CC, Cmp);
11243 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11253 // Look pass the truncate if the high bits are known zero.
11254 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11255 Cond = Cond.getOperand(0);
11257 // We know the result of AND is compared against zero. Try to match
11259 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11260 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11261 if (NewSetCC.getNode()) {
11262 CC = NewSetCC.getOperand(0);
11263 Cond = NewSetCC.getOperand(1);
11270 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11271 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11273 Cond = ConvertCmpIfNecessary(Cond, DAG);
11274 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11275 Chain, Dest, CC, Cond);
11278 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11279 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11280 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11281 // that the guard pages used by the OS virtual memory manager are allocated in
11282 // correct sequence.
11284 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11285 SelectionDAG &DAG) const {
11286 MachineFunction &MF = DAG.getMachineFunction();
11287 bool SplitStack = MF.shouldSplitStack();
11288 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11293 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11294 SDNode* Node = Op.getNode();
11296 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11297 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11298 " not tell us which reg is the stack pointer!");
11299 EVT VT = Node->getValueType(0);
11300 SDValue Tmp1 = SDValue(Node, 0);
11301 SDValue Tmp2 = SDValue(Node, 1);
11302 SDValue Tmp3 = Node->getOperand(2);
11303 SDValue Chain = Tmp1.getOperand(0);
11305 // Chain the dynamic stack allocation so that it doesn't modify the stack
11306 // pointer when other instructions are using the stack.
11307 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11310 SDValue Size = Tmp2.getOperand(1);
11311 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11312 Chain = SP.getValue(1);
11313 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11314 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11315 unsigned StackAlign = TFI.getStackAlignment();
11316 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11317 if (Align > StackAlign)
11318 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11319 DAG.getConstant(-(uint64_t)Align, VT));
11320 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11322 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11323 DAG.getIntPtrConstant(0, true), SDValue(),
11326 SDValue Ops[2] = { Tmp1, Tmp2 };
11327 return DAG.getMergeValues(Ops, dl);
11331 SDValue Chain = Op.getOperand(0);
11332 SDValue Size = Op.getOperand(1);
11333 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11334 EVT VT = Op.getNode()->getValueType(0);
11336 bool Is64Bit = Subtarget->is64Bit();
11337 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11340 MachineRegisterInfo &MRI = MF.getRegInfo();
11343 // The 64 bit implementation of segmented stacks needs to clobber both r10
11344 // r11. This makes it impossible to use it along with nested parameters.
11345 const Function *F = MF.getFunction();
11347 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11349 if (I->hasNestAttr())
11350 report_fatal_error("Cannot use segmented stacks with functions that "
11351 "have nested arguments.");
11354 const TargetRegisterClass *AddrRegClass =
11355 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11356 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11357 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11358 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11359 DAG.getRegister(Vreg, SPTy));
11360 SDValue Ops1[2] = { Value, Chain };
11361 return DAG.getMergeValues(Ops1, dl);
11364 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11366 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11367 Flag = Chain.getValue(1);
11368 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11370 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11372 const X86RegisterInfo *RegInfo =
11373 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11374 unsigned SPReg = RegInfo->getStackRegister();
11375 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11376 Chain = SP.getValue(1);
11379 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11380 DAG.getConstant(-(uint64_t)Align, VT));
11381 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11384 SDValue Ops1[2] = { SP, Chain };
11385 return DAG.getMergeValues(Ops1, dl);
11389 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11390 MachineFunction &MF = DAG.getMachineFunction();
11391 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11393 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11396 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11397 // vastart just stores the address of the VarArgsFrameIndex slot into the
11398 // memory location argument.
11399 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11401 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11402 MachinePointerInfo(SV), false, false, 0);
11406 // gp_offset (0 - 6 * 8)
11407 // fp_offset (48 - 48 + 8 * 16)
11408 // overflow_arg_area (point to parameters coming in memory).
11410 SmallVector<SDValue, 8> MemOps;
11411 SDValue FIN = Op.getOperand(1);
11413 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11414 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11416 FIN, MachinePointerInfo(SV), false, false, 0);
11417 MemOps.push_back(Store);
11420 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11421 FIN, DAG.getIntPtrConstant(4));
11422 Store = DAG.getStore(Op.getOperand(0), DL,
11423 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11425 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11426 MemOps.push_back(Store);
11428 // Store ptr to overflow_arg_area
11429 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11430 FIN, DAG.getIntPtrConstant(4));
11431 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11433 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11434 MachinePointerInfo(SV, 8),
11436 MemOps.push_back(Store);
11438 // Store ptr to reg_save_area.
11439 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11440 FIN, DAG.getIntPtrConstant(8));
11441 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11443 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11444 MachinePointerInfo(SV, 16), false, false, 0);
11445 MemOps.push_back(Store);
11446 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11449 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11450 assert(Subtarget->is64Bit() &&
11451 "LowerVAARG only handles 64-bit va_arg!");
11452 assert((Subtarget->isTargetLinux() ||
11453 Subtarget->isTargetDarwin()) &&
11454 "Unhandled target in LowerVAARG");
11455 assert(Op.getNode()->getNumOperands() == 4);
11456 SDValue Chain = Op.getOperand(0);
11457 SDValue SrcPtr = Op.getOperand(1);
11458 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11459 unsigned Align = Op.getConstantOperandVal(3);
11462 EVT ArgVT = Op.getNode()->getValueType(0);
11463 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11464 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11467 // Decide which area this value should be read from.
11468 // TODO: Implement the AMD64 ABI in its entirety. This simple
11469 // selection mechanism works only for the basic types.
11470 if (ArgVT == MVT::f80) {
11471 llvm_unreachable("va_arg for f80 not yet implemented");
11472 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11473 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11474 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11475 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11477 llvm_unreachable("Unhandled argument type in LowerVAARG");
11480 if (ArgMode == 2) {
11481 // Sanity Check: Make sure using fp_offset makes sense.
11482 assert(!getTargetMachine().Options.UseSoftFloat &&
11483 !(DAG.getMachineFunction()
11484 .getFunction()->getAttributes()
11485 .hasAttribute(AttributeSet::FunctionIndex,
11486 Attribute::NoImplicitFloat)) &&
11487 Subtarget->hasSSE1());
11490 // Insert VAARG_64 node into the DAG
11491 // VAARG_64 returns two values: Variable Argument Address, Chain
11492 SmallVector<SDValue, 11> InstOps;
11493 InstOps.push_back(Chain);
11494 InstOps.push_back(SrcPtr);
11495 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11496 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11497 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11498 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11499 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11500 VTs, InstOps, MVT::i64,
11501 MachinePointerInfo(SV),
11503 /*Volatile=*/false,
11505 /*WriteMem=*/true);
11506 Chain = VAARG.getValue(1);
11508 // Load the next argument and return it
11509 return DAG.getLoad(ArgVT, dl,
11512 MachinePointerInfo(),
11513 false, false, false, 0);
11516 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11517 SelectionDAG &DAG) {
11518 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11519 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11520 SDValue Chain = Op.getOperand(0);
11521 SDValue DstPtr = Op.getOperand(1);
11522 SDValue SrcPtr = Op.getOperand(2);
11523 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11524 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11527 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11528 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11530 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11533 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11534 // amount is a constant. Takes immediate version of shift as input.
11535 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11536 SDValue SrcOp, uint64_t ShiftAmt,
11537 SelectionDAG &DAG) {
11538 MVT ElementType = VT.getVectorElementType();
11540 // Check for ShiftAmt >= element width
11541 if (ShiftAmt >= ElementType.getSizeInBits()) {
11542 if (Opc == X86ISD::VSRAI)
11543 ShiftAmt = ElementType.getSizeInBits() - 1;
11545 return DAG.getConstant(0, VT);
11548 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11549 && "Unknown target vector shift-by-constant node");
11551 // Fold this packed vector shift into a build vector if SrcOp is a
11552 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11553 if (VT == SrcOp.getSimpleValueType() &&
11554 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11555 SmallVector<SDValue, 8> Elts;
11556 unsigned NumElts = SrcOp->getNumOperands();
11557 ConstantSDNode *ND;
11560 default: llvm_unreachable(nullptr);
11561 case X86ISD::VSHLI:
11562 for (unsigned i=0; i!=NumElts; ++i) {
11563 SDValue CurrentOp = SrcOp->getOperand(i);
11564 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11565 Elts.push_back(CurrentOp);
11568 ND = cast<ConstantSDNode>(CurrentOp);
11569 const APInt &C = ND->getAPIntValue();
11570 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11573 case X86ISD::VSRLI:
11574 for (unsigned i=0; i!=NumElts; ++i) {
11575 SDValue CurrentOp = SrcOp->getOperand(i);
11576 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11577 Elts.push_back(CurrentOp);
11580 ND = cast<ConstantSDNode>(CurrentOp);
11581 const APInt &C = ND->getAPIntValue();
11582 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11585 case X86ISD::VSRAI:
11586 for (unsigned i=0; i!=NumElts; ++i) {
11587 SDValue CurrentOp = SrcOp->getOperand(i);
11588 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11589 Elts.push_back(CurrentOp);
11592 ND = cast<ConstantSDNode>(CurrentOp);
11593 const APInt &C = ND->getAPIntValue();
11594 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11599 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11602 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11605 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11606 // may or may not be a constant. Takes immediate version of shift as input.
11607 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11608 SDValue SrcOp, SDValue ShAmt,
11609 SelectionDAG &DAG) {
11610 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11612 // Catch shift-by-constant.
11613 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11614 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11615 CShAmt->getZExtValue(), DAG);
11617 // Change opcode to non-immediate version
11619 default: llvm_unreachable("Unknown target vector shift node");
11620 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11621 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11622 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11625 // Need to build a vector containing shift amount
11626 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11629 ShOps[1] = DAG.getConstant(0, MVT::i32);
11630 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11631 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11633 // The return type has to be a 128-bit type with the same element
11634 // type as the input type.
11635 MVT EltVT = VT.getVectorElementType();
11636 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11638 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11639 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11642 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11644 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11646 default: return SDValue(); // Don't custom lower most intrinsics.
11647 // Comparison intrinsics.
11648 case Intrinsic::x86_sse_comieq_ss:
11649 case Intrinsic::x86_sse_comilt_ss:
11650 case Intrinsic::x86_sse_comile_ss:
11651 case Intrinsic::x86_sse_comigt_ss:
11652 case Intrinsic::x86_sse_comige_ss:
11653 case Intrinsic::x86_sse_comineq_ss:
11654 case Intrinsic::x86_sse_ucomieq_ss:
11655 case Intrinsic::x86_sse_ucomilt_ss:
11656 case Intrinsic::x86_sse_ucomile_ss:
11657 case Intrinsic::x86_sse_ucomigt_ss:
11658 case Intrinsic::x86_sse_ucomige_ss:
11659 case Intrinsic::x86_sse_ucomineq_ss:
11660 case Intrinsic::x86_sse2_comieq_sd:
11661 case Intrinsic::x86_sse2_comilt_sd:
11662 case Intrinsic::x86_sse2_comile_sd:
11663 case Intrinsic::x86_sse2_comigt_sd:
11664 case Intrinsic::x86_sse2_comige_sd:
11665 case Intrinsic::x86_sse2_comineq_sd:
11666 case Intrinsic::x86_sse2_ucomieq_sd:
11667 case Intrinsic::x86_sse2_ucomilt_sd:
11668 case Intrinsic::x86_sse2_ucomile_sd:
11669 case Intrinsic::x86_sse2_ucomigt_sd:
11670 case Intrinsic::x86_sse2_ucomige_sd:
11671 case Intrinsic::x86_sse2_ucomineq_sd: {
11675 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11676 case Intrinsic::x86_sse_comieq_ss:
11677 case Intrinsic::x86_sse2_comieq_sd:
11678 Opc = X86ISD::COMI;
11681 case Intrinsic::x86_sse_comilt_ss:
11682 case Intrinsic::x86_sse2_comilt_sd:
11683 Opc = X86ISD::COMI;
11686 case Intrinsic::x86_sse_comile_ss:
11687 case Intrinsic::x86_sse2_comile_sd:
11688 Opc = X86ISD::COMI;
11691 case Intrinsic::x86_sse_comigt_ss:
11692 case Intrinsic::x86_sse2_comigt_sd:
11693 Opc = X86ISD::COMI;
11696 case Intrinsic::x86_sse_comige_ss:
11697 case Intrinsic::x86_sse2_comige_sd:
11698 Opc = X86ISD::COMI;
11701 case Intrinsic::x86_sse_comineq_ss:
11702 case Intrinsic::x86_sse2_comineq_sd:
11703 Opc = X86ISD::COMI;
11706 case Intrinsic::x86_sse_ucomieq_ss:
11707 case Intrinsic::x86_sse2_ucomieq_sd:
11708 Opc = X86ISD::UCOMI;
11711 case Intrinsic::x86_sse_ucomilt_ss:
11712 case Intrinsic::x86_sse2_ucomilt_sd:
11713 Opc = X86ISD::UCOMI;
11716 case Intrinsic::x86_sse_ucomile_ss:
11717 case Intrinsic::x86_sse2_ucomile_sd:
11718 Opc = X86ISD::UCOMI;
11721 case Intrinsic::x86_sse_ucomigt_ss:
11722 case Intrinsic::x86_sse2_ucomigt_sd:
11723 Opc = X86ISD::UCOMI;
11726 case Intrinsic::x86_sse_ucomige_ss:
11727 case Intrinsic::x86_sse2_ucomige_sd:
11728 Opc = X86ISD::UCOMI;
11731 case Intrinsic::x86_sse_ucomineq_ss:
11732 case Intrinsic::x86_sse2_ucomineq_sd:
11733 Opc = X86ISD::UCOMI;
11738 SDValue LHS = Op.getOperand(1);
11739 SDValue RHS = Op.getOperand(2);
11740 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11741 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11742 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11743 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11744 DAG.getConstant(X86CC, MVT::i8), Cond);
11745 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11748 // Arithmetic intrinsics.
11749 case Intrinsic::x86_sse2_pmulu_dq:
11750 case Intrinsic::x86_avx2_pmulu_dq:
11751 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11752 Op.getOperand(1), Op.getOperand(2));
11754 case Intrinsic::x86_sse41_pmuldq:
11755 case Intrinsic::x86_avx2_pmul_dq:
11756 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11757 Op.getOperand(1), Op.getOperand(2));
11759 case Intrinsic::x86_sse2_pmulhu_w:
11760 case Intrinsic::x86_avx2_pmulhu_w:
11761 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11762 Op.getOperand(1), Op.getOperand(2));
11764 case Intrinsic::x86_sse2_pmulh_w:
11765 case Intrinsic::x86_avx2_pmulh_w:
11766 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11767 Op.getOperand(1), Op.getOperand(2));
11769 // SSE2/AVX2 sub with unsigned saturation intrinsics
11770 case Intrinsic::x86_sse2_psubus_b:
11771 case Intrinsic::x86_sse2_psubus_w:
11772 case Intrinsic::x86_avx2_psubus_b:
11773 case Intrinsic::x86_avx2_psubus_w:
11774 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11775 Op.getOperand(1), Op.getOperand(2));
11777 // SSE3/AVX horizontal add/sub intrinsics
11778 case Intrinsic::x86_sse3_hadd_ps:
11779 case Intrinsic::x86_sse3_hadd_pd:
11780 case Intrinsic::x86_avx_hadd_ps_256:
11781 case Intrinsic::x86_avx_hadd_pd_256:
11782 case Intrinsic::x86_sse3_hsub_ps:
11783 case Intrinsic::x86_sse3_hsub_pd:
11784 case Intrinsic::x86_avx_hsub_ps_256:
11785 case Intrinsic::x86_avx_hsub_pd_256:
11786 case Intrinsic::x86_ssse3_phadd_w_128:
11787 case Intrinsic::x86_ssse3_phadd_d_128:
11788 case Intrinsic::x86_avx2_phadd_w:
11789 case Intrinsic::x86_avx2_phadd_d:
11790 case Intrinsic::x86_ssse3_phsub_w_128:
11791 case Intrinsic::x86_ssse3_phsub_d_128:
11792 case Intrinsic::x86_avx2_phsub_w:
11793 case Intrinsic::x86_avx2_phsub_d: {
11796 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11797 case Intrinsic::x86_sse3_hadd_ps:
11798 case Intrinsic::x86_sse3_hadd_pd:
11799 case Intrinsic::x86_avx_hadd_ps_256:
11800 case Intrinsic::x86_avx_hadd_pd_256:
11801 Opcode = X86ISD::FHADD;
11803 case Intrinsic::x86_sse3_hsub_ps:
11804 case Intrinsic::x86_sse3_hsub_pd:
11805 case Intrinsic::x86_avx_hsub_ps_256:
11806 case Intrinsic::x86_avx_hsub_pd_256:
11807 Opcode = X86ISD::FHSUB;
11809 case Intrinsic::x86_ssse3_phadd_w_128:
11810 case Intrinsic::x86_ssse3_phadd_d_128:
11811 case Intrinsic::x86_avx2_phadd_w:
11812 case Intrinsic::x86_avx2_phadd_d:
11813 Opcode = X86ISD::HADD;
11815 case Intrinsic::x86_ssse3_phsub_w_128:
11816 case Intrinsic::x86_ssse3_phsub_d_128:
11817 case Intrinsic::x86_avx2_phsub_w:
11818 case Intrinsic::x86_avx2_phsub_d:
11819 Opcode = X86ISD::HSUB;
11822 return DAG.getNode(Opcode, dl, Op.getValueType(),
11823 Op.getOperand(1), Op.getOperand(2));
11826 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11827 case Intrinsic::x86_sse2_pmaxu_b:
11828 case Intrinsic::x86_sse41_pmaxuw:
11829 case Intrinsic::x86_sse41_pmaxud:
11830 case Intrinsic::x86_avx2_pmaxu_b:
11831 case Intrinsic::x86_avx2_pmaxu_w:
11832 case Intrinsic::x86_avx2_pmaxu_d:
11833 case Intrinsic::x86_sse2_pminu_b:
11834 case Intrinsic::x86_sse41_pminuw:
11835 case Intrinsic::x86_sse41_pminud:
11836 case Intrinsic::x86_avx2_pminu_b:
11837 case Intrinsic::x86_avx2_pminu_w:
11838 case Intrinsic::x86_avx2_pminu_d:
11839 case Intrinsic::x86_sse41_pmaxsb:
11840 case Intrinsic::x86_sse2_pmaxs_w:
11841 case Intrinsic::x86_sse41_pmaxsd:
11842 case Intrinsic::x86_avx2_pmaxs_b:
11843 case Intrinsic::x86_avx2_pmaxs_w:
11844 case Intrinsic::x86_avx2_pmaxs_d:
11845 case Intrinsic::x86_sse41_pminsb:
11846 case Intrinsic::x86_sse2_pmins_w:
11847 case Intrinsic::x86_sse41_pminsd:
11848 case Intrinsic::x86_avx2_pmins_b:
11849 case Intrinsic::x86_avx2_pmins_w:
11850 case Intrinsic::x86_avx2_pmins_d: {
11853 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11854 case Intrinsic::x86_sse2_pmaxu_b:
11855 case Intrinsic::x86_sse41_pmaxuw:
11856 case Intrinsic::x86_sse41_pmaxud:
11857 case Intrinsic::x86_avx2_pmaxu_b:
11858 case Intrinsic::x86_avx2_pmaxu_w:
11859 case Intrinsic::x86_avx2_pmaxu_d:
11860 Opcode = X86ISD::UMAX;
11862 case Intrinsic::x86_sse2_pminu_b:
11863 case Intrinsic::x86_sse41_pminuw:
11864 case Intrinsic::x86_sse41_pminud:
11865 case Intrinsic::x86_avx2_pminu_b:
11866 case Intrinsic::x86_avx2_pminu_w:
11867 case Intrinsic::x86_avx2_pminu_d:
11868 Opcode = X86ISD::UMIN;
11870 case Intrinsic::x86_sse41_pmaxsb:
11871 case Intrinsic::x86_sse2_pmaxs_w:
11872 case Intrinsic::x86_sse41_pmaxsd:
11873 case Intrinsic::x86_avx2_pmaxs_b:
11874 case Intrinsic::x86_avx2_pmaxs_w:
11875 case Intrinsic::x86_avx2_pmaxs_d:
11876 Opcode = X86ISD::SMAX;
11878 case Intrinsic::x86_sse41_pminsb:
11879 case Intrinsic::x86_sse2_pmins_w:
11880 case Intrinsic::x86_sse41_pminsd:
11881 case Intrinsic::x86_avx2_pmins_b:
11882 case Intrinsic::x86_avx2_pmins_w:
11883 case Intrinsic::x86_avx2_pmins_d:
11884 Opcode = X86ISD::SMIN;
11887 return DAG.getNode(Opcode, dl, Op.getValueType(),
11888 Op.getOperand(1), Op.getOperand(2));
11891 // SSE/SSE2/AVX floating point max/min intrinsics.
11892 case Intrinsic::x86_sse_max_ps:
11893 case Intrinsic::x86_sse2_max_pd:
11894 case Intrinsic::x86_avx_max_ps_256:
11895 case Intrinsic::x86_avx_max_pd_256:
11896 case Intrinsic::x86_sse_min_ps:
11897 case Intrinsic::x86_sse2_min_pd:
11898 case Intrinsic::x86_avx_min_ps_256:
11899 case Intrinsic::x86_avx_min_pd_256: {
11902 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11903 case Intrinsic::x86_sse_max_ps:
11904 case Intrinsic::x86_sse2_max_pd:
11905 case Intrinsic::x86_avx_max_ps_256:
11906 case Intrinsic::x86_avx_max_pd_256:
11907 Opcode = X86ISD::FMAX;
11909 case Intrinsic::x86_sse_min_ps:
11910 case Intrinsic::x86_sse2_min_pd:
11911 case Intrinsic::x86_avx_min_ps_256:
11912 case Intrinsic::x86_avx_min_pd_256:
11913 Opcode = X86ISD::FMIN;
11916 return DAG.getNode(Opcode, dl, Op.getValueType(),
11917 Op.getOperand(1), Op.getOperand(2));
11920 // AVX2 variable shift intrinsics
11921 case Intrinsic::x86_avx2_psllv_d:
11922 case Intrinsic::x86_avx2_psllv_q:
11923 case Intrinsic::x86_avx2_psllv_d_256:
11924 case Intrinsic::x86_avx2_psllv_q_256:
11925 case Intrinsic::x86_avx2_psrlv_d:
11926 case Intrinsic::x86_avx2_psrlv_q:
11927 case Intrinsic::x86_avx2_psrlv_d_256:
11928 case Intrinsic::x86_avx2_psrlv_q_256:
11929 case Intrinsic::x86_avx2_psrav_d:
11930 case Intrinsic::x86_avx2_psrav_d_256: {
11933 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11934 case Intrinsic::x86_avx2_psllv_d:
11935 case Intrinsic::x86_avx2_psllv_q:
11936 case Intrinsic::x86_avx2_psllv_d_256:
11937 case Intrinsic::x86_avx2_psllv_q_256:
11940 case Intrinsic::x86_avx2_psrlv_d:
11941 case Intrinsic::x86_avx2_psrlv_q:
11942 case Intrinsic::x86_avx2_psrlv_d_256:
11943 case Intrinsic::x86_avx2_psrlv_q_256:
11946 case Intrinsic::x86_avx2_psrav_d:
11947 case Intrinsic::x86_avx2_psrav_d_256:
11951 return DAG.getNode(Opcode, dl, Op.getValueType(),
11952 Op.getOperand(1), Op.getOperand(2));
11955 case Intrinsic::x86_ssse3_pshuf_b_128:
11956 case Intrinsic::x86_avx2_pshuf_b:
11957 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11958 Op.getOperand(1), Op.getOperand(2));
11960 case Intrinsic::x86_ssse3_psign_b_128:
11961 case Intrinsic::x86_ssse3_psign_w_128:
11962 case Intrinsic::x86_ssse3_psign_d_128:
11963 case Intrinsic::x86_avx2_psign_b:
11964 case Intrinsic::x86_avx2_psign_w:
11965 case Intrinsic::x86_avx2_psign_d:
11966 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11967 Op.getOperand(1), Op.getOperand(2));
11969 case Intrinsic::x86_sse41_insertps:
11970 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11971 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11973 case Intrinsic::x86_avx_vperm2f128_ps_256:
11974 case Intrinsic::x86_avx_vperm2f128_pd_256:
11975 case Intrinsic::x86_avx_vperm2f128_si_256:
11976 case Intrinsic::x86_avx2_vperm2i128:
11977 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11978 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11980 case Intrinsic::x86_avx2_permd:
11981 case Intrinsic::x86_avx2_permps:
11982 // Operands intentionally swapped. Mask is last operand to intrinsic,
11983 // but second operand for node/instruction.
11984 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11985 Op.getOperand(2), Op.getOperand(1));
11987 case Intrinsic::x86_sse_sqrt_ps:
11988 case Intrinsic::x86_sse2_sqrt_pd:
11989 case Intrinsic::x86_avx_sqrt_ps_256:
11990 case Intrinsic::x86_avx_sqrt_pd_256:
11991 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11993 // ptest and testp intrinsics. The intrinsic these come from are designed to
11994 // return an integer value, not just an instruction so lower it to the ptest
11995 // or testp pattern and a setcc for the result.
11996 case Intrinsic::x86_sse41_ptestz:
11997 case Intrinsic::x86_sse41_ptestc:
11998 case Intrinsic::x86_sse41_ptestnzc:
11999 case Intrinsic::x86_avx_ptestz_256:
12000 case Intrinsic::x86_avx_ptestc_256:
12001 case Intrinsic::x86_avx_ptestnzc_256:
12002 case Intrinsic::x86_avx_vtestz_ps:
12003 case Intrinsic::x86_avx_vtestc_ps:
12004 case Intrinsic::x86_avx_vtestnzc_ps:
12005 case Intrinsic::x86_avx_vtestz_pd:
12006 case Intrinsic::x86_avx_vtestc_pd:
12007 case Intrinsic::x86_avx_vtestnzc_pd:
12008 case Intrinsic::x86_avx_vtestz_ps_256:
12009 case Intrinsic::x86_avx_vtestc_ps_256:
12010 case Intrinsic::x86_avx_vtestnzc_ps_256:
12011 case Intrinsic::x86_avx_vtestz_pd_256:
12012 case Intrinsic::x86_avx_vtestc_pd_256:
12013 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12014 bool IsTestPacked = false;
12017 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12018 case Intrinsic::x86_avx_vtestz_ps:
12019 case Intrinsic::x86_avx_vtestz_pd:
12020 case Intrinsic::x86_avx_vtestz_ps_256:
12021 case Intrinsic::x86_avx_vtestz_pd_256:
12022 IsTestPacked = true; // Fallthrough
12023 case Intrinsic::x86_sse41_ptestz:
12024 case Intrinsic::x86_avx_ptestz_256:
12026 X86CC = X86::COND_E;
12028 case Intrinsic::x86_avx_vtestc_ps:
12029 case Intrinsic::x86_avx_vtestc_pd:
12030 case Intrinsic::x86_avx_vtestc_ps_256:
12031 case Intrinsic::x86_avx_vtestc_pd_256:
12032 IsTestPacked = true; // Fallthrough
12033 case Intrinsic::x86_sse41_ptestc:
12034 case Intrinsic::x86_avx_ptestc_256:
12036 X86CC = X86::COND_B;
12038 case Intrinsic::x86_avx_vtestnzc_ps:
12039 case Intrinsic::x86_avx_vtestnzc_pd:
12040 case Intrinsic::x86_avx_vtestnzc_ps_256:
12041 case Intrinsic::x86_avx_vtestnzc_pd_256:
12042 IsTestPacked = true; // Fallthrough
12043 case Intrinsic::x86_sse41_ptestnzc:
12044 case Intrinsic::x86_avx_ptestnzc_256:
12046 X86CC = X86::COND_A;
12050 SDValue LHS = Op.getOperand(1);
12051 SDValue RHS = Op.getOperand(2);
12052 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12053 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12054 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12055 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12056 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12058 case Intrinsic::x86_avx512_kortestz_w:
12059 case Intrinsic::x86_avx512_kortestc_w: {
12060 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12061 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12062 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12063 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12064 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12065 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12066 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12069 // SSE/AVX shift intrinsics
12070 case Intrinsic::x86_sse2_psll_w:
12071 case Intrinsic::x86_sse2_psll_d:
12072 case Intrinsic::x86_sse2_psll_q:
12073 case Intrinsic::x86_avx2_psll_w:
12074 case Intrinsic::x86_avx2_psll_d:
12075 case Intrinsic::x86_avx2_psll_q:
12076 case Intrinsic::x86_sse2_psrl_w:
12077 case Intrinsic::x86_sse2_psrl_d:
12078 case Intrinsic::x86_sse2_psrl_q:
12079 case Intrinsic::x86_avx2_psrl_w:
12080 case Intrinsic::x86_avx2_psrl_d:
12081 case Intrinsic::x86_avx2_psrl_q:
12082 case Intrinsic::x86_sse2_psra_w:
12083 case Intrinsic::x86_sse2_psra_d:
12084 case Intrinsic::x86_avx2_psra_w:
12085 case Intrinsic::x86_avx2_psra_d: {
12088 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12089 case Intrinsic::x86_sse2_psll_w:
12090 case Intrinsic::x86_sse2_psll_d:
12091 case Intrinsic::x86_sse2_psll_q:
12092 case Intrinsic::x86_avx2_psll_w:
12093 case Intrinsic::x86_avx2_psll_d:
12094 case Intrinsic::x86_avx2_psll_q:
12095 Opcode = X86ISD::VSHL;
12097 case Intrinsic::x86_sse2_psrl_w:
12098 case Intrinsic::x86_sse2_psrl_d:
12099 case Intrinsic::x86_sse2_psrl_q:
12100 case Intrinsic::x86_avx2_psrl_w:
12101 case Intrinsic::x86_avx2_psrl_d:
12102 case Intrinsic::x86_avx2_psrl_q:
12103 Opcode = X86ISD::VSRL;
12105 case Intrinsic::x86_sse2_psra_w:
12106 case Intrinsic::x86_sse2_psra_d:
12107 case Intrinsic::x86_avx2_psra_w:
12108 case Intrinsic::x86_avx2_psra_d:
12109 Opcode = X86ISD::VSRA;
12112 return DAG.getNode(Opcode, dl, Op.getValueType(),
12113 Op.getOperand(1), Op.getOperand(2));
12116 // SSE/AVX immediate shift intrinsics
12117 case Intrinsic::x86_sse2_pslli_w:
12118 case Intrinsic::x86_sse2_pslli_d:
12119 case Intrinsic::x86_sse2_pslli_q:
12120 case Intrinsic::x86_avx2_pslli_w:
12121 case Intrinsic::x86_avx2_pslli_d:
12122 case Intrinsic::x86_avx2_pslli_q:
12123 case Intrinsic::x86_sse2_psrli_w:
12124 case Intrinsic::x86_sse2_psrli_d:
12125 case Intrinsic::x86_sse2_psrli_q:
12126 case Intrinsic::x86_avx2_psrli_w:
12127 case Intrinsic::x86_avx2_psrli_d:
12128 case Intrinsic::x86_avx2_psrli_q:
12129 case Intrinsic::x86_sse2_psrai_w:
12130 case Intrinsic::x86_sse2_psrai_d:
12131 case Intrinsic::x86_avx2_psrai_w:
12132 case Intrinsic::x86_avx2_psrai_d: {
12135 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12136 case Intrinsic::x86_sse2_pslli_w:
12137 case Intrinsic::x86_sse2_pslli_d:
12138 case Intrinsic::x86_sse2_pslli_q:
12139 case Intrinsic::x86_avx2_pslli_w:
12140 case Intrinsic::x86_avx2_pslli_d:
12141 case Intrinsic::x86_avx2_pslli_q:
12142 Opcode = X86ISD::VSHLI;
12144 case Intrinsic::x86_sse2_psrli_w:
12145 case Intrinsic::x86_sse2_psrli_d:
12146 case Intrinsic::x86_sse2_psrli_q:
12147 case Intrinsic::x86_avx2_psrli_w:
12148 case Intrinsic::x86_avx2_psrli_d:
12149 case Intrinsic::x86_avx2_psrli_q:
12150 Opcode = X86ISD::VSRLI;
12152 case Intrinsic::x86_sse2_psrai_w:
12153 case Intrinsic::x86_sse2_psrai_d:
12154 case Intrinsic::x86_avx2_psrai_w:
12155 case Intrinsic::x86_avx2_psrai_d:
12156 Opcode = X86ISD::VSRAI;
12159 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12160 Op.getOperand(1), Op.getOperand(2), DAG);
12163 case Intrinsic::x86_sse42_pcmpistria128:
12164 case Intrinsic::x86_sse42_pcmpestria128:
12165 case Intrinsic::x86_sse42_pcmpistric128:
12166 case Intrinsic::x86_sse42_pcmpestric128:
12167 case Intrinsic::x86_sse42_pcmpistrio128:
12168 case Intrinsic::x86_sse42_pcmpestrio128:
12169 case Intrinsic::x86_sse42_pcmpistris128:
12170 case Intrinsic::x86_sse42_pcmpestris128:
12171 case Intrinsic::x86_sse42_pcmpistriz128:
12172 case Intrinsic::x86_sse42_pcmpestriz128: {
12176 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12177 case Intrinsic::x86_sse42_pcmpistria128:
12178 Opcode = X86ISD::PCMPISTRI;
12179 X86CC = X86::COND_A;
12181 case Intrinsic::x86_sse42_pcmpestria128:
12182 Opcode = X86ISD::PCMPESTRI;
12183 X86CC = X86::COND_A;
12185 case Intrinsic::x86_sse42_pcmpistric128:
12186 Opcode = X86ISD::PCMPISTRI;
12187 X86CC = X86::COND_B;
12189 case Intrinsic::x86_sse42_pcmpestric128:
12190 Opcode = X86ISD::PCMPESTRI;
12191 X86CC = X86::COND_B;
12193 case Intrinsic::x86_sse42_pcmpistrio128:
12194 Opcode = X86ISD::PCMPISTRI;
12195 X86CC = X86::COND_O;
12197 case Intrinsic::x86_sse42_pcmpestrio128:
12198 Opcode = X86ISD::PCMPESTRI;
12199 X86CC = X86::COND_O;
12201 case Intrinsic::x86_sse42_pcmpistris128:
12202 Opcode = X86ISD::PCMPISTRI;
12203 X86CC = X86::COND_S;
12205 case Intrinsic::x86_sse42_pcmpestris128:
12206 Opcode = X86ISD::PCMPESTRI;
12207 X86CC = X86::COND_S;
12209 case Intrinsic::x86_sse42_pcmpistriz128:
12210 Opcode = X86ISD::PCMPISTRI;
12211 X86CC = X86::COND_E;
12213 case Intrinsic::x86_sse42_pcmpestriz128:
12214 Opcode = X86ISD::PCMPESTRI;
12215 X86CC = X86::COND_E;
12218 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12219 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12220 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12221 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12222 DAG.getConstant(X86CC, MVT::i8),
12223 SDValue(PCMP.getNode(), 1));
12224 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12227 case Intrinsic::x86_sse42_pcmpistri128:
12228 case Intrinsic::x86_sse42_pcmpestri128: {
12230 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12231 Opcode = X86ISD::PCMPISTRI;
12233 Opcode = X86ISD::PCMPESTRI;
12235 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12236 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12237 return DAG.getNode(Opcode, dl, VTs, NewOps);
12239 case Intrinsic::x86_fma_vfmadd_ps:
12240 case Intrinsic::x86_fma_vfmadd_pd:
12241 case Intrinsic::x86_fma_vfmsub_ps:
12242 case Intrinsic::x86_fma_vfmsub_pd:
12243 case Intrinsic::x86_fma_vfnmadd_ps:
12244 case Intrinsic::x86_fma_vfnmadd_pd:
12245 case Intrinsic::x86_fma_vfnmsub_ps:
12246 case Intrinsic::x86_fma_vfnmsub_pd:
12247 case Intrinsic::x86_fma_vfmaddsub_ps:
12248 case Intrinsic::x86_fma_vfmaddsub_pd:
12249 case Intrinsic::x86_fma_vfmsubadd_ps:
12250 case Intrinsic::x86_fma_vfmsubadd_pd:
12251 case Intrinsic::x86_fma_vfmadd_ps_256:
12252 case Intrinsic::x86_fma_vfmadd_pd_256:
12253 case Intrinsic::x86_fma_vfmsub_ps_256:
12254 case Intrinsic::x86_fma_vfmsub_pd_256:
12255 case Intrinsic::x86_fma_vfnmadd_ps_256:
12256 case Intrinsic::x86_fma_vfnmadd_pd_256:
12257 case Intrinsic::x86_fma_vfnmsub_ps_256:
12258 case Intrinsic::x86_fma_vfnmsub_pd_256:
12259 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12260 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12261 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12262 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12263 case Intrinsic::x86_fma_vfmadd_ps_512:
12264 case Intrinsic::x86_fma_vfmadd_pd_512:
12265 case Intrinsic::x86_fma_vfmsub_ps_512:
12266 case Intrinsic::x86_fma_vfmsub_pd_512:
12267 case Intrinsic::x86_fma_vfnmadd_ps_512:
12268 case Intrinsic::x86_fma_vfnmadd_pd_512:
12269 case Intrinsic::x86_fma_vfnmsub_ps_512:
12270 case Intrinsic::x86_fma_vfnmsub_pd_512:
12271 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12272 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12273 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12274 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12277 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12278 case Intrinsic::x86_fma_vfmadd_ps:
12279 case Intrinsic::x86_fma_vfmadd_pd:
12280 case Intrinsic::x86_fma_vfmadd_ps_256:
12281 case Intrinsic::x86_fma_vfmadd_pd_256:
12282 case Intrinsic::x86_fma_vfmadd_ps_512:
12283 case Intrinsic::x86_fma_vfmadd_pd_512:
12284 Opc = X86ISD::FMADD;
12286 case Intrinsic::x86_fma_vfmsub_ps:
12287 case Intrinsic::x86_fma_vfmsub_pd:
12288 case Intrinsic::x86_fma_vfmsub_ps_256:
12289 case Intrinsic::x86_fma_vfmsub_pd_256:
12290 case Intrinsic::x86_fma_vfmsub_ps_512:
12291 case Intrinsic::x86_fma_vfmsub_pd_512:
12292 Opc = X86ISD::FMSUB;
12294 case Intrinsic::x86_fma_vfnmadd_ps:
12295 case Intrinsic::x86_fma_vfnmadd_pd:
12296 case Intrinsic::x86_fma_vfnmadd_ps_256:
12297 case Intrinsic::x86_fma_vfnmadd_pd_256:
12298 case Intrinsic::x86_fma_vfnmadd_ps_512:
12299 case Intrinsic::x86_fma_vfnmadd_pd_512:
12300 Opc = X86ISD::FNMADD;
12302 case Intrinsic::x86_fma_vfnmsub_ps:
12303 case Intrinsic::x86_fma_vfnmsub_pd:
12304 case Intrinsic::x86_fma_vfnmsub_ps_256:
12305 case Intrinsic::x86_fma_vfnmsub_pd_256:
12306 case Intrinsic::x86_fma_vfnmsub_ps_512:
12307 case Intrinsic::x86_fma_vfnmsub_pd_512:
12308 Opc = X86ISD::FNMSUB;
12310 case Intrinsic::x86_fma_vfmaddsub_ps:
12311 case Intrinsic::x86_fma_vfmaddsub_pd:
12312 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12313 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12314 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12315 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12316 Opc = X86ISD::FMADDSUB;
12318 case Intrinsic::x86_fma_vfmsubadd_ps:
12319 case Intrinsic::x86_fma_vfmsubadd_pd:
12320 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12321 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12322 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12323 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12324 Opc = X86ISD::FMSUBADD;
12328 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12329 Op.getOperand(2), Op.getOperand(3));
12334 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12335 SDValue Base, SDValue Index,
12336 SDValue ScaleOp, SDValue Chain,
12337 const X86Subtarget * Subtarget) {
12339 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12340 assert(C && "Invalid scale type");
12341 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12342 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12343 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12344 Index.getSimpleValueType().getVectorNumElements());
12345 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12346 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12347 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12348 SDValue Segment = DAG.getRegister(0, MVT::i32);
12349 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12350 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12351 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12352 return DAG.getMergeValues(RetOps, dl);
12355 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12356 SDValue Src, SDValue Mask, SDValue Base,
12357 SDValue Index, SDValue ScaleOp, SDValue Chain,
12358 const X86Subtarget * Subtarget) {
12360 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12361 assert(C && "Invalid scale type");
12362 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12363 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12364 Index.getSimpleValueType().getVectorNumElements());
12365 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12366 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12367 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12368 SDValue Segment = DAG.getRegister(0, MVT::i32);
12369 if (Src.getOpcode() == ISD::UNDEF)
12370 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12371 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12372 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12373 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12374 return DAG.getMergeValues(RetOps, dl);
12377 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12378 SDValue Src, SDValue Base, SDValue Index,
12379 SDValue ScaleOp, SDValue Chain) {
12381 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12382 assert(C && "Invalid scale type");
12383 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12384 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12385 SDValue Segment = DAG.getRegister(0, MVT::i32);
12386 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12387 Index.getSimpleValueType().getVectorNumElements());
12388 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12389 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12390 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12391 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12392 return SDValue(Res, 1);
12395 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12396 SDValue Src, SDValue Mask, SDValue Base,
12397 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12399 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12400 assert(C && "Invalid scale type");
12401 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12402 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12403 SDValue Segment = DAG.getRegister(0, MVT::i32);
12404 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12405 Index.getSimpleValueType().getVectorNumElements());
12406 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12407 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12408 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12409 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12410 return SDValue(Res, 1);
12413 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12414 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12415 // also used to custom lower READCYCLECOUNTER nodes.
12416 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12417 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12418 SmallVectorImpl<SDValue> &Results) {
12419 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12420 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12423 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12424 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12425 // and the EAX register is loaded with the low-order 32 bits.
12426 if (Subtarget->is64Bit()) {
12427 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12428 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12431 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12432 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12435 SDValue Chain = HI.getValue(1);
12437 if (Opcode == X86ISD::RDTSCP_DAG) {
12438 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12440 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12441 // the ECX register. Add 'ecx' explicitly to the chain.
12442 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12444 // Explicitly store the content of ECX at the location passed in input
12445 // to the 'rdtscp' intrinsic.
12446 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12447 MachinePointerInfo(), false, false, 0);
12450 if (Subtarget->is64Bit()) {
12451 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12452 // the EAX register is loaded with the low-order 32 bits.
12453 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12454 DAG.getConstant(32, MVT::i8));
12455 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12456 Results.push_back(Chain);
12460 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12461 SDValue Ops[] = { LO, HI };
12462 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12463 Results.push_back(Pair);
12464 Results.push_back(Chain);
12467 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12468 SelectionDAG &DAG) {
12469 SmallVector<SDValue, 2> Results;
12471 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12473 return DAG.getMergeValues(Results, DL);
12476 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12477 SelectionDAG &DAG) {
12479 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12481 default: return SDValue(); // Don't custom lower most intrinsics.
12483 // RDRAND/RDSEED intrinsics.
12484 case Intrinsic::x86_rdrand_16:
12485 case Intrinsic::x86_rdrand_32:
12486 case Intrinsic::x86_rdrand_64:
12487 case Intrinsic::x86_rdseed_16:
12488 case Intrinsic::x86_rdseed_32:
12489 case Intrinsic::x86_rdseed_64: {
12490 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12491 IntNo == Intrinsic::x86_rdseed_32 ||
12492 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12494 // Emit the node with the right value type.
12495 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12496 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12498 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12499 // Otherwise return the value from Rand, which is always 0, casted to i32.
12500 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12501 DAG.getConstant(1, Op->getValueType(1)),
12502 DAG.getConstant(X86::COND_B, MVT::i32),
12503 SDValue(Result.getNode(), 1) };
12504 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12505 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12508 // Return { result, isValid, chain }.
12509 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12510 SDValue(Result.getNode(), 2));
12512 //int_gather(index, base, scale);
12513 case Intrinsic::x86_avx512_gather_qpd_512:
12514 case Intrinsic::x86_avx512_gather_qps_512:
12515 case Intrinsic::x86_avx512_gather_dpd_512:
12516 case Intrinsic::x86_avx512_gather_qpi_512:
12517 case Intrinsic::x86_avx512_gather_qpq_512:
12518 case Intrinsic::x86_avx512_gather_dpq_512:
12519 case Intrinsic::x86_avx512_gather_dps_512:
12520 case Intrinsic::x86_avx512_gather_dpi_512: {
12523 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12524 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12525 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12526 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12527 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12528 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12529 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12530 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12531 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12533 SDValue Chain = Op.getOperand(0);
12534 SDValue Index = Op.getOperand(2);
12535 SDValue Base = Op.getOperand(3);
12536 SDValue Scale = Op.getOperand(4);
12537 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12539 //int_gather_mask(v1, mask, index, base, scale);
12540 case Intrinsic::x86_avx512_gather_qps_mask_512:
12541 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12542 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12543 case Intrinsic::x86_avx512_gather_dps_mask_512:
12544 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12545 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12546 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12547 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12550 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12551 case Intrinsic::x86_avx512_gather_qps_mask_512:
12552 Opc = X86::VGATHERQPSZrm; break;
12553 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12554 Opc = X86::VGATHERQPDZrm; break;
12555 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12556 Opc = X86::VGATHERDPDZrm; break;
12557 case Intrinsic::x86_avx512_gather_dps_mask_512:
12558 Opc = X86::VGATHERDPSZrm; break;
12559 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12560 Opc = X86::VPGATHERQDZrm; break;
12561 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12562 Opc = X86::VPGATHERQQZrm; break;
12563 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12564 Opc = X86::VPGATHERDDZrm; break;
12565 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12566 Opc = X86::VPGATHERDQZrm; break;
12568 SDValue Chain = Op.getOperand(0);
12569 SDValue Src = Op.getOperand(2);
12570 SDValue Mask = Op.getOperand(3);
12571 SDValue Index = Op.getOperand(4);
12572 SDValue Base = Op.getOperand(5);
12573 SDValue Scale = Op.getOperand(6);
12574 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12577 //int_scatter(base, index, v1, scale);
12578 case Intrinsic::x86_avx512_scatter_qpd_512:
12579 case Intrinsic::x86_avx512_scatter_qps_512:
12580 case Intrinsic::x86_avx512_scatter_dpd_512:
12581 case Intrinsic::x86_avx512_scatter_qpi_512:
12582 case Intrinsic::x86_avx512_scatter_qpq_512:
12583 case Intrinsic::x86_avx512_scatter_dpq_512:
12584 case Intrinsic::x86_avx512_scatter_dps_512:
12585 case Intrinsic::x86_avx512_scatter_dpi_512: {
12588 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12589 case Intrinsic::x86_avx512_scatter_qpd_512:
12590 Opc = X86::VSCATTERQPDZmr; break;
12591 case Intrinsic::x86_avx512_scatter_qps_512:
12592 Opc = X86::VSCATTERQPSZmr; break;
12593 case Intrinsic::x86_avx512_scatter_dpd_512:
12594 Opc = X86::VSCATTERDPDZmr; break;
12595 case Intrinsic::x86_avx512_scatter_dps_512:
12596 Opc = X86::VSCATTERDPSZmr; break;
12597 case Intrinsic::x86_avx512_scatter_qpi_512:
12598 Opc = X86::VPSCATTERQDZmr; break;
12599 case Intrinsic::x86_avx512_scatter_qpq_512:
12600 Opc = X86::VPSCATTERQQZmr; break;
12601 case Intrinsic::x86_avx512_scatter_dpq_512:
12602 Opc = X86::VPSCATTERDQZmr; break;
12603 case Intrinsic::x86_avx512_scatter_dpi_512:
12604 Opc = X86::VPSCATTERDDZmr; break;
12606 SDValue Chain = Op.getOperand(0);
12607 SDValue Base = Op.getOperand(2);
12608 SDValue Index = Op.getOperand(3);
12609 SDValue Src = Op.getOperand(4);
12610 SDValue Scale = Op.getOperand(5);
12611 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12613 //int_scatter_mask(base, mask, index, v1, scale);
12614 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12615 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12616 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12617 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12618 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12619 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12620 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12621 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12624 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12625 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12626 Opc = X86::VSCATTERQPDZmr; break;
12627 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12628 Opc = X86::VSCATTERQPSZmr; break;
12629 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12630 Opc = X86::VSCATTERDPDZmr; break;
12631 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12632 Opc = X86::VSCATTERDPSZmr; break;
12633 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12634 Opc = X86::VPSCATTERQDZmr; break;
12635 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12636 Opc = X86::VPSCATTERQQZmr; break;
12637 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12638 Opc = X86::VPSCATTERDQZmr; break;
12639 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12640 Opc = X86::VPSCATTERDDZmr; break;
12642 SDValue Chain = Op.getOperand(0);
12643 SDValue Base = Op.getOperand(2);
12644 SDValue Mask = Op.getOperand(3);
12645 SDValue Index = Op.getOperand(4);
12646 SDValue Src = Op.getOperand(5);
12647 SDValue Scale = Op.getOperand(6);
12648 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12650 // Read Time Stamp Counter (RDTSC).
12651 case Intrinsic::x86_rdtsc:
12652 // Read Time Stamp Counter and Processor ID (RDTSCP).
12653 case Intrinsic::x86_rdtscp: {
12656 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12657 case Intrinsic::x86_rdtsc:
12658 Opc = X86ISD::RDTSC_DAG; break;
12659 case Intrinsic::x86_rdtscp:
12660 Opc = X86ISD::RDTSCP_DAG; break;
12662 SmallVector<SDValue, 2> Results;
12663 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12664 return DAG.getMergeValues(Results, dl);
12666 // XTEST intrinsics.
12667 case Intrinsic::x86_xtest: {
12668 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12669 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12670 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12671 DAG.getConstant(X86::COND_NE, MVT::i8),
12673 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12674 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12675 Ret, SDValue(InTrans.getNode(), 1));
12680 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12681 SelectionDAG &DAG) const {
12682 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12683 MFI->setReturnAddressIsTaken(true);
12685 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12688 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12690 EVT PtrVT = getPointerTy();
12693 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12694 const X86RegisterInfo *RegInfo =
12695 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12696 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12697 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12698 DAG.getNode(ISD::ADD, dl, PtrVT,
12699 FrameAddr, Offset),
12700 MachinePointerInfo(), false, false, false, 0);
12703 // Just load the return address.
12704 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12705 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12706 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12709 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12710 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12711 MFI->setFrameAddressIsTaken(true);
12713 EVT VT = Op.getValueType();
12714 SDLoc dl(Op); // FIXME probably not meaningful
12715 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12716 const X86RegisterInfo *RegInfo =
12717 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12718 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12719 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12720 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12721 "Invalid Frame Register!");
12722 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12724 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12725 MachinePointerInfo(),
12726 false, false, false, 0);
12730 // FIXME? Maybe this could be a TableGen attribute on some registers and
12731 // this table could be generated automatically from RegInfo.
12732 unsigned X86TargetLowering::getRegisterByName(const char* RegName) const {
12733 unsigned Reg = StringSwitch<unsigned>(RegName)
12734 .Case("esp", X86::ESP)
12735 .Case("rsp", X86::RSP)
12739 report_fatal_error("Invalid register name global variable");
12742 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12743 SelectionDAG &DAG) const {
12744 const X86RegisterInfo *RegInfo =
12745 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12746 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12749 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12750 SDValue Chain = Op.getOperand(0);
12751 SDValue Offset = Op.getOperand(1);
12752 SDValue Handler = Op.getOperand(2);
12755 EVT PtrVT = getPointerTy();
12756 const X86RegisterInfo *RegInfo =
12757 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12758 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12759 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12760 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12761 "Invalid Frame Register!");
12762 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12763 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12765 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12766 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12767 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12768 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12770 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12772 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12773 DAG.getRegister(StoreAddrReg, PtrVT));
12776 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12777 SelectionDAG &DAG) const {
12779 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12780 DAG.getVTList(MVT::i32, MVT::Other),
12781 Op.getOperand(0), Op.getOperand(1));
12784 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12785 SelectionDAG &DAG) const {
12787 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12788 Op.getOperand(0), Op.getOperand(1));
12791 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12792 return Op.getOperand(0);
12795 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12796 SelectionDAG &DAG) const {
12797 SDValue Root = Op.getOperand(0);
12798 SDValue Trmp = Op.getOperand(1); // trampoline
12799 SDValue FPtr = Op.getOperand(2); // nested function
12800 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12803 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12804 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12806 if (Subtarget->is64Bit()) {
12807 SDValue OutChains[6];
12809 // Large code-model.
12810 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12811 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12813 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12814 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12816 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12818 // Load the pointer to the nested function into R11.
12819 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12820 SDValue Addr = Trmp;
12821 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12822 Addr, MachinePointerInfo(TrmpAddr),
12825 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12826 DAG.getConstant(2, MVT::i64));
12827 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12828 MachinePointerInfo(TrmpAddr, 2),
12831 // Load the 'nest' parameter value into R10.
12832 // R10 is specified in X86CallingConv.td
12833 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12834 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12835 DAG.getConstant(10, MVT::i64));
12836 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12837 Addr, MachinePointerInfo(TrmpAddr, 10),
12840 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12841 DAG.getConstant(12, MVT::i64));
12842 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12843 MachinePointerInfo(TrmpAddr, 12),
12846 // Jump to the nested function.
12847 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12848 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12849 DAG.getConstant(20, MVT::i64));
12850 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12851 Addr, MachinePointerInfo(TrmpAddr, 20),
12854 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12855 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12856 DAG.getConstant(22, MVT::i64));
12857 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12858 MachinePointerInfo(TrmpAddr, 22),
12861 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12863 const Function *Func =
12864 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12865 CallingConv::ID CC = Func->getCallingConv();
12870 llvm_unreachable("Unsupported calling convention");
12871 case CallingConv::C:
12872 case CallingConv::X86_StdCall: {
12873 // Pass 'nest' parameter in ECX.
12874 // Must be kept in sync with X86CallingConv.td
12875 NestReg = X86::ECX;
12877 // Check that ECX wasn't needed by an 'inreg' parameter.
12878 FunctionType *FTy = Func->getFunctionType();
12879 const AttributeSet &Attrs = Func->getAttributes();
12881 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12882 unsigned InRegCount = 0;
12885 for (FunctionType::param_iterator I = FTy->param_begin(),
12886 E = FTy->param_end(); I != E; ++I, ++Idx)
12887 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12888 // FIXME: should only count parameters that are lowered to integers.
12889 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12891 if (InRegCount > 2) {
12892 report_fatal_error("Nest register in use - reduce number of inreg"
12898 case CallingConv::X86_FastCall:
12899 case CallingConv::X86_ThisCall:
12900 case CallingConv::Fast:
12901 // Pass 'nest' parameter in EAX.
12902 // Must be kept in sync with X86CallingConv.td
12903 NestReg = X86::EAX;
12907 SDValue OutChains[4];
12908 SDValue Addr, Disp;
12910 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12911 DAG.getConstant(10, MVT::i32));
12912 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12914 // This is storing the opcode for MOV32ri.
12915 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12916 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12917 OutChains[0] = DAG.getStore(Root, dl,
12918 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12919 Trmp, MachinePointerInfo(TrmpAddr),
12922 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12923 DAG.getConstant(1, MVT::i32));
12924 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12925 MachinePointerInfo(TrmpAddr, 1),
12928 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12929 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12930 DAG.getConstant(5, MVT::i32));
12931 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12932 MachinePointerInfo(TrmpAddr, 5),
12935 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12936 DAG.getConstant(6, MVT::i32));
12937 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12938 MachinePointerInfo(TrmpAddr, 6),
12941 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12945 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12946 SelectionDAG &DAG) const {
12948 The rounding mode is in bits 11:10 of FPSR, and has the following
12950 00 Round to nearest
12955 FLT_ROUNDS, on the other hand, expects the following:
12962 To perform the conversion, we do:
12963 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12966 MachineFunction &MF = DAG.getMachineFunction();
12967 const TargetMachine &TM = MF.getTarget();
12968 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12969 unsigned StackAlignment = TFI.getStackAlignment();
12970 MVT VT = Op.getSimpleValueType();
12973 // Save FP Control Word to stack slot
12974 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12975 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12977 MachineMemOperand *MMO =
12978 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12979 MachineMemOperand::MOStore, 2, 2);
12981 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12982 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12983 DAG.getVTList(MVT::Other),
12984 Ops, MVT::i16, MMO);
12986 // Load FP Control Word from stack slot
12987 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12988 MachinePointerInfo(), false, false, false, 0);
12990 // Transform as necessary
12992 DAG.getNode(ISD::SRL, DL, MVT::i16,
12993 DAG.getNode(ISD::AND, DL, MVT::i16,
12994 CWD, DAG.getConstant(0x800, MVT::i16)),
12995 DAG.getConstant(11, MVT::i8));
12997 DAG.getNode(ISD::SRL, DL, MVT::i16,
12998 DAG.getNode(ISD::AND, DL, MVT::i16,
12999 CWD, DAG.getConstant(0x400, MVT::i16)),
13000 DAG.getConstant(9, MVT::i8));
13003 DAG.getNode(ISD::AND, DL, MVT::i16,
13004 DAG.getNode(ISD::ADD, DL, MVT::i16,
13005 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13006 DAG.getConstant(1, MVT::i16)),
13007 DAG.getConstant(3, MVT::i16));
13009 return DAG.getNode((VT.getSizeInBits() < 16 ?
13010 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13013 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13014 MVT VT = Op.getSimpleValueType();
13016 unsigned NumBits = VT.getSizeInBits();
13019 Op = Op.getOperand(0);
13020 if (VT == MVT::i8) {
13021 // Zero extend to i32 since there is not an i8 bsr.
13023 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13026 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13027 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13028 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13030 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13033 DAG.getConstant(NumBits+NumBits-1, OpVT),
13034 DAG.getConstant(X86::COND_E, MVT::i8),
13037 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13039 // Finally xor with NumBits-1.
13040 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13043 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13047 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13048 MVT VT = Op.getSimpleValueType();
13050 unsigned NumBits = VT.getSizeInBits();
13053 Op = Op.getOperand(0);
13054 if (VT == MVT::i8) {
13055 // Zero extend to i32 since there is not an i8 bsr.
13057 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13060 // Issue a bsr (scan bits in reverse).
13061 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13062 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13064 // And xor with NumBits-1.
13065 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13068 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13072 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13073 MVT VT = Op.getSimpleValueType();
13074 unsigned NumBits = VT.getSizeInBits();
13076 Op = Op.getOperand(0);
13078 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13079 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13080 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13082 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13085 DAG.getConstant(NumBits, VT),
13086 DAG.getConstant(X86::COND_E, MVT::i8),
13089 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13092 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13093 // ones, and then concatenate the result back.
13094 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13095 MVT VT = Op.getSimpleValueType();
13097 assert(VT.is256BitVector() && VT.isInteger() &&
13098 "Unsupported value type for operation");
13100 unsigned NumElems = VT.getVectorNumElements();
13103 // Extract the LHS vectors
13104 SDValue LHS = Op.getOperand(0);
13105 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13106 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13108 // Extract the RHS vectors
13109 SDValue RHS = Op.getOperand(1);
13110 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13111 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13113 MVT EltVT = VT.getVectorElementType();
13114 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13116 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13117 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13118 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13121 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13122 assert(Op.getSimpleValueType().is256BitVector() &&
13123 Op.getSimpleValueType().isInteger() &&
13124 "Only handle AVX 256-bit vector integer operation");
13125 return Lower256IntArith(Op, DAG);
13128 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13129 assert(Op.getSimpleValueType().is256BitVector() &&
13130 Op.getSimpleValueType().isInteger() &&
13131 "Only handle AVX 256-bit vector integer operation");
13132 return Lower256IntArith(Op, DAG);
13135 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13136 SelectionDAG &DAG) {
13138 MVT VT = Op.getSimpleValueType();
13140 // Decompose 256-bit ops into smaller 128-bit ops.
13141 if (VT.is256BitVector() && !Subtarget->hasInt256())
13142 return Lower256IntArith(Op, DAG);
13144 SDValue A = Op.getOperand(0);
13145 SDValue B = Op.getOperand(1);
13147 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13148 if (VT == MVT::v4i32) {
13149 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13150 "Should not custom lower when pmuldq is available!");
13152 // Extract the odd parts.
13153 static const int UnpackMask[] = { 1, -1, 3, -1 };
13154 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13155 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13157 // Multiply the even parts.
13158 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13159 // Now multiply odd parts.
13160 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13162 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13163 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13165 // Merge the two vectors back together with a shuffle. This expands into 2
13167 static const int ShufMask[] = { 0, 4, 2, 6 };
13168 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13171 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13172 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13174 // Ahi = psrlqi(a, 32);
13175 // Bhi = psrlqi(b, 32);
13177 // AloBlo = pmuludq(a, b);
13178 // AloBhi = pmuludq(a, Bhi);
13179 // AhiBlo = pmuludq(Ahi, b);
13181 // AloBhi = psllqi(AloBhi, 32);
13182 // AhiBlo = psllqi(AhiBlo, 32);
13183 // return AloBlo + AloBhi + AhiBlo;
13185 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13186 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13188 // Bit cast to 32-bit vectors for MULUDQ
13189 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13190 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13191 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13192 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13193 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13194 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13196 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13197 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13198 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13200 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13201 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13203 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13204 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13207 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13208 assert(Subtarget->isTargetWin64() && "Unexpected target");
13209 EVT VT = Op.getValueType();
13210 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13211 "Unexpected return type for lowering");
13215 switch (Op->getOpcode()) {
13216 default: llvm_unreachable("Unexpected request for libcall!");
13217 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13218 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13219 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13220 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13221 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13222 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13226 SDValue InChain = DAG.getEntryNode();
13228 TargetLowering::ArgListTy Args;
13229 TargetLowering::ArgListEntry Entry;
13230 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13231 EVT ArgVT = Op->getOperand(i).getValueType();
13232 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13233 "Unexpected argument type for lowering");
13234 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13235 Entry.Node = StackPtr;
13236 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13238 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13239 Entry.Ty = PointerType::get(ArgTy,0);
13240 Entry.isSExt = false;
13241 Entry.isZExt = false;
13242 Args.push_back(Entry);
13245 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13248 TargetLowering::CallLoweringInfo CLI(
13249 InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13250 isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13251 /*isTailCall=*/false,
13252 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13254 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13256 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13259 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13260 SelectionDAG &DAG) {
13261 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13262 EVT VT = Op0.getValueType();
13265 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13266 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13268 // Get the high parts.
13269 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13270 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13271 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13273 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13275 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13276 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13278 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13279 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13280 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13281 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13282 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13284 // Shuffle it back into the right order.
13285 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13286 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13287 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13288 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13290 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13291 // unsigned multiply.
13292 if (IsSigned && !Subtarget->hasSSE41()) {
13294 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13295 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13296 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13297 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13298 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13300 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13301 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13304 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13307 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13308 const X86Subtarget *Subtarget) {
13309 MVT VT = Op.getSimpleValueType();
13311 SDValue R = Op.getOperand(0);
13312 SDValue Amt = Op.getOperand(1);
13314 // Optimize shl/srl/sra with constant shift amount.
13315 if (isSplatVector(Amt.getNode())) {
13316 SDValue SclrAmt = Amt->getOperand(0);
13317 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13318 uint64_t ShiftAmt = C->getZExtValue();
13320 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13321 (Subtarget->hasInt256() &&
13322 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13323 (Subtarget->hasAVX512() &&
13324 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13325 if (Op.getOpcode() == ISD::SHL)
13326 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13328 if (Op.getOpcode() == ISD::SRL)
13329 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13331 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13332 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13336 if (VT == MVT::v16i8) {
13337 if (Op.getOpcode() == ISD::SHL) {
13338 // Make a large shift.
13339 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13340 MVT::v8i16, R, ShiftAmt,
13342 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13343 // Zero out the rightmost bits.
13344 SmallVector<SDValue, 16> V(16,
13345 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13347 return DAG.getNode(ISD::AND, dl, VT, SHL,
13348 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13350 if (Op.getOpcode() == ISD::SRL) {
13351 // Make a large shift.
13352 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13353 MVT::v8i16, R, ShiftAmt,
13355 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13356 // Zero out the leftmost bits.
13357 SmallVector<SDValue, 16> V(16,
13358 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13360 return DAG.getNode(ISD::AND, dl, VT, SRL,
13361 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13363 if (Op.getOpcode() == ISD::SRA) {
13364 if (ShiftAmt == 7) {
13365 // R s>> 7 === R s< 0
13366 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13367 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13370 // R s>> a === ((R u>> a) ^ m) - m
13371 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13372 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13374 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13375 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13376 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13379 llvm_unreachable("Unknown shift opcode.");
13382 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13383 if (Op.getOpcode() == ISD::SHL) {
13384 // Make a large shift.
13385 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13386 MVT::v16i16, R, ShiftAmt,
13388 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13389 // Zero out the rightmost bits.
13390 SmallVector<SDValue, 32> V(32,
13391 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13393 return DAG.getNode(ISD::AND, dl, VT, SHL,
13394 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13396 if (Op.getOpcode() == ISD::SRL) {
13397 // Make a large shift.
13398 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13399 MVT::v16i16, R, ShiftAmt,
13401 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13402 // Zero out the leftmost bits.
13403 SmallVector<SDValue, 32> V(32,
13404 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13406 return DAG.getNode(ISD::AND, dl, VT, SRL,
13407 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13409 if (Op.getOpcode() == ISD::SRA) {
13410 if (ShiftAmt == 7) {
13411 // R s>> 7 === R s< 0
13412 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13413 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13416 // R s>> a === ((R u>> a) ^ m) - m
13417 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13418 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13420 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13421 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13422 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13425 llvm_unreachable("Unknown shift opcode.");
13430 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13431 if (!Subtarget->is64Bit() &&
13432 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13433 Amt.getOpcode() == ISD::BITCAST &&
13434 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13435 Amt = Amt.getOperand(0);
13436 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13437 VT.getVectorNumElements();
13438 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13439 uint64_t ShiftAmt = 0;
13440 for (unsigned i = 0; i != Ratio; ++i) {
13441 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13445 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13447 // Check remaining shift amounts.
13448 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13449 uint64_t ShAmt = 0;
13450 for (unsigned j = 0; j != Ratio; ++j) {
13451 ConstantSDNode *C =
13452 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13456 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13458 if (ShAmt != ShiftAmt)
13461 switch (Op.getOpcode()) {
13463 llvm_unreachable("Unknown shift opcode!");
13465 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13468 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13471 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13479 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13480 const X86Subtarget* Subtarget) {
13481 MVT VT = Op.getSimpleValueType();
13483 SDValue R = Op.getOperand(0);
13484 SDValue Amt = Op.getOperand(1);
13486 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13487 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13488 (Subtarget->hasInt256() &&
13489 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13490 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13491 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13493 EVT EltVT = VT.getVectorElementType();
13495 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13496 unsigned NumElts = VT.getVectorNumElements();
13498 for (i = 0; i != NumElts; ++i) {
13499 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13503 for (j = i; j != NumElts; ++j) {
13504 SDValue Arg = Amt.getOperand(j);
13505 if (Arg.getOpcode() == ISD::UNDEF) continue;
13506 if (Arg != Amt.getOperand(i))
13509 if (i != NumElts && j == NumElts)
13510 BaseShAmt = Amt.getOperand(i);
13512 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13513 Amt = Amt.getOperand(0);
13514 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13515 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13516 SDValue InVec = Amt.getOperand(0);
13517 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13518 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13520 for (; i != NumElts; ++i) {
13521 SDValue Arg = InVec.getOperand(i);
13522 if (Arg.getOpcode() == ISD::UNDEF) continue;
13526 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13527 if (ConstantSDNode *C =
13528 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13529 unsigned SplatIdx =
13530 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13531 if (C->getZExtValue() == SplatIdx)
13532 BaseShAmt = InVec.getOperand(1);
13535 if (!BaseShAmt.getNode())
13536 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13537 DAG.getIntPtrConstant(0));
13541 if (BaseShAmt.getNode()) {
13542 if (EltVT.bitsGT(MVT::i32))
13543 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13544 else if (EltVT.bitsLT(MVT::i32))
13545 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13547 switch (Op.getOpcode()) {
13549 llvm_unreachable("Unknown shift opcode!");
13551 switch (VT.SimpleTy) {
13552 default: return SDValue();
13561 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13564 switch (VT.SimpleTy) {
13565 default: return SDValue();
13572 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13575 switch (VT.SimpleTy) {
13576 default: return SDValue();
13585 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13591 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13592 if (!Subtarget->is64Bit() &&
13593 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13594 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13595 Amt.getOpcode() == ISD::BITCAST &&
13596 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13597 Amt = Amt.getOperand(0);
13598 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13599 VT.getVectorNumElements();
13600 std::vector<SDValue> Vals(Ratio);
13601 for (unsigned i = 0; i != Ratio; ++i)
13602 Vals[i] = Amt.getOperand(i);
13603 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13604 for (unsigned j = 0; j != Ratio; ++j)
13605 if (Vals[j] != Amt.getOperand(i + j))
13608 switch (Op.getOpcode()) {
13610 llvm_unreachable("Unknown shift opcode!");
13612 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13614 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13616 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13623 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13624 SelectionDAG &DAG) {
13626 MVT VT = Op.getSimpleValueType();
13628 SDValue R = Op.getOperand(0);
13629 SDValue Amt = Op.getOperand(1);
13632 if (!Subtarget->hasSSE2())
13635 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13639 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13643 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13645 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13646 if (Subtarget->hasInt256()) {
13647 if (Op.getOpcode() == ISD::SRL &&
13648 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13649 VT == MVT::v4i64 || VT == MVT::v8i32))
13651 if (Op.getOpcode() == ISD::SHL &&
13652 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13653 VT == MVT::v4i64 || VT == MVT::v8i32))
13655 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13659 // If possible, lower this packed shift into a vector multiply instead of
13660 // expanding it into a sequence of scalar shifts.
13661 // Do this only if the vector shift count is a constant build_vector.
13662 if (Op.getOpcode() == ISD::SHL &&
13663 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13664 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13665 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13666 SmallVector<SDValue, 8> Elts;
13667 EVT SVT = VT.getScalarType();
13668 unsigned SVTBits = SVT.getSizeInBits();
13669 const APInt &One = APInt(SVTBits, 1);
13670 unsigned NumElems = VT.getVectorNumElements();
13672 for (unsigned i=0; i !=NumElems; ++i) {
13673 SDValue Op = Amt->getOperand(i);
13674 if (Op->getOpcode() == ISD::UNDEF) {
13675 Elts.push_back(Op);
13679 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13680 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13681 uint64_t ShAmt = C.getZExtValue();
13682 if (ShAmt >= SVTBits) {
13683 Elts.push_back(DAG.getUNDEF(SVT));
13686 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13688 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13689 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13692 // Lower SHL with variable shift amount.
13693 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13694 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13696 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13697 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13698 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13699 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13702 // If possible, lower this shift as a sequence of two shifts by
13703 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13705 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13707 // Could be rewritten as:
13708 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13710 // The advantage is that the two shifts from the example would be
13711 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13712 // the vector shift into four scalar shifts plus four pairs of vector
13714 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13715 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13716 unsigned TargetOpcode = X86ISD::MOVSS;
13717 bool CanBeSimplified;
13718 // The splat value for the first packed shift (the 'X' from the example).
13719 SDValue Amt1 = Amt->getOperand(0);
13720 // The splat value for the second packed shift (the 'Y' from the example).
13721 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13722 Amt->getOperand(2);
13724 // See if it is possible to replace this node with a sequence of
13725 // two shifts followed by a MOVSS/MOVSD
13726 if (VT == MVT::v4i32) {
13727 // Check if it is legal to use a MOVSS.
13728 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13729 Amt2 == Amt->getOperand(3);
13730 if (!CanBeSimplified) {
13731 // Otherwise, check if we can still simplify this node using a MOVSD.
13732 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13733 Amt->getOperand(2) == Amt->getOperand(3);
13734 TargetOpcode = X86ISD::MOVSD;
13735 Amt2 = Amt->getOperand(2);
13738 // Do similar checks for the case where the machine value type
13740 CanBeSimplified = Amt1 == Amt->getOperand(1);
13741 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13742 CanBeSimplified = Amt2 == Amt->getOperand(i);
13744 if (!CanBeSimplified) {
13745 TargetOpcode = X86ISD::MOVSD;
13746 CanBeSimplified = true;
13747 Amt2 = Amt->getOperand(4);
13748 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13749 CanBeSimplified = Amt1 == Amt->getOperand(i);
13750 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13751 CanBeSimplified = Amt2 == Amt->getOperand(j);
13755 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13756 isa<ConstantSDNode>(Amt2)) {
13757 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13758 EVT CastVT = MVT::v4i32;
13760 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13761 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13763 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13764 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13765 if (TargetOpcode == X86ISD::MOVSD)
13766 CastVT = MVT::v2i64;
13767 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13768 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13769 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13771 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13775 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13776 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13779 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13780 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13782 // Turn 'a' into a mask suitable for VSELECT
13783 SDValue VSelM = DAG.getConstant(0x80, VT);
13784 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13785 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13787 SDValue CM1 = DAG.getConstant(0x0f, VT);
13788 SDValue CM2 = DAG.getConstant(0x3f, VT);
13790 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13791 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13792 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13793 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13794 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13797 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13798 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13799 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13801 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13802 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13803 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13804 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13805 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13808 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13809 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13810 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13812 // return VSELECT(r, r+r, a);
13813 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13814 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13818 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13819 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13820 // solution better.
13821 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13822 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13824 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13825 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13826 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13827 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13828 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13831 // Decompose 256-bit shifts into smaller 128-bit shifts.
13832 if (VT.is256BitVector()) {
13833 unsigned NumElems = VT.getVectorNumElements();
13834 MVT EltVT = VT.getVectorElementType();
13835 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13837 // Extract the two vectors
13838 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13839 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13841 // Recreate the shift amount vectors
13842 SDValue Amt1, Amt2;
13843 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13844 // Constant shift amount
13845 SmallVector<SDValue, 4> Amt1Csts;
13846 SmallVector<SDValue, 4> Amt2Csts;
13847 for (unsigned i = 0; i != NumElems/2; ++i)
13848 Amt1Csts.push_back(Amt->getOperand(i));
13849 for (unsigned i = NumElems/2; i != NumElems; ++i)
13850 Amt2Csts.push_back(Amt->getOperand(i));
13852 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13853 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13855 // Variable shift amount
13856 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13857 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13860 // Issue new vector shifts for the smaller types
13861 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13862 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13864 // Concatenate the result back
13865 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13871 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13872 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13873 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13874 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13875 // has only one use.
13876 SDNode *N = Op.getNode();
13877 SDValue LHS = N->getOperand(0);
13878 SDValue RHS = N->getOperand(1);
13879 unsigned BaseOp = 0;
13882 switch (Op.getOpcode()) {
13883 default: llvm_unreachable("Unknown ovf instruction!");
13885 // A subtract of one will be selected as a INC. Note that INC doesn't
13886 // set CF, so we can't do this for UADDO.
13887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13889 BaseOp = X86ISD::INC;
13890 Cond = X86::COND_O;
13893 BaseOp = X86ISD::ADD;
13894 Cond = X86::COND_O;
13897 BaseOp = X86ISD::ADD;
13898 Cond = X86::COND_B;
13901 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13902 // set CF, so we can't do this for USUBO.
13903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13905 BaseOp = X86ISD::DEC;
13906 Cond = X86::COND_O;
13909 BaseOp = X86ISD::SUB;
13910 Cond = X86::COND_O;
13913 BaseOp = X86ISD::SUB;
13914 Cond = X86::COND_B;
13917 BaseOp = X86ISD::SMUL;
13918 Cond = X86::COND_O;
13920 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13921 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13923 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13926 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13927 DAG.getConstant(X86::COND_O, MVT::i32),
13928 SDValue(Sum.getNode(), 2));
13930 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13934 // Also sets EFLAGS.
13935 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13936 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13939 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13940 DAG.getConstant(Cond, MVT::i32),
13941 SDValue(Sum.getNode(), 1));
13943 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13946 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13947 SelectionDAG &DAG) const {
13949 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13950 MVT VT = Op.getSimpleValueType();
13952 if (!Subtarget->hasSSE2() || !VT.isVector())
13955 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13956 ExtraVT.getScalarType().getSizeInBits();
13958 switch (VT.SimpleTy) {
13959 default: return SDValue();
13962 if (!Subtarget->hasFp256())
13964 if (!Subtarget->hasInt256()) {
13965 // needs to be split
13966 unsigned NumElems = VT.getVectorNumElements();
13968 // Extract the LHS vectors
13969 SDValue LHS = Op.getOperand(0);
13970 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13971 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13973 MVT EltVT = VT.getVectorElementType();
13974 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13976 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13977 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13978 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13980 SDValue Extra = DAG.getValueType(ExtraVT);
13982 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13983 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13985 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13990 SDValue Op0 = Op.getOperand(0);
13991 SDValue Op00 = Op0.getOperand(0);
13993 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13994 if (Op0.getOpcode() == ISD::BITCAST &&
13995 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13996 // (sext (vzext x)) -> (vsext x)
13997 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13998 if (Tmp1.getNode()) {
13999 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14000 // This folding is only valid when the in-reg type is a vector of i8,
14002 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14003 ExtraEltVT == MVT::i32) {
14004 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14005 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14006 "This optimization is invalid without a VZEXT.");
14007 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14013 // If the above didn't work, then just use Shift-Left + Shift-Right.
14014 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14016 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14022 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14023 SelectionDAG &DAG) {
14025 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14026 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14027 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14028 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14030 // The only fence that needs an instruction is a sequentially-consistent
14031 // cross-thread fence.
14032 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14033 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14034 // no-sse2). There isn't any reason to disable it if the target processor
14036 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14037 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14039 SDValue Chain = Op.getOperand(0);
14040 SDValue Zero = DAG.getConstant(0, MVT::i32);
14042 DAG.getRegister(X86::ESP, MVT::i32), // Base
14043 DAG.getTargetConstant(1, MVT::i8), // Scale
14044 DAG.getRegister(0, MVT::i32), // Index
14045 DAG.getTargetConstant(0, MVT::i32), // Disp
14046 DAG.getRegister(0, MVT::i32), // Segment.
14050 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14051 return SDValue(Res, 0);
14054 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14055 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14058 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14059 SelectionDAG &DAG) {
14060 MVT T = Op.getSimpleValueType();
14064 switch(T.SimpleTy) {
14065 default: llvm_unreachable("Invalid value type!");
14066 case MVT::i8: Reg = X86::AL; size = 1; break;
14067 case MVT::i16: Reg = X86::AX; size = 2; break;
14068 case MVT::i32: Reg = X86::EAX; size = 4; break;
14070 assert(Subtarget->is64Bit() && "Node not type legal!");
14071 Reg = X86::RAX; size = 8;
14074 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14075 Op.getOperand(2), SDValue());
14076 SDValue Ops[] = { cpIn.getValue(0),
14079 DAG.getTargetConstant(size, MVT::i8),
14080 cpIn.getValue(1) };
14081 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14082 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14083 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14086 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14090 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14091 SelectionDAG &DAG) {
14092 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14093 MVT DstVT = Op.getSimpleValueType();
14094 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14095 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14096 assert((DstVT == MVT::i64 ||
14097 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14098 "Unexpected custom BITCAST");
14099 // i64 <=> MMX conversions are Legal.
14100 if (SrcVT==MVT::i64 && DstVT.isVector())
14102 if (DstVT==MVT::i64 && SrcVT.isVector())
14104 // MMX <=> MMX conversions are Legal.
14105 if (SrcVT.isVector() && DstVT.isVector())
14107 // All other conversions need to be expanded.
14111 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14112 SDNode *Node = Op.getNode();
14114 EVT T = Node->getValueType(0);
14115 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14116 DAG.getConstant(0, T), Node->getOperand(2));
14117 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14118 cast<AtomicSDNode>(Node)->getMemoryVT(),
14119 Node->getOperand(0),
14120 Node->getOperand(1), negOp,
14121 cast<AtomicSDNode>(Node)->getMemOperand(),
14122 cast<AtomicSDNode>(Node)->getOrdering(),
14123 cast<AtomicSDNode>(Node)->getSynchScope());
14126 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14127 SDNode *Node = Op.getNode();
14129 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14131 // Convert seq_cst store -> xchg
14132 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14133 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14134 // (The only way to get a 16-byte store is cmpxchg16b)
14135 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14136 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14137 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14138 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14139 cast<AtomicSDNode>(Node)->getMemoryVT(),
14140 Node->getOperand(0),
14141 Node->getOperand(1), Node->getOperand(2),
14142 cast<AtomicSDNode>(Node)->getMemOperand(),
14143 cast<AtomicSDNode>(Node)->getOrdering(),
14144 cast<AtomicSDNode>(Node)->getSynchScope());
14145 return Swap.getValue(1);
14147 // Other atomic stores have a simple pattern.
14151 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14152 EVT VT = Op.getNode()->getSimpleValueType(0);
14154 // Let legalize expand this if it isn't a legal type yet.
14155 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14158 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14161 bool ExtraOp = false;
14162 switch (Op.getOpcode()) {
14163 default: llvm_unreachable("Invalid code");
14164 case ISD::ADDC: Opc = X86ISD::ADD; break;
14165 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14166 case ISD::SUBC: Opc = X86ISD::SUB; break;
14167 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14171 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14173 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14174 Op.getOperand(1), Op.getOperand(2));
14177 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14178 SelectionDAG &DAG) {
14179 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14181 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14182 // which returns the values as { float, float } (in XMM0) or
14183 // { double, double } (which is returned in XMM0, XMM1).
14185 SDValue Arg = Op.getOperand(0);
14186 EVT ArgVT = Arg.getValueType();
14187 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14189 TargetLowering::ArgListTy Args;
14190 TargetLowering::ArgListEntry Entry;
14194 Entry.isSExt = false;
14195 Entry.isZExt = false;
14196 Args.push_back(Entry);
14198 bool isF64 = ArgVT == MVT::f64;
14199 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14200 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14201 // the results are returned via SRet in memory.
14202 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14203 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14204 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14206 Type *RetTy = isF64
14207 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14208 : (Type*)VectorType::get(ArgTy, 4);
14210 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14211 false, false, false, false, 0,
14212 CallingConv::C, /*isTaillCall=*/false,
14213 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14214 Callee, Args, DAG, dl);
14215 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14218 // Returned in xmm0 and xmm1.
14219 return CallResult.first;
14221 // Returned in bits 0:31 and 32:64 xmm0.
14222 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14223 CallResult.first, DAG.getIntPtrConstant(0));
14224 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14225 CallResult.first, DAG.getIntPtrConstant(1));
14226 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14227 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14230 /// LowerOperation - Provide custom lowering hooks for some operations.
14232 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14233 switch (Op.getOpcode()) {
14234 default: llvm_unreachable("Should not custom lower this!");
14235 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14236 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14237 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14238 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14239 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14240 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14241 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14242 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14243 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14244 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14245 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14246 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14247 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14248 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14249 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14250 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14251 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14252 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14253 case ISD::SHL_PARTS:
14254 case ISD::SRA_PARTS:
14255 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14256 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14257 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14258 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14259 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14260 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14261 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14262 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14263 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14264 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14265 case ISD::FABS: return LowerFABS(Op, DAG);
14266 case ISD::FNEG: return LowerFNEG(Op, DAG);
14267 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14268 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14269 case ISD::SETCC: return LowerSETCC(Op, DAG);
14270 case ISD::SELECT: return LowerSELECT(Op, DAG);
14271 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14272 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14273 case ISD::VASTART: return LowerVASTART(Op, DAG);
14274 case ISD::VAARG: return LowerVAARG(Op, DAG);
14275 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14276 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14277 case ISD::INTRINSIC_VOID:
14278 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14279 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14280 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14281 case ISD::FRAME_TO_ARGS_OFFSET:
14282 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14283 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14284 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14285 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14286 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14287 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14288 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14289 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14290 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14291 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14292 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14293 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14294 case ISD::UMUL_LOHI:
14295 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14298 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14304 case ISD::UMULO: return LowerXALUO(Op, DAG);
14305 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14306 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14310 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14311 case ISD::ADD: return LowerADD(Op, DAG);
14312 case ISD::SUB: return LowerSUB(Op, DAG);
14313 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14317 static void ReplaceATOMIC_LOAD(SDNode *Node,
14318 SmallVectorImpl<SDValue> &Results,
14319 SelectionDAG &DAG) {
14321 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14323 // Convert wide load -> cmpxchg8b/cmpxchg16b
14324 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14325 // (The only way to get a 16-byte load is cmpxchg16b)
14326 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14327 SDValue Zero = DAG.getConstant(0, VT);
14328 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14329 Node->getOperand(0),
14330 Node->getOperand(1), Zero, Zero,
14331 cast<AtomicSDNode>(Node)->getMemOperand(),
14332 cast<AtomicSDNode>(Node)->getOrdering(),
14333 cast<AtomicSDNode>(Node)->getOrdering(),
14334 cast<AtomicSDNode>(Node)->getSynchScope());
14335 Results.push_back(Swap.getValue(0));
14336 Results.push_back(Swap.getValue(1));
14340 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14341 SelectionDAG &DAG, unsigned NewOp) {
14343 assert (Node->getValueType(0) == MVT::i64 &&
14344 "Only know how to expand i64 atomics");
14346 SDValue Chain = Node->getOperand(0);
14347 SDValue In1 = Node->getOperand(1);
14348 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14349 Node->getOperand(2), DAG.getIntPtrConstant(0));
14350 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14351 Node->getOperand(2), DAG.getIntPtrConstant(1));
14352 SDValue Ops[] = { Chain, In1, In2L, In2H };
14353 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14355 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14356 cast<MemSDNode>(Node)->getMemOperand());
14357 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14358 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14359 Results.push_back(Result.getValue(2));
14362 /// ReplaceNodeResults - Replace a node with an illegal result type
14363 /// with a new node built out of custom code.
14364 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14365 SmallVectorImpl<SDValue>&Results,
14366 SelectionDAG &DAG) const {
14368 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14369 switch (N->getOpcode()) {
14371 llvm_unreachable("Do not know how to custom type legalize this operation!");
14372 case ISD::SIGN_EXTEND_INREG:
14377 // We don't want to expand or promote these.
14384 case ISD::UDIVREM: {
14385 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14386 Results.push_back(V);
14389 case ISD::FP_TO_SINT:
14390 case ISD::FP_TO_UINT: {
14391 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14393 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14396 std::pair<SDValue,SDValue> Vals =
14397 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14398 SDValue FIST = Vals.first, StackSlot = Vals.second;
14399 if (FIST.getNode()) {
14400 EVT VT = N->getValueType(0);
14401 // Return a load from the stack slot.
14402 if (StackSlot.getNode())
14403 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14404 MachinePointerInfo(),
14405 false, false, false, 0));
14407 Results.push_back(FIST);
14411 case ISD::UINT_TO_FP: {
14412 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14413 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14414 N->getValueType(0) != MVT::v2f32)
14416 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14418 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14420 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14421 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14422 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14423 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14424 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14425 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14428 case ISD::FP_ROUND: {
14429 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14431 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14432 Results.push_back(V);
14435 case ISD::INTRINSIC_W_CHAIN: {
14436 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14438 default : llvm_unreachable("Do not know how to custom type "
14439 "legalize this intrinsic operation!");
14440 case Intrinsic::x86_rdtsc:
14441 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14443 case Intrinsic::x86_rdtscp:
14444 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14448 case ISD::READCYCLECOUNTER: {
14449 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14452 case ISD::ATOMIC_CMP_SWAP: {
14453 EVT T = N->getValueType(0);
14454 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14455 bool Regs64bit = T == MVT::i128;
14456 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14457 SDValue cpInL, cpInH;
14458 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14459 DAG.getConstant(0, HalfT));
14460 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14461 DAG.getConstant(1, HalfT));
14462 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14463 Regs64bit ? X86::RAX : X86::EAX,
14465 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14466 Regs64bit ? X86::RDX : X86::EDX,
14467 cpInH, cpInL.getValue(1));
14468 SDValue swapInL, swapInH;
14469 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14470 DAG.getConstant(0, HalfT));
14471 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14472 DAG.getConstant(1, HalfT));
14473 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14474 Regs64bit ? X86::RBX : X86::EBX,
14475 swapInL, cpInH.getValue(1));
14476 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14477 Regs64bit ? X86::RCX : X86::ECX,
14478 swapInH, swapInL.getValue(1));
14479 SDValue Ops[] = { swapInH.getValue(0),
14481 swapInH.getValue(1) };
14482 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14483 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14484 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14485 X86ISD::LCMPXCHG8_DAG;
14486 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14487 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14488 Regs64bit ? X86::RAX : X86::EAX,
14489 HalfT, Result.getValue(1));
14490 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14491 Regs64bit ? X86::RDX : X86::EDX,
14492 HalfT, cpOutL.getValue(2));
14493 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14494 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14495 Results.push_back(cpOutH.getValue(1));
14498 case ISD::ATOMIC_LOAD_ADD:
14499 case ISD::ATOMIC_LOAD_AND:
14500 case ISD::ATOMIC_LOAD_NAND:
14501 case ISD::ATOMIC_LOAD_OR:
14502 case ISD::ATOMIC_LOAD_SUB:
14503 case ISD::ATOMIC_LOAD_XOR:
14504 case ISD::ATOMIC_LOAD_MAX:
14505 case ISD::ATOMIC_LOAD_MIN:
14506 case ISD::ATOMIC_LOAD_UMAX:
14507 case ISD::ATOMIC_LOAD_UMIN:
14508 case ISD::ATOMIC_SWAP: {
14510 switch (N->getOpcode()) {
14511 default: llvm_unreachable("Unexpected opcode");
14512 case ISD::ATOMIC_LOAD_ADD:
14513 Opc = X86ISD::ATOMADD64_DAG;
14515 case ISD::ATOMIC_LOAD_AND:
14516 Opc = X86ISD::ATOMAND64_DAG;
14518 case ISD::ATOMIC_LOAD_NAND:
14519 Opc = X86ISD::ATOMNAND64_DAG;
14521 case ISD::ATOMIC_LOAD_OR:
14522 Opc = X86ISD::ATOMOR64_DAG;
14524 case ISD::ATOMIC_LOAD_SUB:
14525 Opc = X86ISD::ATOMSUB64_DAG;
14527 case ISD::ATOMIC_LOAD_XOR:
14528 Opc = X86ISD::ATOMXOR64_DAG;
14530 case ISD::ATOMIC_LOAD_MAX:
14531 Opc = X86ISD::ATOMMAX64_DAG;
14533 case ISD::ATOMIC_LOAD_MIN:
14534 Opc = X86ISD::ATOMMIN64_DAG;
14536 case ISD::ATOMIC_LOAD_UMAX:
14537 Opc = X86ISD::ATOMUMAX64_DAG;
14539 case ISD::ATOMIC_LOAD_UMIN:
14540 Opc = X86ISD::ATOMUMIN64_DAG;
14542 case ISD::ATOMIC_SWAP:
14543 Opc = X86ISD::ATOMSWAP64_DAG;
14546 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14549 case ISD::ATOMIC_LOAD:
14550 ReplaceATOMIC_LOAD(N, Results, DAG);
14554 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14556 default: return nullptr;
14557 case X86ISD::BSF: return "X86ISD::BSF";
14558 case X86ISD::BSR: return "X86ISD::BSR";
14559 case X86ISD::SHLD: return "X86ISD::SHLD";
14560 case X86ISD::SHRD: return "X86ISD::SHRD";
14561 case X86ISD::FAND: return "X86ISD::FAND";
14562 case X86ISD::FANDN: return "X86ISD::FANDN";
14563 case X86ISD::FOR: return "X86ISD::FOR";
14564 case X86ISD::FXOR: return "X86ISD::FXOR";
14565 case X86ISD::FSRL: return "X86ISD::FSRL";
14566 case X86ISD::FILD: return "X86ISD::FILD";
14567 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14568 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14569 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14570 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14571 case X86ISD::FLD: return "X86ISD::FLD";
14572 case X86ISD::FST: return "X86ISD::FST";
14573 case X86ISD::CALL: return "X86ISD::CALL";
14574 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14575 case X86ISD::BT: return "X86ISD::BT";
14576 case X86ISD::CMP: return "X86ISD::CMP";
14577 case X86ISD::COMI: return "X86ISD::COMI";
14578 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14579 case X86ISD::CMPM: return "X86ISD::CMPM";
14580 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14581 case X86ISD::SETCC: return "X86ISD::SETCC";
14582 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14583 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14584 case X86ISD::CMOV: return "X86ISD::CMOV";
14585 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14586 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14587 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14588 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14589 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14590 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14591 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14592 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14593 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14594 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14595 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14596 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14597 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14598 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14599 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14600 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14601 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14602 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14603 case X86ISD::HADD: return "X86ISD::HADD";
14604 case X86ISD::HSUB: return "X86ISD::HSUB";
14605 case X86ISD::FHADD: return "X86ISD::FHADD";
14606 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14607 case X86ISD::UMAX: return "X86ISD::UMAX";
14608 case X86ISD::UMIN: return "X86ISD::UMIN";
14609 case X86ISD::SMAX: return "X86ISD::SMAX";
14610 case X86ISD::SMIN: return "X86ISD::SMIN";
14611 case X86ISD::FMAX: return "X86ISD::FMAX";
14612 case X86ISD::FMIN: return "X86ISD::FMIN";
14613 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14614 case X86ISD::FMINC: return "X86ISD::FMINC";
14615 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14616 case X86ISD::FRCP: return "X86ISD::FRCP";
14617 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14618 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14619 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14620 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14621 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14622 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14623 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14624 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14625 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14626 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14627 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14628 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14629 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14630 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14631 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14632 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14633 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14634 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14635 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14636 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14637 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14638 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14639 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14640 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14641 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14642 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14643 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14644 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14645 case X86ISD::VSHL: return "X86ISD::VSHL";
14646 case X86ISD::VSRL: return "X86ISD::VSRL";
14647 case X86ISD::VSRA: return "X86ISD::VSRA";
14648 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14649 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14650 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14651 case X86ISD::CMPP: return "X86ISD::CMPP";
14652 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14653 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14654 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14655 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14656 case X86ISD::ADD: return "X86ISD::ADD";
14657 case X86ISD::SUB: return "X86ISD::SUB";
14658 case X86ISD::ADC: return "X86ISD::ADC";
14659 case X86ISD::SBB: return "X86ISD::SBB";
14660 case X86ISD::SMUL: return "X86ISD::SMUL";
14661 case X86ISD::UMUL: return "X86ISD::UMUL";
14662 case X86ISD::INC: return "X86ISD::INC";
14663 case X86ISD::DEC: return "X86ISD::DEC";
14664 case X86ISD::OR: return "X86ISD::OR";
14665 case X86ISD::XOR: return "X86ISD::XOR";
14666 case X86ISD::AND: return "X86ISD::AND";
14667 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14668 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14669 case X86ISD::PTEST: return "X86ISD::PTEST";
14670 case X86ISD::TESTP: return "X86ISD::TESTP";
14671 case X86ISD::TESTM: return "X86ISD::TESTM";
14672 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14673 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14674 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14675 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14676 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14677 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14678 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14679 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14680 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14681 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14682 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14683 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14684 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14685 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14686 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14687 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14688 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14689 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14690 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14691 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14692 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14693 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14694 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14695 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14696 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14697 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14698 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14699 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14700 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14701 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14702 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14703 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14704 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14705 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14706 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14707 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14708 case X86ISD::SAHF: return "X86ISD::SAHF";
14709 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14710 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14711 case X86ISD::FMADD: return "X86ISD::FMADD";
14712 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14713 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14714 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14715 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14716 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14717 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14718 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14719 case X86ISD::XTEST: return "X86ISD::XTEST";
14723 // isLegalAddressingMode - Return true if the addressing mode represented
14724 // by AM is legal for this target, for a load/store of the specified type.
14725 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14727 // X86 supports extremely general addressing modes.
14728 CodeModel::Model M = getTargetMachine().getCodeModel();
14729 Reloc::Model R = getTargetMachine().getRelocationModel();
14731 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14732 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14737 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14739 // If a reference to this global requires an extra load, we can't fold it.
14740 if (isGlobalStubReference(GVFlags))
14743 // If BaseGV requires a register for the PIC base, we cannot also have a
14744 // BaseReg specified.
14745 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14748 // If lower 4G is not available, then we must use rip-relative addressing.
14749 if ((M != CodeModel::Small || R != Reloc::Static) &&
14750 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14754 switch (AM.Scale) {
14760 // These scales always work.
14765 // These scales are formed with basereg+scalereg. Only accept if there is
14770 default: // Other stuff never works.
14777 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14778 unsigned Bits = Ty->getScalarSizeInBits();
14780 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14781 // particularly cheaper than those without.
14785 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14786 // variable shifts just as cheap as scalar ones.
14787 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14790 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14791 // fully general vector.
14795 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14796 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14798 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14799 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14800 return NumBits1 > NumBits2;
14803 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14804 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14807 if (!isTypeLegal(EVT::getEVT(Ty1)))
14810 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14812 // Assuming the caller doesn't have a zeroext or signext return parameter,
14813 // truncation all the way down to i1 is valid.
14817 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14818 return isInt<32>(Imm);
14821 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14822 // Can also use sub to handle negated immediates.
14823 return isInt<32>(Imm);
14826 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14827 if (!VT1.isInteger() || !VT2.isInteger())
14829 unsigned NumBits1 = VT1.getSizeInBits();
14830 unsigned NumBits2 = VT2.getSizeInBits();
14831 return NumBits1 > NumBits2;
14834 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14835 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14836 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14839 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14840 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14841 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14844 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14845 EVT VT1 = Val.getValueType();
14846 if (isZExtFree(VT1, VT2))
14849 if (Val.getOpcode() != ISD::LOAD)
14852 if (!VT1.isSimple() || !VT1.isInteger() ||
14853 !VT2.isSimple() || !VT2.isInteger())
14856 switch (VT1.getSimpleVT().SimpleTy) {
14861 // X86 has 8, 16, and 32-bit zero-extending loads.
14869 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14870 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14873 VT = VT.getScalarType();
14875 if (!VT.isSimple())
14878 switch (VT.getSimpleVT().SimpleTy) {
14889 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14890 // i16 instructions are longer (0x66 prefix) and potentially slower.
14891 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14894 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14895 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14896 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14897 /// are assumed to be legal.
14899 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14901 if (!VT.isSimple())
14904 MVT SVT = VT.getSimpleVT();
14906 // Very little shuffling can be done for 64-bit vectors right now.
14907 if (VT.getSizeInBits() == 64)
14910 // FIXME: pshufb, blends, shifts.
14911 return (SVT.getVectorNumElements() == 2 ||
14912 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14913 isMOVLMask(M, SVT) ||
14914 isSHUFPMask(M, SVT) ||
14915 isPSHUFDMask(M, SVT) ||
14916 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14917 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14918 isPALIGNRMask(M, SVT, Subtarget) ||
14919 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14920 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14921 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14922 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14926 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14928 if (!VT.isSimple())
14931 MVT SVT = VT.getSimpleVT();
14932 unsigned NumElts = SVT.getVectorNumElements();
14933 // FIXME: This collection of masks seems suspect.
14936 if (NumElts == 4 && SVT.is128BitVector()) {
14937 return (isMOVLMask(Mask, SVT) ||
14938 isCommutedMOVLMask(Mask, SVT, true) ||
14939 isSHUFPMask(Mask, SVT) ||
14940 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14945 //===----------------------------------------------------------------------===//
14946 // X86 Scheduler Hooks
14947 //===----------------------------------------------------------------------===//
14949 /// Utility function to emit xbegin specifying the start of an RTM region.
14950 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14951 const TargetInstrInfo *TII) {
14952 DebugLoc DL = MI->getDebugLoc();
14954 const BasicBlock *BB = MBB->getBasicBlock();
14955 MachineFunction::iterator I = MBB;
14958 // For the v = xbegin(), we generate
14969 MachineBasicBlock *thisMBB = MBB;
14970 MachineFunction *MF = MBB->getParent();
14971 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14972 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14973 MF->insert(I, mainMBB);
14974 MF->insert(I, sinkMBB);
14976 // Transfer the remainder of BB and its successor edges to sinkMBB.
14977 sinkMBB->splice(sinkMBB->begin(), MBB,
14978 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14979 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14983 // # fallthrough to mainMBB
14984 // # abortion to sinkMBB
14985 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14986 thisMBB->addSuccessor(mainMBB);
14987 thisMBB->addSuccessor(sinkMBB);
14991 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14992 mainMBB->addSuccessor(sinkMBB);
14995 // EAX is live into the sinkMBB
14996 sinkMBB->addLiveIn(X86::EAX);
14997 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14998 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15001 MI->eraseFromParent();
15005 // Get CMPXCHG opcode for the specified data type.
15006 static unsigned getCmpXChgOpcode(EVT VT) {
15007 switch (VT.getSimpleVT().SimpleTy) {
15008 case MVT::i8: return X86::LCMPXCHG8;
15009 case MVT::i16: return X86::LCMPXCHG16;
15010 case MVT::i32: return X86::LCMPXCHG32;
15011 case MVT::i64: return X86::LCMPXCHG64;
15015 llvm_unreachable("Invalid operand size!");
15018 // Get LOAD opcode for the specified data type.
15019 static unsigned getLoadOpcode(EVT VT) {
15020 switch (VT.getSimpleVT().SimpleTy) {
15021 case MVT::i8: return X86::MOV8rm;
15022 case MVT::i16: return X86::MOV16rm;
15023 case MVT::i32: return X86::MOV32rm;
15024 case MVT::i64: return X86::MOV64rm;
15028 llvm_unreachable("Invalid operand size!");
15031 // Get opcode of the non-atomic one from the specified atomic instruction.
15032 static unsigned getNonAtomicOpcode(unsigned Opc) {
15034 case X86::ATOMAND8: return X86::AND8rr;
15035 case X86::ATOMAND16: return X86::AND16rr;
15036 case X86::ATOMAND32: return X86::AND32rr;
15037 case X86::ATOMAND64: return X86::AND64rr;
15038 case X86::ATOMOR8: return X86::OR8rr;
15039 case X86::ATOMOR16: return X86::OR16rr;
15040 case X86::ATOMOR32: return X86::OR32rr;
15041 case X86::ATOMOR64: return X86::OR64rr;
15042 case X86::ATOMXOR8: return X86::XOR8rr;
15043 case X86::ATOMXOR16: return X86::XOR16rr;
15044 case X86::ATOMXOR32: return X86::XOR32rr;
15045 case X86::ATOMXOR64: return X86::XOR64rr;
15047 llvm_unreachable("Unhandled atomic-load-op opcode!");
15050 // Get opcode of the non-atomic one from the specified atomic instruction with
15052 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15053 unsigned &ExtraOpc) {
15055 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15056 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15057 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15058 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15059 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15060 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15061 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15062 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15063 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15064 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15065 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15066 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15067 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15068 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15069 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15070 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15071 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15072 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15073 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15074 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15076 llvm_unreachable("Unhandled atomic-load-op opcode!");
15079 // Get opcode of the non-atomic one from the specified atomic instruction for
15080 // 64-bit data type on 32-bit target.
15081 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15083 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15084 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15085 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15086 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15087 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15088 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15089 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15090 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15091 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15092 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15094 llvm_unreachable("Unhandled atomic-load-op opcode!");
15097 // Get opcode of the non-atomic one from the specified atomic instruction for
15098 // 64-bit data type on 32-bit target with extra opcode.
15099 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15101 unsigned &ExtraOpc) {
15103 case X86::ATOMNAND6432:
15104 ExtraOpc = X86::NOT32r;
15105 HiOpc = X86::AND32rr;
15106 return X86::AND32rr;
15108 llvm_unreachable("Unhandled atomic-load-op opcode!");
15111 // Get pseudo CMOV opcode from the specified data type.
15112 static unsigned getPseudoCMOVOpc(EVT VT) {
15113 switch (VT.getSimpleVT().SimpleTy) {
15114 case MVT::i8: return X86::CMOV_GR8;
15115 case MVT::i16: return X86::CMOV_GR16;
15116 case MVT::i32: return X86::CMOV_GR32;
15120 llvm_unreachable("Unknown CMOV opcode!");
15123 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15124 // They will be translated into a spin-loop or compare-exchange loop from
15127 // dst = atomic-fetch-op MI.addr, MI.val
15133 // t1 = LOAD MI.addr
15135 // t4 = phi(t1, t3 / loop)
15136 // t2 = OP MI.val, t4
15138 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15144 MachineBasicBlock *
15145 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15146 MachineBasicBlock *MBB) const {
15147 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15148 DebugLoc DL = MI->getDebugLoc();
15150 MachineFunction *MF = MBB->getParent();
15151 MachineRegisterInfo &MRI = MF->getRegInfo();
15153 const BasicBlock *BB = MBB->getBasicBlock();
15154 MachineFunction::iterator I = MBB;
15157 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15158 "Unexpected number of operands");
15160 assert(MI->hasOneMemOperand() &&
15161 "Expected atomic-load-op to have one memoperand");
15163 // Memory Reference
15164 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15165 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15167 unsigned DstReg, SrcReg;
15168 unsigned MemOpndSlot;
15170 unsigned CurOp = 0;
15172 DstReg = MI->getOperand(CurOp++).getReg();
15173 MemOpndSlot = CurOp;
15174 CurOp += X86::AddrNumOperands;
15175 SrcReg = MI->getOperand(CurOp++).getReg();
15177 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15178 MVT::SimpleValueType VT = *RC->vt_begin();
15179 unsigned t1 = MRI.createVirtualRegister(RC);
15180 unsigned t2 = MRI.createVirtualRegister(RC);
15181 unsigned t3 = MRI.createVirtualRegister(RC);
15182 unsigned t4 = MRI.createVirtualRegister(RC);
15183 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15185 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15186 unsigned LOADOpc = getLoadOpcode(VT);
15188 // For the atomic load-arith operator, we generate
15191 // t1 = LOAD [MI.addr]
15193 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15194 // t1 = OP MI.val, EAX
15196 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15202 MachineBasicBlock *thisMBB = MBB;
15203 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15204 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15205 MF->insert(I, mainMBB);
15206 MF->insert(I, sinkMBB);
15208 MachineInstrBuilder MIB;
15210 // Transfer the remainder of BB and its successor edges to sinkMBB.
15211 sinkMBB->splice(sinkMBB->begin(), MBB,
15212 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15213 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15216 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15217 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15218 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15220 NewMO.setIsKill(false);
15221 MIB.addOperand(NewMO);
15223 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15224 unsigned flags = (*MMOI)->getFlags();
15225 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15226 MachineMemOperand *MMO =
15227 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15228 (*MMOI)->getSize(),
15229 (*MMOI)->getBaseAlignment(),
15230 (*MMOI)->getTBAAInfo(),
15231 (*MMOI)->getRanges());
15232 MIB.addMemOperand(MMO);
15235 thisMBB->addSuccessor(mainMBB);
15238 MachineBasicBlock *origMainMBB = mainMBB;
15241 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15242 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15244 unsigned Opc = MI->getOpcode();
15247 llvm_unreachable("Unhandled atomic-load-op opcode!");
15248 case X86::ATOMAND8:
15249 case X86::ATOMAND16:
15250 case X86::ATOMAND32:
15251 case X86::ATOMAND64:
15253 case X86::ATOMOR16:
15254 case X86::ATOMOR32:
15255 case X86::ATOMOR64:
15256 case X86::ATOMXOR8:
15257 case X86::ATOMXOR16:
15258 case X86::ATOMXOR32:
15259 case X86::ATOMXOR64: {
15260 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15261 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15265 case X86::ATOMNAND8:
15266 case X86::ATOMNAND16:
15267 case X86::ATOMNAND32:
15268 case X86::ATOMNAND64: {
15269 unsigned Tmp = MRI.createVirtualRegister(RC);
15271 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15272 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15274 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15277 case X86::ATOMMAX8:
15278 case X86::ATOMMAX16:
15279 case X86::ATOMMAX32:
15280 case X86::ATOMMAX64:
15281 case X86::ATOMMIN8:
15282 case X86::ATOMMIN16:
15283 case X86::ATOMMIN32:
15284 case X86::ATOMMIN64:
15285 case X86::ATOMUMAX8:
15286 case X86::ATOMUMAX16:
15287 case X86::ATOMUMAX32:
15288 case X86::ATOMUMAX64:
15289 case X86::ATOMUMIN8:
15290 case X86::ATOMUMIN16:
15291 case X86::ATOMUMIN32:
15292 case X86::ATOMUMIN64: {
15294 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15296 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15300 if (Subtarget->hasCMov()) {
15301 if (VT != MVT::i8) {
15303 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15307 // Promote i8 to i32 to use CMOV32
15308 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15309 const TargetRegisterClass *RC32 =
15310 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15311 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15312 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15313 unsigned Tmp = MRI.createVirtualRegister(RC32);
15315 unsigned Undef = MRI.createVirtualRegister(RC32);
15316 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15318 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15321 .addImm(X86::sub_8bit);
15322 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15325 .addImm(X86::sub_8bit);
15327 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15331 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15332 .addReg(Tmp, 0, X86::sub_8bit);
15335 // Use pseudo select and lower them.
15336 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15337 "Invalid atomic-load-op transformation!");
15338 unsigned SelOpc = getPseudoCMOVOpc(VT);
15339 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15340 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15341 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15342 .addReg(SrcReg).addReg(t4)
15344 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15345 // Replace the original PHI node as mainMBB is changed after CMOV
15347 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15348 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15349 Phi->eraseFromParent();
15355 // Copy PhyReg back from virtual register.
15356 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15359 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15360 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15361 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15363 NewMO.setIsKill(false);
15364 MIB.addOperand(NewMO);
15367 MIB.setMemRefs(MMOBegin, MMOEnd);
15369 // Copy PhyReg back to virtual register.
15370 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15373 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15375 mainMBB->addSuccessor(origMainMBB);
15376 mainMBB->addSuccessor(sinkMBB);
15379 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15380 TII->get(TargetOpcode::COPY), DstReg)
15383 MI->eraseFromParent();
15387 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15388 // instructions. They will be translated into a spin-loop or compare-exchange
15392 // dst = atomic-fetch-op MI.addr, MI.val
15398 // t1L = LOAD [MI.addr + 0]
15399 // t1H = LOAD [MI.addr + 4]
15401 // t4L = phi(t1L, t3L / loop)
15402 // t4H = phi(t1H, t3H / loop)
15403 // t2L = OP MI.val.lo, t4L
15404 // t2H = OP MI.val.hi, t4H
15409 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15417 MachineBasicBlock *
15418 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15419 MachineBasicBlock *MBB) const {
15420 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15421 DebugLoc DL = MI->getDebugLoc();
15423 MachineFunction *MF = MBB->getParent();
15424 MachineRegisterInfo &MRI = MF->getRegInfo();
15426 const BasicBlock *BB = MBB->getBasicBlock();
15427 MachineFunction::iterator I = MBB;
15430 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15431 "Unexpected number of operands");
15433 assert(MI->hasOneMemOperand() &&
15434 "Expected atomic-load-op32 to have one memoperand");
15436 // Memory Reference
15437 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15438 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15440 unsigned DstLoReg, DstHiReg;
15441 unsigned SrcLoReg, SrcHiReg;
15442 unsigned MemOpndSlot;
15444 unsigned CurOp = 0;
15446 DstLoReg = MI->getOperand(CurOp++).getReg();
15447 DstHiReg = MI->getOperand(CurOp++).getReg();
15448 MemOpndSlot = CurOp;
15449 CurOp += X86::AddrNumOperands;
15450 SrcLoReg = MI->getOperand(CurOp++).getReg();
15451 SrcHiReg = MI->getOperand(CurOp++).getReg();
15453 const TargetRegisterClass *RC = &X86::GR32RegClass;
15454 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15456 unsigned t1L = MRI.createVirtualRegister(RC);
15457 unsigned t1H = MRI.createVirtualRegister(RC);
15458 unsigned t2L = MRI.createVirtualRegister(RC);
15459 unsigned t2H = MRI.createVirtualRegister(RC);
15460 unsigned t3L = MRI.createVirtualRegister(RC);
15461 unsigned t3H = MRI.createVirtualRegister(RC);
15462 unsigned t4L = MRI.createVirtualRegister(RC);
15463 unsigned t4H = MRI.createVirtualRegister(RC);
15465 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15466 unsigned LOADOpc = X86::MOV32rm;
15468 // For the atomic load-arith operator, we generate
15471 // t1L = LOAD [MI.addr + 0]
15472 // t1H = LOAD [MI.addr + 4]
15474 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15475 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15476 // t2L = OP MI.val.lo, t4L
15477 // t2H = OP MI.val.hi, t4H
15480 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15488 MachineBasicBlock *thisMBB = MBB;
15489 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15490 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15491 MF->insert(I, mainMBB);
15492 MF->insert(I, sinkMBB);
15494 MachineInstrBuilder MIB;
15496 // Transfer the remainder of BB and its successor edges to sinkMBB.
15497 sinkMBB->splice(sinkMBB->begin(), MBB,
15498 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15499 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15503 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15504 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15505 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15507 NewMO.setIsKill(false);
15508 MIB.addOperand(NewMO);
15510 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15511 unsigned flags = (*MMOI)->getFlags();
15512 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15513 MachineMemOperand *MMO =
15514 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15515 (*MMOI)->getSize(),
15516 (*MMOI)->getBaseAlignment(),
15517 (*MMOI)->getTBAAInfo(),
15518 (*MMOI)->getRanges());
15519 MIB.addMemOperand(MMO);
15521 MachineInstr *LowMI = MIB;
15524 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15525 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15526 if (i == X86::AddrDisp) {
15527 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15529 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15531 NewMO.setIsKill(false);
15532 MIB.addOperand(NewMO);
15535 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15537 thisMBB->addSuccessor(mainMBB);
15540 MachineBasicBlock *origMainMBB = mainMBB;
15543 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15544 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15545 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15546 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15548 unsigned Opc = MI->getOpcode();
15551 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15552 case X86::ATOMAND6432:
15553 case X86::ATOMOR6432:
15554 case X86::ATOMXOR6432:
15555 case X86::ATOMADD6432:
15556 case X86::ATOMSUB6432: {
15558 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15559 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15561 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15565 case X86::ATOMNAND6432: {
15566 unsigned HiOpc, NOTOpc;
15567 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15568 unsigned TmpL = MRI.createVirtualRegister(RC);
15569 unsigned TmpH = MRI.createVirtualRegister(RC);
15570 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15572 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15574 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15575 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15578 case X86::ATOMMAX6432:
15579 case X86::ATOMMIN6432:
15580 case X86::ATOMUMAX6432:
15581 case X86::ATOMUMIN6432: {
15583 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15584 unsigned cL = MRI.createVirtualRegister(RC8);
15585 unsigned cH = MRI.createVirtualRegister(RC8);
15586 unsigned cL32 = MRI.createVirtualRegister(RC);
15587 unsigned cH32 = MRI.createVirtualRegister(RC);
15588 unsigned cc = MRI.createVirtualRegister(RC);
15589 // cl := cmp src_lo, lo
15590 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15591 .addReg(SrcLoReg).addReg(t4L);
15592 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15593 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15594 // ch := cmp src_hi, hi
15595 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15596 .addReg(SrcHiReg).addReg(t4H);
15597 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15598 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15599 // cc := if (src_hi == hi) ? cl : ch;
15600 if (Subtarget->hasCMov()) {
15601 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15602 .addReg(cH32).addReg(cL32);
15604 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15605 .addReg(cH32).addReg(cL32)
15606 .addImm(X86::COND_E);
15607 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15609 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15610 if (Subtarget->hasCMov()) {
15611 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15612 .addReg(SrcLoReg).addReg(t4L);
15613 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15614 .addReg(SrcHiReg).addReg(t4H);
15616 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15617 .addReg(SrcLoReg).addReg(t4L)
15618 .addImm(X86::COND_NE);
15619 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15620 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15621 // 2nd CMOV lowering.
15622 mainMBB->addLiveIn(X86::EFLAGS);
15623 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15624 .addReg(SrcHiReg).addReg(t4H)
15625 .addImm(X86::COND_NE);
15626 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15627 // Replace the original PHI node as mainMBB is changed after CMOV
15629 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15630 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15631 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15632 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15633 PhiL->eraseFromParent();
15634 PhiH->eraseFromParent();
15638 case X86::ATOMSWAP6432: {
15640 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15641 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15642 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15647 // Copy EDX:EAX back from HiReg:LoReg
15648 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15649 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15650 // Copy ECX:EBX from t1H:t1L
15651 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15652 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15654 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15655 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15656 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15658 NewMO.setIsKill(false);
15659 MIB.addOperand(NewMO);
15661 MIB.setMemRefs(MMOBegin, MMOEnd);
15663 // Copy EDX:EAX back to t3H:t3L
15664 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15665 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15667 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15669 mainMBB->addSuccessor(origMainMBB);
15670 mainMBB->addSuccessor(sinkMBB);
15673 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15674 TII->get(TargetOpcode::COPY), DstLoReg)
15676 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15677 TII->get(TargetOpcode::COPY), DstHiReg)
15680 MI->eraseFromParent();
15684 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15685 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15686 // in the .td file.
15687 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15688 const TargetInstrInfo *TII) {
15690 switch (MI->getOpcode()) {
15691 default: llvm_unreachable("illegal opcode!");
15692 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15693 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15694 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15695 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15696 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15697 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15698 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15699 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15702 DebugLoc dl = MI->getDebugLoc();
15703 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15705 unsigned NumArgs = MI->getNumOperands();
15706 for (unsigned i = 1; i < NumArgs; ++i) {
15707 MachineOperand &Op = MI->getOperand(i);
15708 if (!(Op.isReg() && Op.isImplicit()))
15709 MIB.addOperand(Op);
15711 if (MI->hasOneMemOperand())
15712 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15714 BuildMI(*BB, MI, dl,
15715 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15716 .addReg(X86::XMM0);
15718 MI->eraseFromParent();
15722 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15723 // defs in an instruction pattern
15724 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15725 const TargetInstrInfo *TII) {
15727 switch (MI->getOpcode()) {
15728 default: llvm_unreachable("illegal opcode!");
15729 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15730 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15731 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15732 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15733 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15734 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15735 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15736 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15739 DebugLoc dl = MI->getDebugLoc();
15740 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15742 unsigned NumArgs = MI->getNumOperands(); // remove the results
15743 for (unsigned i = 1; i < NumArgs; ++i) {
15744 MachineOperand &Op = MI->getOperand(i);
15745 if (!(Op.isReg() && Op.isImplicit()))
15746 MIB.addOperand(Op);
15748 if (MI->hasOneMemOperand())
15749 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15751 BuildMI(*BB, MI, dl,
15752 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15755 MI->eraseFromParent();
15759 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15760 const TargetInstrInfo *TII,
15761 const X86Subtarget* Subtarget) {
15762 DebugLoc dl = MI->getDebugLoc();
15764 // Address into RAX/EAX, other two args into ECX, EDX.
15765 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15766 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15767 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15768 for (int i = 0; i < X86::AddrNumOperands; ++i)
15769 MIB.addOperand(MI->getOperand(i));
15771 unsigned ValOps = X86::AddrNumOperands;
15772 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15773 .addReg(MI->getOperand(ValOps).getReg());
15774 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15775 .addReg(MI->getOperand(ValOps+1).getReg());
15777 // The instruction doesn't actually take any operands though.
15778 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15780 MI->eraseFromParent(); // The pseudo is gone now.
15784 MachineBasicBlock *
15785 X86TargetLowering::EmitVAARG64WithCustomInserter(
15787 MachineBasicBlock *MBB) const {
15788 // Emit va_arg instruction on X86-64.
15790 // Operands to this pseudo-instruction:
15791 // 0 ) Output : destination address (reg)
15792 // 1-5) Input : va_list address (addr, i64mem)
15793 // 6 ) ArgSize : Size (in bytes) of vararg type
15794 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15795 // 8 ) Align : Alignment of type
15796 // 9 ) EFLAGS (implicit-def)
15798 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15799 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15801 unsigned DestReg = MI->getOperand(0).getReg();
15802 MachineOperand &Base = MI->getOperand(1);
15803 MachineOperand &Scale = MI->getOperand(2);
15804 MachineOperand &Index = MI->getOperand(3);
15805 MachineOperand &Disp = MI->getOperand(4);
15806 MachineOperand &Segment = MI->getOperand(5);
15807 unsigned ArgSize = MI->getOperand(6).getImm();
15808 unsigned ArgMode = MI->getOperand(7).getImm();
15809 unsigned Align = MI->getOperand(8).getImm();
15811 // Memory Reference
15812 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15813 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15814 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15816 // Machine Information
15817 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15818 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15819 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15820 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15821 DebugLoc DL = MI->getDebugLoc();
15823 // struct va_list {
15826 // i64 overflow_area (address)
15827 // i64 reg_save_area (address)
15829 // sizeof(va_list) = 24
15830 // alignment(va_list) = 8
15832 unsigned TotalNumIntRegs = 6;
15833 unsigned TotalNumXMMRegs = 8;
15834 bool UseGPOffset = (ArgMode == 1);
15835 bool UseFPOffset = (ArgMode == 2);
15836 unsigned MaxOffset = TotalNumIntRegs * 8 +
15837 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15839 /* Align ArgSize to a multiple of 8 */
15840 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15841 bool NeedsAlign = (Align > 8);
15843 MachineBasicBlock *thisMBB = MBB;
15844 MachineBasicBlock *overflowMBB;
15845 MachineBasicBlock *offsetMBB;
15846 MachineBasicBlock *endMBB;
15848 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15849 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15850 unsigned OffsetReg = 0;
15852 if (!UseGPOffset && !UseFPOffset) {
15853 // If we only pull from the overflow region, we don't create a branch.
15854 // We don't need to alter control flow.
15855 OffsetDestReg = 0; // unused
15856 OverflowDestReg = DestReg;
15858 offsetMBB = nullptr;
15859 overflowMBB = thisMBB;
15862 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15863 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15864 // If not, pull from overflow_area. (branch to overflowMBB)
15869 // offsetMBB overflowMBB
15874 // Registers for the PHI in endMBB
15875 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15876 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15878 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15879 MachineFunction *MF = MBB->getParent();
15880 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15881 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15882 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15884 MachineFunction::iterator MBBIter = MBB;
15887 // Insert the new basic blocks
15888 MF->insert(MBBIter, offsetMBB);
15889 MF->insert(MBBIter, overflowMBB);
15890 MF->insert(MBBIter, endMBB);
15892 // Transfer the remainder of MBB and its successor edges to endMBB.
15893 endMBB->splice(endMBB->begin(), thisMBB,
15894 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15895 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15897 // Make offsetMBB and overflowMBB successors of thisMBB
15898 thisMBB->addSuccessor(offsetMBB);
15899 thisMBB->addSuccessor(overflowMBB);
15901 // endMBB is a successor of both offsetMBB and overflowMBB
15902 offsetMBB->addSuccessor(endMBB);
15903 overflowMBB->addSuccessor(endMBB);
15905 // Load the offset value into a register
15906 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15907 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15911 .addDisp(Disp, UseFPOffset ? 4 : 0)
15912 .addOperand(Segment)
15913 .setMemRefs(MMOBegin, MMOEnd);
15915 // Check if there is enough room left to pull this argument.
15916 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15918 .addImm(MaxOffset + 8 - ArgSizeA8);
15920 // Branch to "overflowMBB" if offset >= max
15921 // Fall through to "offsetMBB" otherwise
15922 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15923 .addMBB(overflowMBB);
15926 // In offsetMBB, emit code to use the reg_save_area.
15928 assert(OffsetReg != 0);
15930 // Read the reg_save_area address.
15931 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15932 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15937 .addOperand(Segment)
15938 .setMemRefs(MMOBegin, MMOEnd);
15940 // Zero-extend the offset
15941 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15942 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15945 .addImm(X86::sub_32bit);
15947 // Add the offset to the reg_save_area to get the final address.
15948 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15949 .addReg(OffsetReg64)
15950 .addReg(RegSaveReg);
15952 // Compute the offset for the next argument
15953 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15954 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15956 .addImm(UseFPOffset ? 16 : 8);
15958 // Store it back into the va_list.
15959 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15963 .addDisp(Disp, UseFPOffset ? 4 : 0)
15964 .addOperand(Segment)
15965 .addReg(NextOffsetReg)
15966 .setMemRefs(MMOBegin, MMOEnd);
15969 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15974 // Emit code to use overflow area
15977 // Load the overflow_area address into a register.
15978 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15979 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15984 .addOperand(Segment)
15985 .setMemRefs(MMOBegin, MMOEnd);
15987 // If we need to align it, do so. Otherwise, just copy the address
15988 // to OverflowDestReg.
15990 // Align the overflow address
15991 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15992 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15994 // aligned_addr = (addr + (align-1)) & ~(align-1)
15995 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15996 .addReg(OverflowAddrReg)
15999 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16001 .addImm(~(uint64_t)(Align-1));
16003 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16004 .addReg(OverflowAddrReg);
16007 // Compute the next overflow address after this argument.
16008 // (the overflow address should be kept 8-byte aligned)
16009 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16010 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16011 .addReg(OverflowDestReg)
16012 .addImm(ArgSizeA8);
16014 // Store the new overflow address.
16015 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16020 .addOperand(Segment)
16021 .addReg(NextAddrReg)
16022 .setMemRefs(MMOBegin, MMOEnd);
16024 // If we branched, emit the PHI to the front of endMBB.
16026 BuildMI(*endMBB, endMBB->begin(), DL,
16027 TII->get(X86::PHI), DestReg)
16028 .addReg(OffsetDestReg).addMBB(offsetMBB)
16029 .addReg(OverflowDestReg).addMBB(overflowMBB);
16032 // Erase the pseudo instruction
16033 MI->eraseFromParent();
16038 MachineBasicBlock *
16039 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16041 MachineBasicBlock *MBB) const {
16042 // Emit code to save XMM registers to the stack. The ABI says that the
16043 // number of registers to save is given in %al, so it's theoretically
16044 // possible to do an indirect jump trick to avoid saving all of them,
16045 // however this code takes a simpler approach and just executes all
16046 // of the stores if %al is non-zero. It's less code, and it's probably
16047 // easier on the hardware branch predictor, and stores aren't all that
16048 // expensive anyway.
16050 // Create the new basic blocks. One block contains all the XMM stores,
16051 // and one block is the final destination regardless of whether any
16052 // stores were performed.
16053 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16054 MachineFunction *F = MBB->getParent();
16055 MachineFunction::iterator MBBIter = MBB;
16057 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16058 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16059 F->insert(MBBIter, XMMSaveMBB);
16060 F->insert(MBBIter, EndMBB);
16062 // Transfer the remainder of MBB and its successor edges to EndMBB.
16063 EndMBB->splice(EndMBB->begin(), MBB,
16064 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16065 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16067 // The original block will now fall through to the XMM save block.
16068 MBB->addSuccessor(XMMSaveMBB);
16069 // The XMMSaveMBB will fall through to the end block.
16070 XMMSaveMBB->addSuccessor(EndMBB);
16072 // Now add the instructions.
16073 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16074 DebugLoc DL = MI->getDebugLoc();
16076 unsigned CountReg = MI->getOperand(0).getReg();
16077 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16078 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16080 if (!Subtarget->isTargetWin64()) {
16081 // If %al is 0, branch around the XMM save block.
16082 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16083 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16084 MBB->addSuccessor(EndMBB);
16087 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16088 // that was just emitted, but clearly shouldn't be "saved".
16089 assert((MI->getNumOperands() <= 3 ||
16090 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16091 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16092 && "Expected last argument to be EFLAGS");
16093 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16094 // In the XMM save block, save all the XMM argument registers.
16095 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16096 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16097 MachineMemOperand *MMO =
16098 F->getMachineMemOperand(
16099 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16100 MachineMemOperand::MOStore,
16101 /*Size=*/16, /*Align=*/16);
16102 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16103 .addFrameIndex(RegSaveFrameIndex)
16104 .addImm(/*Scale=*/1)
16105 .addReg(/*IndexReg=*/0)
16106 .addImm(/*Disp=*/Offset)
16107 .addReg(/*Segment=*/0)
16108 .addReg(MI->getOperand(i).getReg())
16109 .addMemOperand(MMO);
16112 MI->eraseFromParent(); // The pseudo instruction is gone now.
16117 // The EFLAGS operand of SelectItr might be missing a kill marker
16118 // because there were multiple uses of EFLAGS, and ISel didn't know
16119 // which to mark. Figure out whether SelectItr should have had a
16120 // kill marker, and set it if it should. Returns the correct kill
16122 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16123 MachineBasicBlock* BB,
16124 const TargetRegisterInfo* TRI) {
16125 // Scan forward through BB for a use/def of EFLAGS.
16126 MachineBasicBlock::iterator miI(std::next(SelectItr));
16127 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16128 const MachineInstr& mi = *miI;
16129 if (mi.readsRegister(X86::EFLAGS))
16131 if (mi.definesRegister(X86::EFLAGS))
16132 break; // Should have kill-flag - update below.
16135 // If we hit the end of the block, check whether EFLAGS is live into a
16137 if (miI == BB->end()) {
16138 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16139 sEnd = BB->succ_end();
16140 sItr != sEnd; ++sItr) {
16141 MachineBasicBlock* succ = *sItr;
16142 if (succ->isLiveIn(X86::EFLAGS))
16147 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16148 // out. SelectMI should have a kill flag on EFLAGS.
16149 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16153 MachineBasicBlock *
16154 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16155 MachineBasicBlock *BB) const {
16156 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16157 DebugLoc DL = MI->getDebugLoc();
16159 // To "insert" a SELECT_CC instruction, we actually have to insert the
16160 // diamond control-flow pattern. The incoming instruction knows the
16161 // destination vreg to set, the condition code register to branch on, the
16162 // true/false values to select between, and a branch opcode to use.
16163 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16164 MachineFunction::iterator It = BB;
16170 // cmpTY ccX, r1, r2
16172 // fallthrough --> copy0MBB
16173 MachineBasicBlock *thisMBB = BB;
16174 MachineFunction *F = BB->getParent();
16175 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16176 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16177 F->insert(It, copy0MBB);
16178 F->insert(It, sinkMBB);
16180 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16181 // live into the sink and copy blocks.
16182 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16183 if (!MI->killsRegister(X86::EFLAGS) &&
16184 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16185 copy0MBB->addLiveIn(X86::EFLAGS);
16186 sinkMBB->addLiveIn(X86::EFLAGS);
16189 // Transfer the remainder of BB and its successor edges to sinkMBB.
16190 sinkMBB->splice(sinkMBB->begin(), BB,
16191 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16192 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16194 // Add the true and fallthrough blocks as its successors.
16195 BB->addSuccessor(copy0MBB);
16196 BB->addSuccessor(sinkMBB);
16198 // Create the conditional branch instruction.
16200 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16201 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16204 // %FalseValue = ...
16205 // # fallthrough to sinkMBB
16206 copy0MBB->addSuccessor(sinkMBB);
16209 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16211 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16212 TII->get(X86::PHI), MI->getOperand(0).getReg())
16213 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16214 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16216 MI->eraseFromParent(); // The pseudo instruction is gone now.
16220 MachineBasicBlock *
16221 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16222 bool Is64Bit) const {
16223 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16224 DebugLoc DL = MI->getDebugLoc();
16225 MachineFunction *MF = BB->getParent();
16226 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16228 assert(MF->shouldSplitStack());
16230 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16231 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16234 // ... [Till the alloca]
16235 // If stacklet is not large enough, jump to mallocMBB
16238 // Allocate by subtracting from RSP
16239 // Jump to continueMBB
16242 // Allocate by call to runtime
16246 // [rest of original BB]
16249 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16250 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16251 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16253 MachineRegisterInfo &MRI = MF->getRegInfo();
16254 const TargetRegisterClass *AddrRegClass =
16255 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16257 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16258 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16259 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16260 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16261 sizeVReg = MI->getOperand(1).getReg(),
16262 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16264 MachineFunction::iterator MBBIter = BB;
16267 MF->insert(MBBIter, bumpMBB);
16268 MF->insert(MBBIter, mallocMBB);
16269 MF->insert(MBBIter, continueMBB);
16271 continueMBB->splice(continueMBB->begin(), BB,
16272 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16273 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16275 // Add code to the main basic block to check if the stack limit has been hit,
16276 // and if so, jump to mallocMBB otherwise to bumpMBB.
16277 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16278 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16279 .addReg(tmpSPVReg).addReg(sizeVReg);
16280 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16281 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16282 .addReg(SPLimitVReg);
16283 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16285 // bumpMBB simply decreases the stack pointer, since we know the current
16286 // stacklet has enough space.
16287 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16288 .addReg(SPLimitVReg);
16289 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16290 .addReg(SPLimitVReg);
16291 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16293 // Calls into a routine in libgcc to allocate more space from the heap.
16294 const uint32_t *RegMask =
16295 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16297 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16299 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16300 .addExternalSymbol("__morestack_allocate_stack_space")
16301 .addRegMask(RegMask)
16302 .addReg(X86::RDI, RegState::Implicit)
16303 .addReg(X86::RAX, RegState::ImplicitDefine);
16305 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16307 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16308 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16309 .addExternalSymbol("__morestack_allocate_stack_space")
16310 .addRegMask(RegMask)
16311 .addReg(X86::EAX, RegState::ImplicitDefine);
16315 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16318 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16319 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16320 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16322 // Set up the CFG correctly.
16323 BB->addSuccessor(bumpMBB);
16324 BB->addSuccessor(mallocMBB);
16325 mallocMBB->addSuccessor(continueMBB);
16326 bumpMBB->addSuccessor(continueMBB);
16328 // Take care of the PHI nodes.
16329 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16330 MI->getOperand(0).getReg())
16331 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16332 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16334 // Delete the original pseudo instruction.
16335 MI->eraseFromParent();
16338 return continueMBB;
16341 MachineBasicBlock *
16342 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16343 MachineBasicBlock *BB) const {
16344 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16345 DebugLoc DL = MI->getDebugLoc();
16347 assert(!Subtarget->isTargetMacho());
16349 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16350 // non-trivial part is impdef of ESP.
16352 if (Subtarget->isTargetWin64()) {
16353 if (Subtarget->isTargetCygMing()) {
16354 // ___chkstk(Mingw64):
16355 // Clobbers R10, R11, RAX and EFLAGS.
16357 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16358 .addExternalSymbol("___chkstk")
16359 .addReg(X86::RAX, RegState::Implicit)
16360 .addReg(X86::RSP, RegState::Implicit)
16361 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16362 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16363 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16365 // __chkstk(MSVCRT): does not update stack pointer.
16366 // Clobbers R10, R11 and EFLAGS.
16367 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16368 .addExternalSymbol("__chkstk")
16369 .addReg(X86::RAX, RegState::Implicit)
16370 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16371 // RAX has the offset to be subtracted from RSP.
16372 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16377 const char *StackProbeSymbol =
16378 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16380 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16381 .addExternalSymbol(StackProbeSymbol)
16382 .addReg(X86::EAX, RegState::Implicit)
16383 .addReg(X86::ESP, RegState::Implicit)
16384 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16385 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16386 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16389 MI->eraseFromParent(); // The pseudo instruction is gone now.
16393 MachineBasicBlock *
16394 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16395 MachineBasicBlock *BB) const {
16396 // This is pretty easy. We're taking the value that we received from
16397 // our load from the relocation, sticking it in either RDI (x86-64)
16398 // or EAX and doing an indirect call. The return value will then
16399 // be in the normal return register.
16400 const X86InstrInfo *TII
16401 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16402 DebugLoc DL = MI->getDebugLoc();
16403 MachineFunction *F = BB->getParent();
16405 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16406 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16408 // Get a register mask for the lowered call.
16409 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16410 // proper register mask.
16411 const uint32_t *RegMask =
16412 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16413 if (Subtarget->is64Bit()) {
16414 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16415 TII->get(X86::MOV64rm), X86::RDI)
16417 .addImm(0).addReg(0)
16418 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16419 MI->getOperand(3).getTargetFlags())
16421 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16422 addDirectMem(MIB, X86::RDI);
16423 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16424 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16425 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16426 TII->get(X86::MOV32rm), X86::EAX)
16428 .addImm(0).addReg(0)
16429 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16430 MI->getOperand(3).getTargetFlags())
16432 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16433 addDirectMem(MIB, X86::EAX);
16434 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16436 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16437 TII->get(X86::MOV32rm), X86::EAX)
16438 .addReg(TII->getGlobalBaseReg(F))
16439 .addImm(0).addReg(0)
16440 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16441 MI->getOperand(3).getTargetFlags())
16443 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16444 addDirectMem(MIB, X86::EAX);
16445 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16448 MI->eraseFromParent(); // The pseudo instruction is gone now.
16452 MachineBasicBlock *
16453 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16454 MachineBasicBlock *MBB) const {
16455 DebugLoc DL = MI->getDebugLoc();
16456 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16458 MachineFunction *MF = MBB->getParent();
16459 MachineRegisterInfo &MRI = MF->getRegInfo();
16461 const BasicBlock *BB = MBB->getBasicBlock();
16462 MachineFunction::iterator I = MBB;
16465 // Memory Reference
16466 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16467 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16470 unsigned MemOpndSlot = 0;
16472 unsigned CurOp = 0;
16474 DstReg = MI->getOperand(CurOp++).getReg();
16475 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16476 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16477 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16478 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16480 MemOpndSlot = CurOp;
16482 MVT PVT = getPointerTy();
16483 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16484 "Invalid Pointer Size!");
16486 // For v = setjmp(buf), we generate
16489 // buf[LabelOffset] = restoreMBB
16490 // SjLjSetup restoreMBB
16496 // v = phi(main, restore)
16501 MachineBasicBlock *thisMBB = MBB;
16502 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16503 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16504 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16505 MF->insert(I, mainMBB);
16506 MF->insert(I, sinkMBB);
16507 MF->push_back(restoreMBB);
16509 MachineInstrBuilder MIB;
16511 // Transfer the remainder of BB and its successor edges to sinkMBB.
16512 sinkMBB->splice(sinkMBB->begin(), MBB,
16513 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16514 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16517 unsigned PtrStoreOpc = 0;
16518 unsigned LabelReg = 0;
16519 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16520 Reloc::Model RM = getTargetMachine().getRelocationModel();
16521 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16522 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16524 // Prepare IP either in reg or imm.
16525 if (!UseImmLabel) {
16526 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16527 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16528 LabelReg = MRI.createVirtualRegister(PtrRC);
16529 if (Subtarget->is64Bit()) {
16530 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16534 .addMBB(restoreMBB)
16537 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16538 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16539 .addReg(XII->getGlobalBaseReg(MF))
16542 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16546 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16548 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16549 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16550 if (i == X86::AddrDisp)
16551 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16553 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16556 MIB.addReg(LabelReg);
16558 MIB.addMBB(restoreMBB);
16559 MIB.setMemRefs(MMOBegin, MMOEnd);
16561 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16562 .addMBB(restoreMBB);
16564 const X86RegisterInfo *RegInfo =
16565 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16566 MIB.addRegMask(RegInfo->getNoPreservedMask());
16567 thisMBB->addSuccessor(mainMBB);
16568 thisMBB->addSuccessor(restoreMBB);
16572 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16573 mainMBB->addSuccessor(sinkMBB);
16576 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16577 TII->get(X86::PHI), DstReg)
16578 .addReg(mainDstReg).addMBB(mainMBB)
16579 .addReg(restoreDstReg).addMBB(restoreMBB);
16582 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16583 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16584 restoreMBB->addSuccessor(sinkMBB);
16586 MI->eraseFromParent();
16590 MachineBasicBlock *
16591 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16592 MachineBasicBlock *MBB) const {
16593 DebugLoc DL = MI->getDebugLoc();
16594 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16596 MachineFunction *MF = MBB->getParent();
16597 MachineRegisterInfo &MRI = MF->getRegInfo();
16599 // Memory Reference
16600 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16601 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16603 MVT PVT = getPointerTy();
16604 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16605 "Invalid Pointer Size!");
16607 const TargetRegisterClass *RC =
16608 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16609 unsigned Tmp = MRI.createVirtualRegister(RC);
16610 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16611 const X86RegisterInfo *RegInfo =
16612 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16613 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16614 unsigned SP = RegInfo->getStackRegister();
16616 MachineInstrBuilder MIB;
16618 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16619 const int64_t SPOffset = 2 * PVT.getStoreSize();
16621 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16622 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16625 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16626 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16627 MIB.addOperand(MI->getOperand(i));
16628 MIB.setMemRefs(MMOBegin, MMOEnd);
16630 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16631 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16632 if (i == X86::AddrDisp)
16633 MIB.addDisp(MI->getOperand(i), LabelOffset);
16635 MIB.addOperand(MI->getOperand(i));
16637 MIB.setMemRefs(MMOBegin, MMOEnd);
16639 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16640 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16641 if (i == X86::AddrDisp)
16642 MIB.addDisp(MI->getOperand(i), SPOffset);
16644 MIB.addOperand(MI->getOperand(i));
16646 MIB.setMemRefs(MMOBegin, MMOEnd);
16648 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16650 MI->eraseFromParent();
16654 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16655 // accumulator loops. Writing back to the accumulator allows the coalescer
16656 // to remove extra copies in the loop.
16657 MachineBasicBlock *
16658 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16659 MachineBasicBlock *MBB) const {
16660 MachineOperand &AddendOp = MI->getOperand(3);
16662 // Bail out early if the addend isn't a register - we can't switch these.
16663 if (!AddendOp.isReg())
16666 MachineFunction &MF = *MBB->getParent();
16667 MachineRegisterInfo &MRI = MF.getRegInfo();
16669 // Check whether the addend is defined by a PHI:
16670 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16671 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16672 if (!AddendDef.isPHI())
16675 // Look for the following pattern:
16677 // %addend = phi [%entry, 0], [%loop, %result]
16679 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16683 // %addend = phi [%entry, 0], [%loop, %result]
16685 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16687 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16688 assert(AddendDef.getOperand(i).isReg());
16689 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16690 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16691 if (&PHISrcInst == MI) {
16692 // Found a matching instruction.
16693 unsigned NewFMAOpc = 0;
16694 switch (MI->getOpcode()) {
16695 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16696 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16697 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16698 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16699 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16700 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16701 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16702 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16703 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16704 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16705 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16706 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16707 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16708 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16709 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16710 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16711 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16712 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16713 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16714 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16715 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16716 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16717 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16718 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16719 default: llvm_unreachable("Unrecognized FMA variant.");
16722 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16723 MachineInstrBuilder MIB =
16724 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16725 .addOperand(MI->getOperand(0))
16726 .addOperand(MI->getOperand(3))
16727 .addOperand(MI->getOperand(2))
16728 .addOperand(MI->getOperand(1));
16729 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16730 MI->eraseFromParent();
16737 MachineBasicBlock *
16738 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16739 MachineBasicBlock *BB) const {
16740 switch (MI->getOpcode()) {
16741 default: llvm_unreachable("Unexpected instr type to insert");
16742 case X86::TAILJMPd64:
16743 case X86::TAILJMPr64:
16744 case X86::TAILJMPm64:
16745 llvm_unreachable("TAILJMP64 would not be touched here.");
16746 case X86::TCRETURNdi64:
16747 case X86::TCRETURNri64:
16748 case X86::TCRETURNmi64:
16750 case X86::WIN_ALLOCA:
16751 return EmitLoweredWinAlloca(MI, BB);
16752 case X86::SEG_ALLOCA_32:
16753 return EmitLoweredSegAlloca(MI, BB, false);
16754 case X86::SEG_ALLOCA_64:
16755 return EmitLoweredSegAlloca(MI, BB, true);
16756 case X86::TLSCall_32:
16757 case X86::TLSCall_64:
16758 return EmitLoweredTLSCall(MI, BB);
16759 case X86::CMOV_GR8:
16760 case X86::CMOV_FR32:
16761 case X86::CMOV_FR64:
16762 case X86::CMOV_V4F32:
16763 case X86::CMOV_V2F64:
16764 case X86::CMOV_V2I64:
16765 case X86::CMOV_V8F32:
16766 case X86::CMOV_V4F64:
16767 case X86::CMOV_V4I64:
16768 case X86::CMOV_V16F32:
16769 case X86::CMOV_V8F64:
16770 case X86::CMOV_V8I64:
16771 case X86::CMOV_GR16:
16772 case X86::CMOV_GR32:
16773 case X86::CMOV_RFP32:
16774 case X86::CMOV_RFP64:
16775 case X86::CMOV_RFP80:
16776 return EmitLoweredSelect(MI, BB);
16778 case X86::FP32_TO_INT16_IN_MEM:
16779 case X86::FP32_TO_INT32_IN_MEM:
16780 case X86::FP32_TO_INT64_IN_MEM:
16781 case X86::FP64_TO_INT16_IN_MEM:
16782 case X86::FP64_TO_INT32_IN_MEM:
16783 case X86::FP64_TO_INT64_IN_MEM:
16784 case X86::FP80_TO_INT16_IN_MEM:
16785 case X86::FP80_TO_INT32_IN_MEM:
16786 case X86::FP80_TO_INT64_IN_MEM: {
16787 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16788 DebugLoc DL = MI->getDebugLoc();
16790 // Change the floating point control register to use "round towards zero"
16791 // mode when truncating to an integer value.
16792 MachineFunction *F = BB->getParent();
16793 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16794 addFrameReference(BuildMI(*BB, MI, DL,
16795 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16797 // Load the old value of the high byte of the control word...
16799 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16800 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16803 // Set the high part to be round to zero...
16804 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16807 // Reload the modified control word now...
16808 addFrameReference(BuildMI(*BB, MI, DL,
16809 TII->get(X86::FLDCW16m)), CWFrameIdx);
16811 // Restore the memory image of control word to original value
16812 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16815 // Get the X86 opcode to use.
16817 switch (MI->getOpcode()) {
16818 default: llvm_unreachable("illegal opcode!");
16819 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16820 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16821 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16822 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16823 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16824 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16825 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16826 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16827 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16831 MachineOperand &Op = MI->getOperand(0);
16833 AM.BaseType = X86AddressMode::RegBase;
16834 AM.Base.Reg = Op.getReg();
16836 AM.BaseType = X86AddressMode::FrameIndexBase;
16837 AM.Base.FrameIndex = Op.getIndex();
16839 Op = MI->getOperand(1);
16841 AM.Scale = Op.getImm();
16842 Op = MI->getOperand(2);
16844 AM.IndexReg = Op.getImm();
16845 Op = MI->getOperand(3);
16846 if (Op.isGlobal()) {
16847 AM.GV = Op.getGlobal();
16849 AM.Disp = Op.getImm();
16851 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16852 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16854 // Reload the original control word now.
16855 addFrameReference(BuildMI(*BB, MI, DL,
16856 TII->get(X86::FLDCW16m)), CWFrameIdx);
16858 MI->eraseFromParent(); // The pseudo instruction is gone now.
16861 // String/text processing lowering.
16862 case X86::PCMPISTRM128REG:
16863 case X86::VPCMPISTRM128REG:
16864 case X86::PCMPISTRM128MEM:
16865 case X86::VPCMPISTRM128MEM:
16866 case X86::PCMPESTRM128REG:
16867 case X86::VPCMPESTRM128REG:
16868 case X86::PCMPESTRM128MEM:
16869 case X86::VPCMPESTRM128MEM:
16870 assert(Subtarget->hasSSE42() &&
16871 "Target must have SSE4.2 or AVX features enabled");
16872 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16874 // String/text processing lowering.
16875 case X86::PCMPISTRIREG:
16876 case X86::VPCMPISTRIREG:
16877 case X86::PCMPISTRIMEM:
16878 case X86::VPCMPISTRIMEM:
16879 case X86::PCMPESTRIREG:
16880 case X86::VPCMPESTRIREG:
16881 case X86::PCMPESTRIMEM:
16882 case X86::VPCMPESTRIMEM:
16883 assert(Subtarget->hasSSE42() &&
16884 "Target must have SSE4.2 or AVX features enabled");
16885 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16887 // Thread synchronization.
16889 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16893 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16895 // Atomic Lowering.
16896 case X86::ATOMAND8:
16897 case X86::ATOMAND16:
16898 case X86::ATOMAND32:
16899 case X86::ATOMAND64:
16902 case X86::ATOMOR16:
16903 case X86::ATOMOR32:
16904 case X86::ATOMOR64:
16906 case X86::ATOMXOR16:
16907 case X86::ATOMXOR8:
16908 case X86::ATOMXOR32:
16909 case X86::ATOMXOR64:
16911 case X86::ATOMNAND8:
16912 case X86::ATOMNAND16:
16913 case X86::ATOMNAND32:
16914 case X86::ATOMNAND64:
16916 case X86::ATOMMAX8:
16917 case X86::ATOMMAX16:
16918 case X86::ATOMMAX32:
16919 case X86::ATOMMAX64:
16921 case X86::ATOMMIN8:
16922 case X86::ATOMMIN16:
16923 case X86::ATOMMIN32:
16924 case X86::ATOMMIN64:
16926 case X86::ATOMUMAX8:
16927 case X86::ATOMUMAX16:
16928 case X86::ATOMUMAX32:
16929 case X86::ATOMUMAX64:
16931 case X86::ATOMUMIN8:
16932 case X86::ATOMUMIN16:
16933 case X86::ATOMUMIN32:
16934 case X86::ATOMUMIN64:
16935 return EmitAtomicLoadArith(MI, BB);
16937 // This group does 64-bit operations on a 32-bit host.
16938 case X86::ATOMAND6432:
16939 case X86::ATOMOR6432:
16940 case X86::ATOMXOR6432:
16941 case X86::ATOMNAND6432:
16942 case X86::ATOMADD6432:
16943 case X86::ATOMSUB6432:
16944 case X86::ATOMMAX6432:
16945 case X86::ATOMMIN6432:
16946 case X86::ATOMUMAX6432:
16947 case X86::ATOMUMIN6432:
16948 case X86::ATOMSWAP6432:
16949 return EmitAtomicLoadArith6432(MI, BB);
16951 case X86::VASTART_SAVE_XMM_REGS:
16952 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16954 case X86::VAARG_64:
16955 return EmitVAARG64WithCustomInserter(MI, BB);
16957 case X86::EH_SjLj_SetJmp32:
16958 case X86::EH_SjLj_SetJmp64:
16959 return emitEHSjLjSetJmp(MI, BB);
16961 case X86::EH_SjLj_LongJmp32:
16962 case X86::EH_SjLj_LongJmp64:
16963 return emitEHSjLjLongJmp(MI, BB);
16965 case TargetOpcode::STACKMAP:
16966 case TargetOpcode::PATCHPOINT:
16967 return emitPatchPoint(MI, BB);
16969 case X86::VFMADDPDr213r:
16970 case X86::VFMADDPSr213r:
16971 case X86::VFMADDSDr213r:
16972 case X86::VFMADDSSr213r:
16973 case X86::VFMSUBPDr213r:
16974 case X86::VFMSUBPSr213r:
16975 case X86::VFMSUBSDr213r:
16976 case X86::VFMSUBSSr213r:
16977 case X86::VFNMADDPDr213r:
16978 case X86::VFNMADDPSr213r:
16979 case X86::VFNMADDSDr213r:
16980 case X86::VFNMADDSSr213r:
16981 case X86::VFNMSUBPDr213r:
16982 case X86::VFNMSUBPSr213r:
16983 case X86::VFNMSUBSDr213r:
16984 case X86::VFNMSUBSSr213r:
16985 case X86::VFMADDPDr213rY:
16986 case X86::VFMADDPSr213rY:
16987 case X86::VFMSUBPDr213rY:
16988 case X86::VFMSUBPSr213rY:
16989 case X86::VFNMADDPDr213rY:
16990 case X86::VFNMADDPSr213rY:
16991 case X86::VFNMSUBPDr213rY:
16992 case X86::VFNMSUBPSr213rY:
16993 return emitFMA3Instr(MI, BB);
16997 //===----------------------------------------------------------------------===//
16998 // X86 Optimization Hooks
16999 //===----------------------------------------------------------------------===//
17001 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
17004 const SelectionDAG &DAG,
17005 unsigned Depth) const {
17006 unsigned BitWidth = KnownZero.getBitWidth();
17007 unsigned Opc = Op.getOpcode();
17008 assert((Opc >= ISD::BUILTIN_OP_END ||
17009 Opc == ISD::INTRINSIC_WO_CHAIN ||
17010 Opc == ISD::INTRINSIC_W_CHAIN ||
17011 Opc == ISD::INTRINSIC_VOID) &&
17012 "Should use MaskedValueIsZero if you don't know whether Op"
17013 " is a target node!");
17015 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17029 // These nodes' second result is a boolean.
17030 if (Op.getResNo() == 0)
17033 case X86ISD::SETCC:
17034 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17036 case ISD::INTRINSIC_WO_CHAIN: {
17037 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17038 unsigned NumLoBits = 0;
17041 case Intrinsic::x86_sse_movmsk_ps:
17042 case Intrinsic::x86_avx_movmsk_ps_256:
17043 case Intrinsic::x86_sse2_movmsk_pd:
17044 case Intrinsic::x86_avx_movmsk_pd_256:
17045 case Intrinsic::x86_mmx_pmovmskb:
17046 case Intrinsic::x86_sse2_pmovmskb_128:
17047 case Intrinsic::x86_avx2_pmovmskb: {
17048 // High bits of movmskp{s|d}, pmovmskb are known zero.
17050 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17051 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17052 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17053 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17054 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17055 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17056 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17057 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17059 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17068 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17070 const SelectionDAG &,
17071 unsigned Depth) const {
17072 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17073 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17074 return Op.getValueType().getScalarType().getSizeInBits();
17080 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17081 /// node is a GlobalAddress + offset.
17082 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17083 const GlobalValue* &GA,
17084 int64_t &Offset) const {
17085 if (N->getOpcode() == X86ISD::Wrapper) {
17086 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17087 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17088 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17092 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17095 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17096 /// same as extracting the high 128-bit part of 256-bit vector and then
17097 /// inserting the result into the low part of a new 256-bit vector
17098 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17099 EVT VT = SVOp->getValueType(0);
17100 unsigned NumElems = VT.getVectorNumElements();
17102 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17103 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17104 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17105 SVOp->getMaskElt(j) >= 0)
17111 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17112 /// same as extracting the low 128-bit part of 256-bit vector and then
17113 /// inserting the result into the high part of a new 256-bit vector
17114 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17115 EVT VT = SVOp->getValueType(0);
17116 unsigned NumElems = VT.getVectorNumElements();
17118 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17119 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17120 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17121 SVOp->getMaskElt(j) >= 0)
17127 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17128 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17129 TargetLowering::DAGCombinerInfo &DCI,
17130 const X86Subtarget* Subtarget) {
17132 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17133 SDValue V1 = SVOp->getOperand(0);
17134 SDValue V2 = SVOp->getOperand(1);
17135 EVT VT = SVOp->getValueType(0);
17136 unsigned NumElems = VT.getVectorNumElements();
17138 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17139 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17143 // V UNDEF BUILD_VECTOR UNDEF
17145 // CONCAT_VECTOR CONCAT_VECTOR
17148 // RESULT: V + zero extended
17150 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17151 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17152 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17155 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17158 // To match the shuffle mask, the first half of the mask should
17159 // be exactly the first vector, and all the rest a splat with the
17160 // first element of the second one.
17161 for (unsigned i = 0; i != NumElems/2; ++i)
17162 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17163 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17166 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17167 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17168 if (Ld->hasNUsesOfValue(1, 0)) {
17169 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17170 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17172 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17174 Ld->getPointerInfo(),
17175 Ld->getAlignment(),
17176 false/*isVolatile*/, true/*ReadMem*/,
17177 false/*WriteMem*/);
17179 // Make sure the newly-created LOAD is in the same position as Ld in
17180 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17181 // and update uses of Ld's output chain to use the TokenFactor.
17182 if (Ld->hasAnyUseOfValue(1)) {
17183 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17184 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17185 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17186 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17187 SDValue(ResNode.getNode(), 1));
17190 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17194 // Emit a zeroed vector and insert the desired subvector on its
17196 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17197 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17198 return DCI.CombineTo(N, InsV);
17201 //===--------------------------------------------------------------------===//
17202 // Combine some shuffles into subvector extracts and inserts:
17205 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17206 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17207 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17208 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17209 return DCI.CombineTo(N, InsV);
17212 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17213 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17214 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17215 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17216 return DCI.CombineTo(N, InsV);
17222 /// PerformShuffleCombine - Performs several different shuffle combines.
17223 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17224 TargetLowering::DAGCombinerInfo &DCI,
17225 const X86Subtarget *Subtarget) {
17227 EVT VT = N->getValueType(0);
17229 // Don't create instructions with illegal types after legalize types has run.
17230 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17231 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17234 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17235 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17236 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17237 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17239 // Only handle 128 wide vector from here on.
17240 if (!VT.is128BitVector())
17243 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17244 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17245 // consecutive, non-overlapping, and in the right order.
17246 SmallVector<SDValue, 16> Elts;
17247 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17248 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17250 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17253 /// PerformTruncateCombine - Converts truncate operation to
17254 /// a sequence of vector shuffle operations.
17255 /// It is possible when we truncate 256-bit vector to 128-bit vector
17256 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17257 TargetLowering::DAGCombinerInfo &DCI,
17258 const X86Subtarget *Subtarget) {
17262 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17263 /// specific shuffle of a load can be folded into a single element load.
17264 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17265 /// shuffles have been customed lowered so we need to handle those here.
17266 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17267 TargetLowering::DAGCombinerInfo &DCI) {
17268 if (DCI.isBeforeLegalizeOps())
17271 SDValue InVec = N->getOperand(0);
17272 SDValue EltNo = N->getOperand(1);
17274 if (!isa<ConstantSDNode>(EltNo))
17277 EVT VT = InVec.getValueType();
17279 bool HasShuffleIntoBitcast = false;
17280 if (InVec.getOpcode() == ISD::BITCAST) {
17281 // Don't duplicate a load with other uses.
17282 if (!InVec.hasOneUse())
17284 EVT BCVT = InVec.getOperand(0).getValueType();
17285 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17287 InVec = InVec.getOperand(0);
17288 HasShuffleIntoBitcast = true;
17291 if (!isTargetShuffle(InVec.getOpcode()))
17294 // Don't duplicate a load with other uses.
17295 if (!InVec.hasOneUse())
17298 SmallVector<int, 16> ShuffleMask;
17300 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17304 // Select the input vector, guarding against out of range extract vector.
17305 unsigned NumElems = VT.getVectorNumElements();
17306 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17307 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17308 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17309 : InVec.getOperand(1);
17311 // If inputs to shuffle are the same for both ops, then allow 2 uses
17312 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17314 if (LdNode.getOpcode() == ISD::BITCAST) {
17315 // Don't duplicate a load with other uses.
17316 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17319 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17320 LdNode = LdNode.getOperand(0);
17323 if (!ISD::isNormalLoad(LdNode.getNode()))
17326 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17328 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17331 if (HasShuffleIntoBitcast) {
17332 // If there's a bitcast before the shuffle, check if the load type and
17333 // alignment is valid.
17334 unsigned Align = LN0->getAlignment();
17335 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17336 unsigned NewAlign = TLI.getDataLayout()->
17337 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17339 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17343 // All checks match so transform back to vector_shuffle so that DAG combiner
17344 // can finish the job
17347 // Create shuffle node taking into account the case that its a unary shuffle
17348 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17349 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17350 InVec.getOperand(0), Shuffle,
17352 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17353 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17357 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17358 /// generation and convert it from being a bunch of shuffles and extracts
17359 /// to a simple store and scalar loads to extract the elements.
17360 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17361 TargetLowering::DAGCombinerInfo &DCI) {
17362 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17363 if (NewOp.getNode())
17366 SDValue InputVector = N->getOperand(0);
17368 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17369 // from mmx to v2i32 has a single usage.
17370 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17371 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17372 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17373 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17374 N->getValueType(0),
17375 InputVector.getNode()->getOperand(0));
17377 // Only operate on vectors of 4 elements, where the alternative shuffling
17378 // gets to be more expensive.
17379 if (InputVector.getValueType() != MVT::v4i32)
17382 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17383 // single use which is a sign-extend or zero-extend, and all elements are
17385 SmallVector<SDNode *, 4> Uses;
17386 unsigned ExtractedElements = 0;
17387 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17388 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17389 if (UI.getUse().getResNo() != InputVector.getResNo())
17392 SDNode *Extract = *UI;
17393 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17396 if (Extract->getValueType(0) != MVT::i32)
17398 if (!Extract->hasOneUse())
17400 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17401 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17403 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17406 // Record which element was extracted.
17407 ExtractedElements |=
17408 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17410 Uses.push_back(Extract);
17413 // If not all the elements were used, this may not be worthwhile.
17414 if (ExtractedElements != 15)
17417 // Ok, we've now decided to do the transformation.
17418 SDLoc dl(InputVector);
17420 // Store the value to a temporary stack slot.
17421 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17422 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17423 MachinePointerInfo(), false, false, 0);
17425 // Replace each use (extract) with a load of the appropriate element.
17426 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17427 UE = Uses.end(); UI != UE; ++UI) {
17428 SDNode *Extract = *UI;
17430 // cOMpute the element's address.
17431 SDValue Idx = Extract->getOperand(1);
17433 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17434 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17435 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17436 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17438 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17439 StackPtr, OffsetVal);
17441 // Load the scalar.
17442 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17443 ScalarAddr, MachinePointerInfo(),
17444 false, false, false, 0);
17446 // Replace the exact with the load.
17447 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17450 // The replacement was made in place; don't return anything.
17454 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17455 static std::pair<unsigned, bool>
17456 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17457 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17458 if (!VT.isVector())
17459 return std::make_pair(0, false);
17461 bool NeedSplit = false;
17462 switch (VT.getSimpleVT().SimpleTy) {
17463 default: return std::make_pair(0, false);
17467 if (!Subtarget->hasAVX2())
17469 if (!Subtarget->hasAVX())
17470 return std::make_pair(0, false);
17475 if (!Subtarget->hasSSE2())
17476 return std::make_pair(0, false);
17479 // SSE2 has only a small subset of the operations.
17480 bool hasUnsigned = Subtarget->hasSSE41() ||
17481 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17482 bool hasSigned = Subtarget->hasSSE41() ||
17483 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17485 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17488 // Check for x CC y ? x : y.
17489 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17490 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17495 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17498 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17501 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17504 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17506 // Check for x CC y ? y : x -- a min/max with reversed arms.
17507 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17508 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17513 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17516 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17519 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17522 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17526 return std::make_pair(Opc, NeedSplit);
17529 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17531 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17532 TargetLowering::DAGCombinerInfo &DCI,
17533 const X86Subtarget *Subtarget) {
17535 SDValue Cond = N->getOperand(0);
17536 // Get the LHS/RHS of the select.
17537 SDValue LHS = N->getOperand(1);
17538 SDValue RHS = N->getOperand(2);
17539 EVT VT = LHS.getValueType();
17540 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17542 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17543 // instructions match the semantics of the common C idiom x<y?x:y but not
17544 // x<=y?x:y, because of how they handle negative zero (which can be
17545 // ignored in unsafe-math mode).
17546 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17547 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17548 (Subtarget->hasSSE2() ||
17549 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17550 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17552 unsigned Opcode = 0;
17553 // Check for x CC y ? x : y.
17554 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17555 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17559 // Converting this to a min would handle NaNs incorrectly, and swapping
17560 // the operands would cause it to handle comparisons between positive
17561 // and negative zero incorrectly.
17562 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17563 if (!DAG.getTarget().Options.UnsafeFPMath &&
17564 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17566 std::swap(LHS, RHS);
17568 Opcode = X86ISD::FMIN;
17571 // Converting this to a min would handle comparisons between positive
17572 // and negative zero incorrectly.
17573 if (!DAG.getTarget().Options.UnsafeFPMath &&
17574 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17576 Opcode = X86ISD::FMIN;
17579 // Converting this to a min would handle both negative zeros and NaNs
17580 // incorrectly, but we can swap the operands to fix both.
17581 std::swap(LHS, RHS);
17585 Opcode = X86ISD::FMIN;
17589 // Converting this to a max would handle comparisons between positive
17590 // and negative zero incorrectly.
17591 if (!DAG.getTarget().Options.UnsafeFPMath &&
17592 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17594 Opcode = X86ISD::FMAX;
17597 // Converting this to a max would handle NaNs incorrectly, and swapping
17598 // the operands would cause it to handle comparisons between positive
17599 // and negative zero incorrectly.
17600 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17601 if (!DAG.getTarget().Options.UnsafeFPMath &&
17602 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17604 std::swap(LHS, RHS);
17606 Opcode = X86ISD::FMAX;
17609 // Converting this to a max would handle both negative zeros and NaNs
17610 // incorrectly, but we can swap the operands to fix both.
17611 std::swap(LHS, RHS);
17615 Opcode = X86ISD::FMAX;
17618 // Check for x CC y ? y : x -- a min/max with reversed arms.
17619 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17620 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17624 // Converting this to a min would handle comparisons between positive
17625 // and negative zero incorrectly, and swapping the operands would
17626 // cause it to handle NaNs incorrectly.
17627 if (!DAG.getTarget().Options.UnsafeFPMath &&
17628 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17629 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17631 std::swap(LHS, RHS);
17633 Opcode = X86ISD::FMIN;
17636 // Converting this to a min would handle NaNs incorrectly.
17637 if (!DAG.getTarget().Options.UnsafeFPMath &&
17638 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17640 Opcode = X86ISD::FMIN;
17643 // Converting this to a min would handle both negative zeros and NaNs
17644 // incorrectly, but we can swap the operands to fix both.
17645 std::swap(LHS, RHS);
17649 Opcode = X86ISD::FMIN;
17653 // Converting this to a max would handle NaNs incorrectly.
17654 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17656 Opcode = X86ISD::FMAX;
17659 // Converting this to a max would handle comparisons between positive
17660 // and negative zero incorrectly, and swapping the operands would
17661 // cause it to handle NaNs incorrectly.
17662 if (!DAG.getTarget().Options.UnsafeFPMath &&
17663 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17664 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17666 std::swap(LHS, RHS);
17668 Opcode = X86ISD::FMAX;
17671 // Converting this to a max would handle both negative zeros and NaNs
17672 // incorrectly, but we can swap the operands to fix both.
17673 std::swap(LHS, RHS);
17677 Opcode = X86ISD::FMAX;
17683 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17686 EVT CondVT = Cond.getValueType();
17687 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17688 CondVT.getVectorElementType() == MVT::i1) {
17689 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17690 // lowering on AVX-512. In this case we convert it to
17691 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17692 // The same situation for all 128 and 256-bit vectors of i8 and i16
17693 EVT OpVT = LHS.getValueType();
17694 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17695 (OpVT.getVectorElementType() == MVT::i8 ||
17696 OpVT.getVectorElementType() == MVT::i16)) {
17697 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17698 DCI.AddToWorklist(Cond.getNode());
17699 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17702 // If this is a select between two integer constants, try to do some
17704 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17705 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17706 // Don't do this for crazy integer types.
17707 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17708 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17709 // so that TrueC (the true value) is larger than FalseC.
17710 bool NeedsCondInvert = false;
17712 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17713 // Efficiently invertible.
17714 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17715 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17716 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17717 NeedsCondInvert = true;
17718 std::swap(TrueC, FalseC);
17721 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17722 if (FalseC->getAPIntValue() == 0 &&
17723 TrueC->getAPIntValue().isPowerOf2()) {
17724 if (NeedsCondInvert) // Invert the condition if needed.
17725 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17726 DAG.getConstant(1, Cond.getValueType()));
17728 // Zero extend the condition if needed.
17729 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17731 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17732 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17733 DAG.getConstant(ShAmt, MVT::i8));
17736 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17737 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17738 if (NeedsCondInvert) // Invert the condition if needed.
17739 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17740 DAG.getConstant(1, Cond.getValueType()));
17742 // Zero extend the condition if needed.
17743 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17744 FalseC->getValueType(0), Cond);
17745 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17746 SDValue(FalseC, 0));
17749 // Optimize cases that will turn into an LEA instruction. This requires
17750 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17751 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17752 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17753 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17755 bool isFastMultiplier = false;
17757 switch ((unsigned char)Diff) {
17759 case 1: // result = add base, cond
17760 case 2: // result = lea base( , cond*2)
17761 case 3: // result = lea base(cond, cond*2)
17762 case 4: // result = lea base( , cond*4)
17763 case 5: // result = lea base(cond, cond*4)
17764 case 8: // result = lea base( , cond*8)
17765 case 9: // result = lea base(cond, cond*8)
17766 isFastMultiplier = true;
17771 if (isFastMultiplier) {
17772 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17773 if (NeedsCondInvert) // Invert the condition if needed.
17774 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17775 DAG.getConstant(1, Cond.getValueType()));
17777 // Zero extend the condition if needed.
17778 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17780 // Scale the condition by the difference.
17782 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17783 DAG.getConstant(Diff, Cond.getValueType()));
17785 // Add the base if non-zero.
17786 if (FalseC->getAPIntValue() != 0)
17787 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17788 SDValue(FalseC, 0));
17795 // Canonicalize max and min:
17796 // (x > y) ? x : y -> (x >= y) ? x : y
17797 // (x < y) ? x : y -> (x <= y) ? x : y
17798 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17799 // the need for an extra compare
17800 // against zero. e.g.
17801 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17803 // testl %edi, %edi
17805 // cmovgl %edi, %eax
17809 // cmovsl %eax, %edi
17810 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17811 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17812 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17813 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17818 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17819 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17820 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17821 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17826 // Early exit check
17827 if (!TLI.isTypeLegal(VT))
17830 // Match VSELECTs into subs with unsigned saturation.
17831 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17832 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17833 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17834 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17835 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17837 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17838 // left side invert the predicate to simplify logic below.
17840 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17842 CC = ISD::getSetCCInverse(CC, true);
17843 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17847 if (Other.getNode() && Other->getNumOperands() == 2 &&
17848 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17849 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17850 SDValue CondRHS = Cond->getOperand(1);
17852 // Look for a general sub with unsigned saturation first.
17853 // x >= y ? x-y : 0 --> subus x, y
17854 // x > y ? x-y : 0 --> subus x, y
17855 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17856 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17857 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17859 // If the RHS is a constant we have to reverse the const canonicalization.
17860 // x > C-1 ? x+-C : 0 --> subus x, C
17861 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17862 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17863 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17864 if (CondRHS.getConstantOperandVal(0) == -A-1)
17865 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17866 DAG.getConstant(-A, VT));
17869 // Another special case: If C was a sign bit, the sub has been
17870 // canonicalized into a xor.
17871 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17872 // it's safe to decanonicalize the xor?
17873 // x s< 0 ? x^C : 0 --> subus x, C
17874 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17875 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17876 isSplatVector(OpRHS.getNode())) {
17877 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17879 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17884 // Try to match a min/max vector operation.
17885 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17886 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17887 unsigned Opc = ret.first;
17888 bool NeedSplit = ret.second;
17890 if (Opc && NeedSplit) {
17891 unsigned NumElems = VT.getVectorNumElements();
17892 // Extract the LHS vectors
17893 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17894 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17896 // Extract the RHS vectors
17897 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17898 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17900 // Create min/max for each subvector
17901 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17902 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17904 // Merge the result
17905 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17907 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17910 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17911 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17912 // Check if SETCC has already been promoted
17913 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17914 // Check that condition value type matches vselect operand type
17917 assert(Cond.getValueType().isVector() &&
17918 "vector select expects a vector selector!");
17920 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17921 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17923 if (!TValIsAllOnes && !FValIsAllZeros) {
17924 // Try invert the condition if true value is not all 1s and false value
17926 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17927 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17929 if (TValIsAllZeros || FValIsAllOnes) {
17930 SDValue CC = Cond.getOperand(2);
17931 ISD::CondCode NewCC =
17932 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17933 Cond.getOperand(0).getValueType().isInteger());
17934 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17935 std::swap(LHS, RHS);
17936 TValIsAllOnes = FValIsAllOnes;
17937 FValIsAllZeros = TValIsAllZeros;
17941 if (TValIsAllOnes || FValIsAllZeros) {
17944 if (TValIsAllOnes && FValIsAllZeros)
17946 else if (TValIsAllOnes)
17947 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17948 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17949 else if (FValIsAllZeros)
17950 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17951 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17953 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17957 // Try to fold this VSELECT into a MOVSS/MOVSD
17958 if (N->getOpcode() == ISD::VSELECT &&
17959 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17960 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17961 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17962 bool CanFold = false;
17963 unsigned NumElems = Cond.getNumOperands();
17967 if (isZero(Cond.getOperand(0))) {
17970 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17971 // fold (vselect <0,-1> -> (movsd A, B)
17972 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17973 CanFold = isAllOnes(Cond.getOperand(i));
17974 } else if (isAllOnes(Cond.getOperand(0))) {
17978 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17979 // fold (vselect <-1,0> -> (movsd B, A)
17980 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17981 CanFold = isZero(Cond.getOperand(i));
17985 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17986 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17987 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17990 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17991 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17992 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17993 // (v2i64 (bitcast B)))))
17995 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17996 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17997 // (v2f64 (bitcast B)))))
17999 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18000 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18001 // (v2i64 (bitcast A)))))
18003 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18004 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18005 // (v2f64 (bitcast A)))))
18007 CanFold = (isZero(Cond.getOperand(0)) &&
18008 isZero(Cond.getOperand(1)) &&
18009 isAllOnes(Cond.getOperand(2)) &&
18010 isAllOnes(Cond.getOperand(3)));
18012 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18013 isAllOnes(Cond.getOperand(1)) &&
18014 isZero(Cond.getOperand(2)) &&
18015 isZero(Cond.getOperand(3))) {
18017 std::swap(LHS, RHS);
18021 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18022 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18023 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18024 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18026 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18032 // If we know that this node is legal then we know that it is going to be
18033 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18034 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18035 // to simplify previous instructions.
18036 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18037 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
18038 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18040 // Don't optimize vector selects that map to mask-registers.
18044 // Check all uses of that condition operand to check whether it will be
18045 // consumed by non-BLEND instructions, which may depend on all bits are set
18047 for (SDNode::use_iterator I = Cond->use_begin(),
18048 E = Cond->use_end(); I != E; ++I)
18049 if (I->getOpcode() != ISD::VSELECT)
18050 // TODO: Add other opcodes eventually lowered into BLEND.
18053 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18054 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18056 APInt KnownZero, KnownOne;
18057 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18058 DCI.isBeforeLegalizeOps());
18059 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18060 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18061 DCI.CommitTargetLoweringOpt(TLO);
18067 // Check whether a boolean test is testing a boolean value generated by
18068 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18071 // Simplify the following patterns:
18072 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18073 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18074 // to (Op EFLAGS Cond)
18076 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18077 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18078 // to (Op EFLAGS !Cond)
18080 // where Op could be BRCOND or CMOV.
18082 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18083 // Quit if not CMP and SUB with its value result used.
18084 if (Cmp.getOpcode() != X86ISD::CMP &&
18085 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18088 // Quit if not used as a boolean value.
18089 if (CC != X86::COND_E && CC != X86::COND_NE)
18092 // Check CMP operands. One of them should be 0 or 1 and the other should be
18093 // an SetCC or extended from it.
18094 SDValue Op1 = Cmp.getOperand(0);
18095 SDValue Op2 = Cmp.getOperand(1);
18098 const ConstantSDNode* C = nullptr;
18099 bool needOppositeCond = (CC == X86::COND_E);
18100 bool checkAgainstTrue = false; // Is it a comparison against 1?
18102 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18104 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18106 else // Quit if all operands are not constants.
18109 if (C->getZExtValue() == 1) {
18110 needOppositeCond = !needOppositeCond;
18111 checkAgainstTrue = true;
18112 } else if (C->getZExtValue() != 0)
18113 // Quit if the constant is neither 0 or 1.
18116 bool truncatedToBoolWithAnd = false;
18117 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18118 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18119 SetCC.getOpcode() == ISD::TRUNCATE ||
18120 SetCC.getOpcode() == ISD::AND) {
18121 if (SetCC.getOpcode() == ISD::AND) {
18123 ConstantSDNode *CS;
18124 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18125 CS->getZExtValue() == 1)
18127 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18128 CS->getZExtValue() == 1)
18132 SetCC = SetCC.getOperand(OpIdx);
18133 truncatedToBoolWithAnd = true;
18135 SetCC = SetCC.getOperand(0);
18138 switch (SetCC.getOpcode()) {
18139 case X86ISD::SETCC_CARRY:
18140 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18141 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18142 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18143 // truncated to i1 using 'and'.
18144 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18146 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18147 "Invalid use of SETCC_CARRY!");
18149 case X86ISD::SETCC:
18150 // Set the condition code or opposite one if necessary.
18151 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18152 if (needOppositeCond)
18153 CC = X86::GetOppositeBranchCondition(CC);
18154 return SetCC.getOperand(1);
18155 case X86ISD::CMOV: {
18156 // Check whether false/true value has canonical one, i.e. 0 or 1.
18157 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18158 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18159 // Quit if true value is not a constant.
18162 // Quit if false value is not a constant.
18164 SDValue Op = SetCC.getOperand(0);
18165 // Skip 'zext' or 'trunc' node.
18166 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18167 Op.getOpcode() == ISD::TRUNCATE)
18168 Op = Op.getOperand(0);
18169 // A special case for rdrand/rdseed, where 0 is set if false cond is
18171 if ((Op.getOpcode() != X86ISD::RDRAND &&
18172 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18175 // Quit if false value is not the constant 0 or 1.
18176 bool FValIsFalse = true;
18177 if (FVal && FVal->getZExtValue() != 0) {
18178 if (FVal->getZExtValue() != 1)
18180 // If FVal is 1, opposite cond is needed.
18181 needOppositeCond = !needOppositeCond;
18182 FValIsFalse = false;
18184 // Quit if TVal is not the constant opposite of FVal.
18185 if (FValIsFalse && TVal->getZExtValue() != 1)
18187 if (!FValIsFalse && TVal->getZExtValue() != 0)
18189 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18190 if (needOppositeCond)
18191 CC = X86::GetOppositeBranchCondition(CC);
18192 return SetCC.getOperand(3);
18199 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18200 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18201 TargetLowering::DAGCombinerInfo &DCI,
18202 const X86Subtarget *Subtarget) {
18205 // If the flag operand isn't dead, don't touch this CMOV.
18206 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18209 SDValue FalseOp = N->getOperand(0);
18210 SDValue TrueOp = N->getOperand(1);
18211 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18212 SDValue Cond = N->getOperand(3);
18214 if (CC == X86::COND_E || CC == X86::COND_NE) {
18215 switch (Cond.getOpcode()) {
18219 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18220 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18221 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18227 Flags = checkBoolTestSetCCCombine(Cond, CC);
18228 if (Flags.getNode() &&
18229 // Extra check as FCMOV only supports a subset of X86 cond.
18230 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18231 SDValue Ops[] = { FalseOp, TrueOp,
18232 DAG.getConstant(CC, MVT::i8), Flags };
18233 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18236 // If this is a select between two integer constants, try to do some
18237 // optimizations. Note that the operands are ordered the opposite of SELECT
18239 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18240 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18241 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18242 // larger than FalseC (the false value).
18243 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18244 CC = X86::GetOppositeBranchCondition(CC);
18245 std::swap(TrueC, FalseC);
18246 std::swap(TrueOp, FalseOp);
18249 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18250 // This is efficient for any integer data type (including i8/i16) and
18252 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18253 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18254 DAG.getConstant(CC, MVT::i8), Cond);
18256 // Zero extend the condition if needed.
18257 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18259 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18260 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18261 DAG.getConstant(ShAmt, MVT::i8));
18262 if (N->getNumValues() == 2) // Dead flag value?
18263 return DCI.CombineTo(N, Cond, SDValue());
18267 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18268 // for any integer data type, including i8/i16.
18269 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18270 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18271 DAG.getConstant(CC, MVT::i8), Cond);
18273 // Zero extend the condition if needed.
18274 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18275 FalseC->getValueType(0), Cond);
18276 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18277 SDValue(FalseC, 0));
18279 if (N->getNumValues() == 2) // Dead flag value?
18280 return DCI.CombineTo(N, Cond, SDValue());
18284 // Optimize cases that will turn into an LEA instruction. This requires
18285 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18286 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18287 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18288 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18290 bool isFastMultiplier = false;
18292 switch ((unsigned char)Diff) {
18294 case 1: // result = add base, cond
18295 case 2: // result = lea base( , cond*2)
18296 case 3: // result = lea base(cond, cond*2)
18297 case 4: // result = lea base( , cond*4)
18298 case 5: // result = lea base(cond, cond*4)
18299 case 8: // result = lea base( , cond*8)
18300 case 9: // result = lea base(cond, cond*8)
18301 isFastMultiplier = true;
18306 if (isFastMultiplier) {
18307 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18308 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18309 DAG.getConstant(CC, MVT::i8), Cond);
18310 // Zero extend the condition if needed.
18311 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18313 // Scale the condition by the difference.
18315 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18316 DAG.getConstant(Diff, Cond.getValueType()));
18318 // Add the base if non-zero.
18319 if (FalseC->getAPIntValue() != 0)
18320 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18321 SDValue(FalseC, 0));
18322 if (N->getNumValues() == 2) // Dead flag value?
18323 return DCI.CombineTo(N, Cond, SDValue());
18330 // Handle these cases:
18331 // (select (x != c), e, c) -> select (x != c), e, x),
18332 // (select (x == c), c, e) -> select (x == c), x, e)
18333 // where the c is an integer constant, and the "select" is the combination
18334 // of CMOV and CMP.
18336 // The rationale for this change is that the conditional-move from a constant
18337 // needs two instructions, however, conditional-move from a register needs
18338 // only one instruction.
18340 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18341 // some instruction-combining opportunities. This opt needs to be
18342 // postponed as late as possible.
18344 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18345 // the DCI.xxxx conditions are provided to postpone the optimization as
18346 // late as possible.
18348 ConstantSDNode *CmpAgainst = nullptr;
18349 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18350 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18351 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18353 if (CC == X86::COND_NE &&
18354 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18355 CC = X86::GetOppositeBranchCondition(CC);
18356 std::swap(TrueOp, FalseOp);
18359 if (CC == X86::COND_E &&
18360 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18361 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18362 DAG.getConstant(CC, MVT::i8), Cond };
18363 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18371 /// PerformMulCombine - Optimize a single multiply with constant into two
18372 /// in order to implement it with two cheaper instructions, e.g.
18373 /// LEA + SHL, LEA + LEA.
18374 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18375 TargetLowering::DAGCombinerInfo &DCI) {
18376 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18379 EVT VT = N->getValueType(0);
18380 if (VT != MVT::i64)
18383 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18386 uint64_t MulAmt = C->getZExtValue();
18387 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18390 uint64_t MulAmt1 = 0;
18391 uint64_t MulAmt2 = 0;
18392 if ((MulAmt % 9) == 0) {
18394 MulAmt2 = MulAmt / 9;
18395 } else if ((MulAmt % 5) == 0) {
18397 MulAmt2 = MulAmt / 5;
18398 } else if ((MulAmt % 3) == 0) {
18400 MulAmt2 = MulAmt / 3;
18403 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18406 if (isPowerOf2_64(MulAmt2) &&
18407 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18408 // If second multiplifer is pow2, issue it first. We want the multiply by
18409 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18411 std::swap(MulAmt1, MulAmt2);
18414 if (isPowerOf2_64(MulAmt1))
18415 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18416 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18418 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18419 DAG.getConstant(MulAmt1, VT));
18421 if (isPowerOf2_64(MulAmt2))
18422 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18423 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18425 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18426 DAG.getConstant(MulAmt2, VT));
18428 // Do not add new nodes to DAG combiner worklist.
18429 DCI.CombineTo(N, NewMul, false);
18434 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18435 SDValue N0 = N->getOperand(0);
18436 SDValue N1 = N->getOperand(1);
18437 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18438 EVT VT = N0.getValueType();
18440 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18441 // since the result of setcc_c is all zero's or all ones.
18442 if (VT.isInteger() && !VT.isVector() &&
18443 N1C && N0.getOpcode() == ISD::AND &&
18444 N0.getOperand(1).getOpcode() == ISD::Constant) {
18445 SDValue N00 = N0.getOperand(0);
18446 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18447 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18448 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18449 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18450 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18451 APInt ShAmt = N1C->getAPIntValue();
18452 Mask = Mask.shl(ShAmt);
18454 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18455 N00, DAG.getConstant(Mask, VT));
18459 // Hardware support for vector shifts is sparse which makes us scalarize the
18460 // vector operations in many cases. Also, on sandybridge ADD is faster than
18462 // (shl V, 1) -> add V,V
18463 if (isSplatVector(N1.getNode())) {
18464 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18465 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18466 // We shift all of the values by one. In many cases we do not have
18467 // hardware support for this operation. This is better expressed as an ADD
18469 if (N1C && (1 == N1C->getZExtValue())) {
18470 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18477 /// \brief Returns a vector of 0s if the node in input is a vector logical
18478 /// shift by a constant amount which is known to be bigger than or equal
18479 /// to the vector element size in bits.
18480 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18481 const X86Subtarget *Subtarget) {
18482 EVT VT = N->getValueType(0);
18484 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18485 (!Subtarget->hasInt256() ||
18486 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18489 SDValue Amt = N->getOperand(1);
18491 if (isSplatVector(Amt.getNode())) {
18492 SDValue SclrAmt = Amt->getOperand(0);
18493 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18494 APInt ShiftAmt = C->getAPIntValue();
18495 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18497 // SSE2/AVX2 logical shifts always return a vector of 0s
18498 // if the shift amount is bigger than or equal to
18499 // the element size. The constant shift amount will be
18500 // encoded as a 8-bit immediate.
18501 if (ShiftAmt.trunc(8).uge(MaxAmount))
18502 return getZeroVector(VT, Subtarget, DAG, DL);
18509 /// PerformShiftCombine - Combine shifts.
18510 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18511 TargetLowering::DAGCombinerInfo &DCI,
18512 const X86Subtarget *Subtarget) {
18513 if (N->getOpcode() == ISD::SHL) {
18514 SDValue V = PerformSHLCombine(N, DAG);
18515 if (V.getNode()) return V;
18518 if (N->getOpcode() != ISD::SRA) {
18519 // Try to fold this logical shift into a zero vector.
18520 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18521 if (V.getNode()) return V;
18527 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18528 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18529 // and friends. Likewise for OR -> CMPNEQSS.
18530 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18531 TargetLowering::DAGCombinerInfo &DCI,
18532 const X86Subtarget *Subtarget) {
18535 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18536 // we're requiring SSE2 for both.
18537 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18538 SDValue N0 = N->getOperand(0);
18539 SDValue N1 = N->getOperand(1);
18540 SDValue CMP0 = N0->getOperand(1);
18541 SDValue CMP1 = N1->getOperand(1);
18544 // The SETCCs should both refer to the same CMP.
18545 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18548 SDValue CMP00 = CMP0->getOperand(0);
18549 SDValue CMP01 = CMP0->getOperand(1);
18550 EVT VT = CMP00.getValueType();
18552 if (VT == MVT::f32 || VT == MVT::f64) {
18553 bool ExpectingFlags = false;
18554 // Check for any users that want flags:
18555 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18556 !ExpectingFlags && UI != UE; ++UI)
18557 switch (UI->getOpcode()) {
18562 ExpectingFlags = true;
18564 case ISD::CopyToReg:
18565 case ISD::SIGN_EXTEND:
18566 case ISD::ZERO_EXTEND:
18567 case ISD::ANY_EXTEND:
18571 if (!ExpectingFlags) {
18572 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18573 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18575 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18576 X86::CondCode tmp = cc0;
18581 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18582 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18583 // FIXME: need symbolic constants for these magic numbers.
18584 // See X86ATTInstPrinter.cpp:printSSECC().
18585 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18586 if (Subtarget->hasAVX512()) {
18587 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18588 CMP01, DAG.getConstant(x86cc, MVT::i8));
18589 if (N->getValueType(0) != MVT::i1)
18590 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18594 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18595 CMP00.getValueType(), CMP00, CMP01,
18596 DAG.getConstant(x86cc, MVT::i8));
18598 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18599 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18601 if (is64BitFP && !Subtarget->is64Bit()) {
18602 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18603 // 64-bit integer, since that's not a legal type. Since
18604 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18605 // bits, but can do this little dance to extract the lowest 32 bits
18606 // and work with those going forward.
18607 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18609 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18611 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18612 Vector32, DAG.getIntPtrConstant(0));
18616 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18617 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18618 DAG.getConstant(1, IntVT));
18619 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18620 return OneBitOfTruth;
18628 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18629 /// so it can be folded inside ANDNP.
18630 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18631 EVT VT = N->getValueType(0);
18633 // Match direct AllOnes for 128 and 256-bit vectors
18634 if (ISD::isBuildVectorAllOnes(N))
18637 // Look through a bit convert.
18638 if (N->getOpcode() == ISD::BITCAST)
18639 N = N->getOperand(0).getNode();
18641 // Sometimes the operand may come from a insert_subvector building a 256-bit
18643 if (VT.is256BitVector() &&
18644 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18645 SDValue V1 = N->getOperand(0);
18646 SDValue V2 = N->getOperand(1);
18648 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18649 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18650 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18651 ISD::isBuildVectorAllOnes(V2.getNode()))
18658 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18659 // register. In most cases we actually compare or select YMM-sized registers
18660 // and mixing the two types creates horrible code. This method optimizes
18661 // some of the transition sequences.
18662 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18663 TargetLowering::DAGCombinerInfo &DCI,
18664 const X86Subtarget *Subtarget) {
18665 EVT VT = N->getValueType(0);
18666 if (!VT.is256BitVector())
18669 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18670 N->getOpcode() == ISD::ZERO_EXTEND ||
18671 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18673 SDValue Narrow = N->getOperand(0);
18674 EVT NarrowVT = Narrow->getValueType(0);
18675 if (!NarrowVT.is128BitVector())
18678 if (Narrow->getOpcode() != ISD::XOR &&
18679 Narrow->getOpcode() != ISD::AND &&
18680 Narrow->getOpcode() != ISD::OR)
18683 SDValue N0 = Narrow->getOperand(0);
18684 SDValue N1 = Narrow->getOperand(1);
18687 // The Left side has to be a trunc.
18688 if (N0.getOpcode() != ISD::TRUNCATE)
18691 // The type of the truncated inputs.
18692 EVT WideVT = N0->getOperand(0)->getValueType(0);
18696 // The right side has to be a 'trunc' or a constant vector.
18697 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18698 bool RHSConst = (isSplatVector(N1.getNode()) &&
18699 isa<ConstantSDNode>(N1->getOperand(0)));
18700 if (!RHSTrunc && !RHSConst)
18703 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18705 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18708 // Set N0 and N1 to hold the inputs to the new wide operation.
18709 N0 = N0->getOperand(0);
18711 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18712 N1->getOperand(0));
18713 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18714 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18715 } else if (RHSTrunc) {
18716 N1 = N1->getOperand(0);
18719 // Generate the wide operation.
18720 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18721 unsigned Opcode = N->getOpcode();
18723 case ISD::ANY_EXTEND:
18725 case ISD::ZERO_EXTEND: {
18726 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18727 APInt Mask = APInt::getAllOnesValue(InBits);
18728 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18729 return DAG.getNode(ISD::AND, DL, VT,
18730 Op, DAG.getConstant(Mask, VT));
18732 case ISD::SIGN_EXTEND:
18733 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18734 Op, DAG.getValueType(NarrowVT));
18736 llvm_unreachable("Unexpected opcode");
18740 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18741 TargetLowering::DAGCombinerInfo &DCI,
18742 const X86Subtarget *Subtarget) {
18743 EVT VT = N->getValueType(0);
18744 if (DCI.isBeforeLegalizeOps())
18747 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18751 // Create BEXTR instructions
18752 // BEXTR is ((X >> imm) & (2**size-1))
18753 if (VT == MVT::i32 || VT == MVT::i64) {
18754 SDValue N0 = N->getOperand(0);
18755 SDValue N1 = N->getOperand(1);
18758 // Check for BEXTR.
18759 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18760 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18761 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18762 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18763 if (MaskNode && ShiftNode) {
18764 uint64_t Mask = MaskNode->getZExtValue();
18765 uint64_t Shift = ShiftNode->getZExtValue();
18766 if (isMask_64(Mask)) {
18767 uint64_t MaskSize = CountPopulation_64(Mask);
18768 if (Shift + MaskSize <= VT.getSizeInBits())
18769 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18770 DAG.getConstant(Shift | (MaskSize << 8), VT));
18778 // Want to form ANDNP nodes:
18779 // 1) In the hopes of then easily combining them with OR and AND nodes
18780 // to form PBLEND/PSIGN.
18781 // 2) To match ANDN packed intrinsics
18782 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18785 SDValue N0 = N->getOperand(0);
18786 SDValue N1 = N->getOperand(1);
18789 // Check LHS for vnot
18790 if (N0.getOpcode() == ISD::XOR &&
18791 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18792 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18793 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18795 // Check RHS for vnot
18796 if (N1.getOpcode() == ISD::XOR &&
18797 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18798 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18799 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18804 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18805 TargetLowering::DAGCombinerInfo &DCI,
18806 const X86Subtarget *Subtarget) {
18807 if (DCI.isBeforeLegalizeOps())
18810 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18814 SDValue N0 = N->getOperand(0);
18815 SDValue N1 = N->getOperand(1);
18816 EVT VT = N->getValueType(0);
18818 // look for psign/blend
18819 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18820 if (!Subtarget->hasSSSE3() ||
18821 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18824 // Canonicalize pandn to RHS
18825 if (N0.getOpcode() == X86ISD::ANDNP)
18827 // or (and (m, y), (pandn m, x))
18828 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18829 SDValue Mask = N1.getOperand(0);
18830 SDValue X = N1.getOperand(1);
18832 if (N0.getOperand(0) == Mask)
18833 Y = N0.getOperand(1);
18834 if (N0.getOperand(1) == Mask)
18835 Y = N0.getOperand(0);
18837 // Check to see if the mask appeared in both the AND and ANDNP and
18841 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18842 // Look through mask bitcast.
18843 if (Mask.getOpcode() == ISD::BITCAST)
18844 Mask = Mask.getOperand(0);
18845 if (X.getOpcode() == ISD::BITCAST)
18846 X = X.getOperand(0);
18847 if (Y.getOpcode() == ISD::BITCAST)
18848 Y = Y.getOperand(0);
18850 EVT MaskVT = Mask.getValueType();
18852 // Validate that the Mask operand is a vector sra node.
18853 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18854 // there is no psrai.b
18855 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18856 unsigned SraAmt = ~0;
18857 if (Mask.getOpcode() == ISD::SRA) {
18858 SDValue Amt = Mask.getOperand(1);
18859 if (isSplatVector(Amt.getNode())) {
18860 SDValue SclrAmt = Amt->getOperand(0);
18861 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18862 SraAmt = C->getZExtValue();
18864 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18865 SDValue SraC = Mask.getOperand(1);
18866 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18868 if ((SraAmt + 1) != EltBits)
18873 // Now we know we at least have a plendvb with the mask val. See if
18874 // we can form a psignb/w/d.
18875 // psign = x.type == y.type == mask.type && y = sub(0, x);
18876 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18877 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18878 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18879 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18880 "Unsupported VT for PSIGN");
18881 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18882 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18884 // PBLENDVB only available on SSE 4.1
18885 if (!Subtarget->hasSSE41())
18888 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18890 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18891 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18892 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18893 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18894 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18898 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18901 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18902 MachineFunction &MF = DAG.getMachineFunction();
18903 bool OptForSize = MF.getFunction()->getAttributes().
18904 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18906 // SHLD/SHRD instructions have lower register pressure, but on some
18907 // platforms they have higher latency than the equivalent
18908 // series of shifts/or that would otherwise be generated.
18909 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18910 // have higher latencies and we are not optimizing for size.
18911 if (!OptForSize && Subtarget->isSHLDSlow())
18914 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18916 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18918 if (!N0.hasOneUse() || !N1.hasOneUse())
18921 SDValue ShAmt0 = N0.getOperand(1);
18922 if (ShAmt0.getValueType() != MVT::i8)
18924 SDValue ShAmt1 = N1.getOperand(1);
18925 if (ShAmt1.getValueType() != MVT::i8)
18927 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18928 ShAmt0 = ShAmt0.getOperand(0);
18929 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18930 ShAmt1 = ShAmt1.getOperand(0);
18933 unsigned Opc = X86ISD::SHLD;
18934 SDValue Op0 = N0.getOperand(0);
18935 SDValue Op1 = N1.getOperand(0);
18936 if (ShAmt0.getOpcode() == ISD::SUB) {
18937 Opc = X86ISD::SHRD;
18938 std::swap(Op0, Op1);
18939 std::swap(ShAmt0, ShAmt1);
18942 unsigned Bits = VT.getSizeInBits();
18943 if (ShAmt1.getOpcode() == ISD::SUB) {
18944 SDValue Sum = ShAmt1.getOperand(0);
18945 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18946 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18947 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18948 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18949 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18950 return DAG.getNode(Opc, DL, VT,
18952 DAG.getNode(ISD::TRUNCATE, DL,
18955 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18956 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18958 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18959 return DAG.getNode(Opc, DL, VT,
18960 N0.getOperand(0), N1.getOperand(0),
18961 DAG.getNode(ISD::TRUNCATE, DL,
18968 // Generate NEG and CMOV for integer abs.
18969 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18970 EVT VT = N->getValueType(0);
18972 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18973 // 8-bit integer abs to NEG and CMOV.
18974 if (VT.isInteger() && VT.getSizeInBits() == 8)
18977 SDValue N0 = N->getOperand(0);
18978 SDValue N1 = N->getOperand(1);
18981 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18982 // and change it to SUB and CMOV.
18983 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18984 N0.getOpcode() == ISD::ADD &&
18985 N0.getOperand(1) == N1 &&
18986 N1.getOpcode() == ISD::SRA &&
18987 N1.getOperand(0) == N0.getOperand(0))
18988 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18989 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18990 // Generate SUB & CMOV.
18991 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18992 DAG.getConstant(0, VT), N0.getOperand(0));
18994 SDValue Ops[] = { N0.getOperand(0), Neg,
18995 DAG.getConstant(X86::COND_GE, MVT::i8),
18996 SDValue(Neg.getNode(), 1) };
18997 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19002 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19003 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19004 TargetLowering::DAGCombinerInfo &DCI,
19005 const X86Subtarget *Subtarget) {
19006 if (DCI.isBeforeLegalizeOps())
19009 if (Subtarget->hasCMov()) {
19010 SDValue RV = performIntegerAbsCombine(N, DAG);
19018 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19019 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19020 TargetLowering::DAGCombinerInfo &DCI,
19021 const X86Subtarget *Subtarget) {
19022 LoadSDNode *Ld = cast<LoadSDNode>(N);
19023 EVT RegVT = Ld->getValueType(0);
19024 EVT MemVT = Ld->getMemoryVT();
19026 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19027 unsigned RegSz = RegVT.getSizeInBits();
19029 // On Sandybridge unaligned 256bit loads are inefficient.
19030 ISD::LoadExtType Ext = Ld->getExtensionType();
19031 unsigned Alignment = Ld->getAlignment();
19032 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19033 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19034 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19035 unsigned NumElems = RegVT.getVectorNumElements();
19039 SDValue Ptr = Ld->getBasePtr();
19040 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19042 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19044 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19045 Ld->getPointerInfo(), Ld->isVolatile(),
19046 Ld->isNonTemporal(), Ld->isInvariant(),
19048 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19049 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19050 Ld->getPointerInfo(), Ld->isVolatile(),
19051 Ld->isNonTemporal(), Ld->isInvariant(),
19052 std::min(16U, Alignment));
19053 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19055 Load2.getValue(1));
19057 SDValue NewVec = DAG.getUNDEF(RegVT);
19058 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19059 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19060 return DCI.CombineTo(N, NewVec, TF, true);
19063 // If this is a vector EXT Load then attempt to optimize it using a
19064 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19065 // expansion is still better than scalar code.
19066 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19067 // emit a shuffle and a arithmetic shift.
19068 // TODO: It is possible to support ZExt by zeroing the undef values
19069 // during the shuffle phase or after the shuffle.
19070 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19071 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19072 assert(MemVT != RegVT && "Cannot extend to the same type");
19073 assert(MemVT.isVector() && "Must load a vector from memory");
19075 unsigned NumElems = RegVT.getVectorNumElements();
19076 unsigned MemSz = MemVT.getSizeInBits();
19077 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19079 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19082 // All sizes must be a power of two.
19083 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19086 // Attempt to load the original value using scalar loads.
19087 // Find the largest scalar type that divides the total loaded size.
19088 MVT SclrLoadTy = MVT::i8;
19089 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19090 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19091 MVT Tp = (MVT::SimpleValueType)tp;
19092 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19097 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19098 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19100 SclrLoadTy = MVT::f64;
19102 // Calculate the number of scalar loads that we need to perform
19103 // in order to load our vector from memory.
19104 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19105 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19108 unsigned loadRegZize = RegSz;
19109 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19112 // Represent our vector as a sequence of elements which are the
19113 // largest scalar that we can load.
19114 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19115 loadRegZize/SclrLoadTy.getSizeInBits());
19117 // Represent the data using the same element type that is stored in
19118 // memory. In practice, we ''widen'' MemVT.
19120 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19121 loadRegZize/MemVT.getScalarType().getSizeInBits());
19123 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19124 "Invalid vector type");
19126 // We can't shuffle using an illegal type.
19127 if (!TLI.isTypeLegal(WideVecVT))
19130 SmallVector<SDValue, 8> Chains;
19131 SDValue Ptr = Ld->getBasePtr();
19132 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19133 TLI.getPointerTy());
19134 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19136 for (unsigned i = 0; i < NumLoads; ++i) {
19137 // Perform a single load.
19138 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19139 Ptr, Ld->getPointerInfo(),
19140 Ld->isVolatile(), Ld->isNonTemporal(),
19141 Ld->isInvariant(), Ld->getAlignment());
19142 Chains.push_back(ScalarLoad.getValue(1));
19143 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19144 // another round of DAGCombining.
19146 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19148 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19149 ScalarLoad, DAG.getIntPtrConstant(i));
19151 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19154 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19156 // Bitcast the loaded value to a vector of the original element type, in
19157 // the size of the target vector type.
19158 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19159 unsigned SizeRatio = RegSz/MemSz;
19161 if (Ext == ISD::SEXTLOAD) {
19162 // If we have SSE4.1 we can directly emit a VSEXT node.
19163 if (Subtarget->hasSSE41()) {
19164 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19165 return DCI.CombineTo(N, Sext, TF, true);
19168 // Otherwise we'll shuffle the small elements in the high bits of the
19169 // larger type and perform an arithmetic shift. If the shift is not legal
19170 // it's better to scalarize.
19171 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19174 // Redistribute the loaded elements into the different locations.
19175 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19176 for (unsigned i = 0; i != NumElems; ++i)
19177 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19179 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19180 DAG.getUNDEF(WideVecVT),
19183 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19185 // Build the arithmetic shift.
19186 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19187 MemVT.getVectorElementType().getSizeInBits();
19188 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19189 DAG.getConstant(Amt, RegVT));
19191 return DCI.CombineTo(N, Shuff, TF, true);
19194 // Redistribute the loaded elements into the different locations.
19195 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19196 for (unsigned i = 0; i != NumElems; ++i)
19197 ShuffleVec[i*SizeRatio] = i;
19199 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19200 DAG.getUNDEF(WideVecVT),
19203 // Bitcast to the requested type.
19204 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19205 // Replace the original load with the new sequence
19206 // and return the new chain.
19207 return DCI.CombineTo(N, Shuff, TF, true);
19213 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19214 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19215 const X86Subtarget *Subtarget) {
19216 StoreSDNode *St = cast<StoreSDNode>(N);
19217 EVT VT = St->getValue().getValueType();
19218 EVT StVT = St->getMemoryVT();
19220 SDValue StoredVal = St->getOperand(1);
19221 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19223 // If we are saving a concatenation of two XMM registers, perform two stores.
19224 // On Sandy Bridge, 256-bit memory operations are executed by two
19225 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19226 // memory operation.
19227 unsigned Alignment = St->getAlignment();
19228 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19229 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19230 StVT == VT && !IsAligned) {
19231 unsigned NumElems = VT.getVectorNumElements();
19235 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19236 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19238 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19239 SDValue Ptr0 = St->getBasePtr();
19240 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19242 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19243 St->getPointerInfo(), St->isVolatile(),
19244 St->isNonTemporal(), Alignment);
19245 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19246 St->getPointerInfo(), St->isVolatile(),
19247 St->isNonTemporal(),
19248 std::min(16U, Alignment));
19249 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19252 // Optimize trunc store (of multiple scalars) to shuffle and store.
19253 // First, pack all of the elements in one place. Next, store to memory
19254 // in fewer chunks.
19255 if (St->isTruncatingStore() && VT.isVector()) {
19256 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19257 unsigned NumElems = VT.getVectorNumElements();
19258 assert(StVT != VT && "Cannot truncate to the same type");
19259 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19260 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19262 // From, To sizes and ElemCount must be pow of two
19263 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19264 // We are going to use the original vector elt for storing.
19265 // Accumulated smaller vector elements must be a multiple of the store size.
19266 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19268 unsigned SizeRatio = FromSz / ToSz;
19270 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19272 // Create a type on which we perform the shuffle
19273 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19274 StVT.getScalarType(), NumElems*SizeRatio);
19276 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19278 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19279 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19280 for (unsigned i = 0; i != NumElems; ++i)
19281 ShuffleVec[i] = i * SizeRatio;
19283 // Can't shuffle using an illegal type.
19284 if (!TLI.isTypeLegal(WideVecVT))
19287 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19288 DAG.getUNDEF(WideVecVT),
19290 // At this point all of the data is stored at the bottom of the
19291 // register. We now need to save it to mem.
19293 // Find the largest store unit
19294 MVT StoreType = MVT::i8;
19295 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19296 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19297 MVT Tp = (MVT::SimpleValueType)tp;
19298 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19302 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19303 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19304 (64 <= NumElems * ToSz))
19305 StoreType = MVT::f64;
19307 // Bitcast the original vector into a vector of store-size units
19308 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19309 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19310 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19311 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19312 SmallVector<SDValue, 8> Chains;
19313 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19314 TLI.getPointerTy());
19315 SDValue Ptr = St->getBasePtr();
19317 // Perform one or more big stores into memory.
19318 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19319 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19320 StoreType, ShuffWide,
19321 DAG.getIntPtrConstant(i));
19322 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19323 St->getPointerInfo(), St->isVolatile(),
19324 St->isNonTemporal(), St->getAlignment());
19325 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19326 Chains.push_back(Ch);
19329 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19332 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19333 // the FP state in cases where an emms may be missing.
19334 // A preferable solution to the general problem is to figure out the right
19335 // places to insert EMMS. This qualifies as a quick hack.
19337 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19338 if (VT.getSizeInBits() != 64)
19341 const Function *F = DAG.getMachineFunction().getFunction();
19342 bool NoImplicitFloatOps = F->getAttributes().
19343 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19344 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19345 && Subtarget->hasSSE2();
19346 if ((VT.isVector() ||
19347 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19348 isa<LoadSDNode>(St->getValue()) &&
19349 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19350 St->getChain().hasOneUse() && !St->isVolatile()) {
19351 SDNode* LdVal = St->getValue().getNode();
19352 LoadSDNode *Ld = nullptr;
19353 int TokenFactorIndex = -1;
19354 SmallVector<SDValue, 8> Ops;
19355 SDNode* ChainVal = St->getChain().getNode();
19356 // Must be a store of a load. We currently handle two cases: the load
19357 // is a direct child, and it's under an intervening TokenFactor. It is
19358 // possible to dig deeper under nested TokenFactors.
19359 if (ChainVal == LdVal)
19360 Ld = cast<LoadSDNode>(St->getChain());
19361 else if (St->getValue().hasOneUse() &&
19362 ChainVal->getOpcode() == ISD::TokenFactor) {
19363 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19364 if (ChainVal->getOperand(i).getNode() == LdVal) {
19365 TokenFactorIndex = i;
19366 Ld = cast<LoadSDNode>(St->getValue());
19368 Ops.push_back(ChainVal->getOperand(i));
19372 if (!Ld || !ISD::isNormalLoad(Ld))
19375 // If this is not the MMX case, i.e. we are just turning i64 load/store
19376 // into f64 load/store, avoid the transformation if there are multiple
19377 // uses of the loaded value.
19378 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19383 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19384 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19386 if (Subtarget->is64Bit() || F64IsLegal) {
19387 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19388 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19389 Ld->getPointerInfo(), Ld->isVolatile(),
19390 Ld->isNonTemporal(), Ld->isInvariant(),
19391 Ld->getAlignment());
19392 SDValue NewChain = NewLd.getValue(1);
19393 if (TokenFactorIndex != -1) {
19394 Ops.push_back(NewChain);
19395 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19397 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19398 St->getPointerInfo(),
19399 St->isVolatile(), St->isNonTemporal(),
19400 St->getAlignment());
19403 // Otherwise, lower to two pairs of 32-bit loads / stores.
19404 SDValue LoAddr = Ld->getBasePtr();
19405 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19406 DAG.getConstant(4, MVT::i32));
19408 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19409 Ld->getPointerInfo(),
19410 Ld->isVolatile(), Ld->isNonTemporal(),
19411 Ld->isInvariant(), Ld->getAlignment());
19412 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19413 Ld->getPointerInfo().getWithOffset(4),
19414 Ld->isVolatile(), Ld->isNonTemporal(),
19416 MinAlign(Ld->getAlignment(), 4));
19418 SDValue NewChain = LoLd.getValue(1);
19419 if (TokenFactorIndex != -1) {
19420 Ops.push_back(LoLd);
19421 Ops.push_back(HiLd);
19422 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19425 LoAddr = St->getBasePtr();
19426 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19427 DAG.getConstant(4, MVT::i32));
19429 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19430 St->getPointerInfo(),
19431 St->isVolatile(), St->isNonTemporal(),
19432 St->getAlignment());
19433 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19434 St->getPointerInfo().getWithOffset(4),
19436 St->isNonTemporal(),
19437 MinAlign(St->getAlignment(), 4));
19438 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19443 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19444 /// and return the operands for the horizontal operation in LHS and RHS. A
19445 /// horizontal operation performs the binary operation on successive elements
19446 /// of its first operand, then on successive elements of its second operand,
19447 /// returning the resulting values in a vector. For example, if
19448 /// A = < float a0, float a1, float a2, float a3 >
19450 /// B = < float b0, float b1, float b2, float b3 >
19451 /// then the result of doing a horizontal operation on A and B is
19452 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19453 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19454 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19455 /// set to A, RHS to B, and the routine returns 'true'.
19456 /// Note that the binary operation should have the property that if one of the
19457 /// operands is UNDEF then the result is UNDEF.
19458 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19459 // Look for the following pattern: if
19460 // A = < float a0, float a1, float a2, float a3 >
19461 // B = < float b0, float b1, float b2, float b3 >
19463 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19464 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19465 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19466 // which is A horizontal-op B.
19468 // At least one of the operands should be a vector shuffle.
19469 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19470 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19473 MVT VT = LHS.getSimpleValueType();
19475 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19476 "Unsupported vector type for horizontal add/sub");
19478 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19479 // operate independently on 128-bit lanes.
19480 unsigned NumElts = VT.getVectorNumElements();
19481 unsigned NumLanes = VT.getSizeInBits()/128;
19482 unsigned NumLaneElts = NumElts / NumLanes;
19483 assert((NumLaneElts % 2 == 0) &&
19484 "Vector type should have an even number of elements in each lane");
19485 unsigned HalfLaneElts = NumLaneElts/2;
19487 // View LHS in the form
19488 // LHS = VECTOR_SHUFFLE A, B, LMask
19489 // If LHS is not a shuffle then pretend it is the shuffle
19490 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19491 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19494 SmallVector<int, 16> LMask(NumElts);
19495 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19496 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19497 A = LHS.getOperand(0);
19498 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19499 B = LHS.getOperand(1);
19500 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19501 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19503 if (LHS.getOpcode() != ISD::UNDEF)
19505 for (unsigned i = 0; i != NumElts; ++i)
19509 // Likewise, view RHS in the form
19510 // RHS = VECTOR_SHUFFLE C, D, RMask
19512 SmallVector<int, 16> RMask(NumElts);
19513 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19514 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19515 C = RHS.getOperand(0);
19516 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19517 D = RHS.getOperand(1);
19518 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19519 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19521 if (RHS.getOpcode() != ISD::UNDEF)
19523 for (unsigned i = 0; i != NumElts; ++i)
19527 // Check that the shuffles are both shuffling the same vectors.
19528 if (!(A == C && B == D) && !(A == D && B == C))
19531 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19532 if (!A.getNode() && !B.getNode())
19535 // If A and B occur in reverse order in RHS, then "swap" them (which means
19536 // rewriting the mask).
19538 CommuteVectorShuffleMask(RMask, NumElts);
19540 // At this point LHS and RHS are equivalent to
19541 // LHS = VECTOR_SHUFFLE A, B, LMask
19542 // RHS = VECTOR_SHUFFLE A, B, RMask
19543 // Check that the masks correspond to performing a horizontal operation.
19544 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19545 for (unsigned i = 0; i != NumLaneElts; ++i) {
19546 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19548 // Ignore any UNDEF components.
19549 if (LIdx < 0 || RIdx < 0 ||
19550 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19551 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19554 // Check that successive elements are being operated on. If not, this is
19555 // not a horizontal operation.
19556 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19557 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19558 if (!(LIdx == Index && RIdx == Index + 1) &&
19559 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19564 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19565 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19569 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19570 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19571 const X86Subtarget *Subtarget) {
19572 EVT VT = N->getValueType(0);
19573 SDValue LHS = N->getOperand(0);
19574 SDValue RHS = N->getOperand(1);
19576 // Try to synthesize horizontal adds from adds of shuffles.
19577 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19578 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19579 isHorizontalBinOp(LHS, RHS, true))
19580 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19584 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19585 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19586 const X86Subtarget *Subtarget) {
19587 EVT VT = N->getValueType(0);
19588 SDValue LHS = N->getOperand(0);
19589 SDValue RHS = N->getOperand(1);
19591 // Try to synthesize horizontal subs from subs of shuffles.
19592 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19593 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19594 isHorizontalBinOp(LHS, RHS, false))
19595 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19599 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19600 /// X86ISD::FXOR nodes.
19601 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19602 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19603 // F[X]OR(0.0, x) -> x
19604 // F[X]OR(x, 0.0) -> x
19605 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19606 if (C->getValueAPF().isPosZero())
19607 return N->getOperand(1);
19608 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19609 if (C->getValueAPF().isPosZero())
19610 return N->getOperand(0);
19614 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19615 /// X86ISD::FMAX nodes.
19616 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19617 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19619 // Only perform optimizations if UnsafeMath is used.
19620 if (!DAG.getTarget().Options.UnsafeFPMath)
19623 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19624 // into FMINC and FMAXC, which are Commutative operations.
19625 unsigned NewOp = 0;
19626 switch (N->getOpcode()) {
19627 default: llvm_unreachable("unknown opcode");
19628 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19629 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19632 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19633 N->getOperand(0), N->getOperand(1));
19636 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19637 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19638 // FAND(0.0, x) -> 0.0
19639 // FAND(x, 0.0) -> 0.0
19640 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19641 if (C->getValueAPF().isPosZero())
19642 return N->getOperand(0);
19643 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19644 if (C->getValueAPF().isPosZero())
19645 return N->getOperand(1);
19649 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19650 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19651 // FANDN(x, 0.0) -> 0.0
19652 // FANDN(0.0, x) -> x
19653 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19654 if (C->getValueAPF().isPosZero())
19655 return N->getOperand(1);
19656 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19657 if (C->getValueAPF().isPosZero())
19658 return N->getOperand(1);
19662 static SDValue PerformBTCombine(SDNode *N,
19664 TargetLowering::DAGCombinerInfo &DCI) {
19665 // BT ignores high bits in the bit index operand.
19666 SDValue Op1 = N->getOperand(1);
19667 if (Op1.hasOneUse()) {
19668 unsigned BitWidth = Op1.getValueSizeInBits();
19669 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19670 APInt KnownZero, KnownOne;
19671 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19672 !DCI.isBeforeLegalizeOps());
19673 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19674 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19675 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19676 DCI.CommitTargetLoweringOpt(TLO);
19681 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19682 SDValue Op = N->getOperand(0);
19683 if (Op.getOpcode() == ISD::BITCAST)
19684 Op = Op.getOperand(0);
19685 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19686 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19687 VT.getVectorElementType().getSizeInBits() ==
19688 OpVT.getVectorElementType().getSizeInBits()) {
19689 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19694 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19695 const X86Subtarget *Subtarget) {
19696 EVT VT = N->getValueType(0);
19697 if (!VT.isVector())
19700 SDValue N0 = N->getOperand(0);
19701 SDValue N1 = N->getOperand(1);
19702 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19705 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19706 // both SSE and AVX2 since there is no sign-extended shift right
19707 // operation on a vector with 64-bit elements.
19708 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19709 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19710 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19711 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19712 SDValue N00 = N0.getOperand(0);
19714 // EXTLOAD has a better solution on AVX2,
19715 // it may be replaced with X86ISD::VSEXT node.
19716 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19717 if (!ISD::isNormalLoad(N00.getNode()))
19720 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19721 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19723 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19729 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19730 TargetLowering::DAGCombinerInfo &DCI,
19731 const X86Subtarget *Subtarget) {
19732 if (!DCI.isBeforeLegalizeOps())
19735 if (!Subtarget->hasFp256())
19738 EVT VT = N->getValueType(0);
19739 if (VT.isVector() && VT.getSizeInBits() == 256) {
19740 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19748 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19749 const X86Subtarget* Subtarget) {
19751 EVT VT = N->getValueType(0);
19753 // Let legalize expand this if it isn't a legal type yet.
19754 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19757 EVT ScalarVT = VT.getScalarType();
19758 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19759 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19762 SDValue A = N->getOperand(0);
19763 SDValue B = N->getOperand(1);
19764 SDValue C = N->getOperand(2);
19766 bool NegA = (A.getOpcode() == ISD::FNEG);
19767 bool NegB = (B.getOpcode() == ISD::FNEG);
19768 bool NegC = (C.getOpcode() == ISD::FNEG);
19770 // Negative multiplication when NegA xor NegB
19771 bool NegMul = (NegA != NegB);
19773 A = A.getOperand(0);
19775 B = B.getOperand(0);
19777 C = C.getOperand(0);
19781 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19783 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19785 return DAG.getNode(Opcode, dl, VT, A, B, C);
19788 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19789 TargetLowering::DAGCombinerInfo &DCI,
19790 const X86Subtarget *Subtarget) {
19791 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19792 // (and (i32 x86isd::setcc_carry), 1)
19793 // This eliminates the zext. This transformation is necessary because
19794 // ISD::SETCC is always legalized to i8.
19796 SDValue N0 = N->getOperand(0);
19797 EVT VT = N->getValueType(0);
19799 if (N0.getOpcode() == ISD::AND &&
19801 N0.getOperand(0).hasOneUse()) {
19802 SDValue N00 = N0.getOperand(0);
19803 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19804 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19805 if (!C || C->getZExtValue() != 1)
19807 return DAG.getNode(ISD::AND, dl, VT,
19808 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19809 N00.getOperand(0), N00.getOperand(1)),
19810 DAG.getConstant(1, VT));
19814 if (N0.getOpcode() == ISD::TRUNCATE &&
19816 N0.getOperand(0).hasOneUse()) {
19817 SDValue N00 = N0.getOperand(0);
19818 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19819 return DAG.getNode(ISD::AND, dl, VT,
19820 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19821 N00.getOperand(0), N00.getOperand(1)),
19822 DAG.getConstant(1, VT));
19825 if (VT.is256BitVector()) {
19826 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19834 // Optimize x == -y --> x+y == 0
19835 // x != -y --> x+y != 0
19836 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19837 const X86Subtarget* Subtarget) {
19838 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19839 SDValue LHS = N->getOperand(0);
19840 SDValue RHS = N->getOperand(1);
19841 EVT VT = N->getValueType(0);
19844 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19845 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19846 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19847 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19848 LHS.getValueType(), RHS, LHS.getOperand(1));
19849 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19850 addV, DAG.getConstant(0, addV.getValueType()), CC);
19852 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19854 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19855 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19856 RHS.getValueType(), LHS, RHS.getOperand(1));
19857 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19858 addV, DAG.getConstant(0, addV.getValueType()), CC);
19861 if (VT.getScalarType() == MVT::i1) {
19862 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19863 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19864 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19865 if (!IsSEXT0 && !IsVZero0)
19867 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19868 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19869 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19871 if (!IsSEXT1 && !IsVZero1)
19874 if (IsSEXT0 && IsVZero1) {
19875 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19876 if (CC == ISD::SETEQ)
19877 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19878 return LHS.getOperand(0);
19880 if (IsSEXT1 && IsVZero0) {
19881 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19882 if (CC == ISD::SETEQ)
19883 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19884 return RHS.getOperand(0);
19891 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19892 // as "sbb reg,reg", since it can be extended without zext and produces
19893 // an all-ones bit which is more useful than 0/1 in some cases.
19894 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19897 return DAG.getNode(ISD::AND, DL, VT,
19898 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19899 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19900 DAG.getConstant(1, VT));
19901 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19902 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19903 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19904 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19907 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19908 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19909 TargetLowering::DAGCombinerInfo &DCI,
19910 const X86Subtarget *Subtarget) {
19912 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19913 SDValue EFLAGS = N->getOperand(1);
19915 if (CC == X86::COND_A) {
19916 // Try to convert COND_A into COND_B in an attempt to facilitate
19917 // materializing "setb reg".
19919 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19920 // cannot take an immediate as its first operand.
19922 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19923 EFLAGS.getValueType().isInteger() &&
19924 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19925 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19926 EFLAGS.getNode()->getVTList(),
19927 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19928 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19929 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19933 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19934 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19936 if (CC == X86::COND_B)
19937 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19941 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19942 if (Flags.getNode()) {
19943 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19944 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19950 // Optimize branch condition evaluation.
19952 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19953 TargetLowering::DAGCombinerInfo &DCI,
19954 const X86Subtarget *Subtarget) {
19956 SDValue Chain = N->getOperand(0);
19957 SDValue Dest = N->getOperand(1);
19958 SDValue EFLAGS = N->getOperand(3);
19959 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19963 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19964 if (Flags.getNode()) {
19965 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19966 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19973 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19974 const X86TargetLowering *XTLI) {
19975 SDValue Op0 = N->getOperand(0);
19976 EVT InVT = Op0->getValueType(0);
19978 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19979 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19981 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19982 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19983 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19986 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19987 // a 32-bit target where SSE doesn't support i64->FP operations.
19988 if (Op0.getOpcode() == ISD::LOAD) {
19989 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19990 EVT VT = Ld->getValueType(0);
19991 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19992 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19993 !XTLI->getSubtarget()->is64Bit() &&
19995 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19996 Ld->getChain(), Op0, DAG);
19997 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20004 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20005 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20006 X86TargetLowering::DAGCombinerInfo &DCI) {
20007 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20008 // the result is either zero or one (depending on the input carry bit).
20009 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20010 if (X86::isZeroNode(N->getOperand(0)) &&
20011 X86::isZeroNode(N->getOperand(1)) &&
20012 // We don't have a good way to replace an EFLAGS use, so only do this when
20014 SDValue(N, 1).use_empty()) {
20016 EVT VT = N->getValueType(0);
20017 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20018 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20019 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20020 DAG.getConstant(X86::COND_B,MVT::i8),
20022 DAG.getConstant(1, VT));
20023 return DCI.CombineTo(N, Res1, CarryOut);
20029 // fold (add Y, (sete X, 0)) -> adc 0, Y
20030 // (add Y, (setne X, 0)) -> sbb -1, Y
20031 // (sub (sete X, 0), Y) -> sbb 0, Y
20032 // (sub (setne X, 0), Y) -> adc -1, Y
20033 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20036 // Look through ZExts.
20037 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20038 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20041 SDValue SetCC = Ext.getOperand(0);
20042 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20045 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20046 if (CC != X86::COND_E && CC != X86::COND_NE)
20049 SDValue Cmp = SetCC.getOperand(1);
20050 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20051 !X86::isZeroNode(Cmp.getOperand(1)) ||
20052 !Cmp.getOperand(0).getValueType().isInteger())
20055 SDValue CmpOp0 = Cmp.getOperand(0);
20056 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20057 DAG.getConstant(1, CmpOp0.getValueType()));
20059 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20060 if (CC == X86::COND_NE)
20061 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20062 DL, OtherVal.getValueType(), OtherVal,
20063 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20064 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20065 DL, OtherVal.getValueType(), OtherVal,
20066 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20069 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20070 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20071 const X86Subtarget *Subtarget) {
20072 EVT VT = N->getValueType(0);
20073 SDValue Op0 = N->getOperand(0);
20074 SDValue Op1 = N->getOperand(1);
20076 // Try to synthesize horizontal adds from adds of shuffles.
20077 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20078 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20079 isHorizontalBinOp(Op0, Op1, true))
20080 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20082 return OptimizeConditionalInDecrement(N, DAG);
20085 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20086 const X86Subtarget *Subtarget) {
20087 SDValue Op0 = N->getOperand(0);
20088 SDValue Op1 = N->getOperand(1);
20090 // X86 can't encode an immediate LHS of a sub. See if we can push the
20091 // negation into a preceding instruction.
20092 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20093 // If the RHS of the sub is a XOR with one use and a constant, invert the
20094 // immediate. Then add one to the LHS of the sub so we can turn
20095 // X-Y -> X+~Y+1, saving one register.
20096 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20097 isa<ConstantSDNode>(Op1.getOperand(1))) {
20098 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20099 EVT VT = Op0.getValueType();
20100 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20102 DAG.getConstant(~XorC, VT));
20103 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20104 DAG.getConstant(C->getAPIntValue()+1, VT));
20108 // Try to synthesize horizontal adds from adds of shuffles.
20109 EVT VT = N->getValueType(0);
20110 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20111 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20112 isHorizontalBinOp(Op0, Op1, true))
20113 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20115 return OptimizeConditionalInDecrement(N, DAG);
20118 /// performVZEXTCombine - Performs build vector combines
20119 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20120 TargetLowering::DAGCombinerInfo &DCI,
20121 const X86Subtarget *Subtarget) {
20122 // (vzext (bitcast (vzext (x)) -> (vzext x)
20123 SDValue In = N->getOperand(0);
20124 while (In.getOpcode() == ISD::BITCAST)
20125 In = In.getOperand(0);
20127 if (In.getOpcode() != X86ISD::VZEXT)
20130 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20134 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20135 DAGCombinerInfo &DCI) const {
20136 SelectionDAG &DAG = DCI.DAG;
20137 switch (N->getOpcode()) {
20139 case ISD::EXTRACT_VECTOR_ELT:
20140 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20142 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20143 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20144 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20145 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20146 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20147 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20150 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20151 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20152 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20153 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20154 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20155 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20156 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20157 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20158 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20160 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20162 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20163 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20164 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20165 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20166 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20167 case ISD::ANY_EXTEND:
20168 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20169 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20170 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20171 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20172 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20173 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20174 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20175 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20176 case X86ISD::SHUFP: // Handle all target specific shuffles
20177 case X86ISD::PALIGNR:
20178 case X86ISD::UNPCKH:
20179 case X86ISD::UNPCKL:
20180 case X86ISD::MOVHLPS:
20181 case X86ISD::MOVLHPS:
20182 case X86ISD::PSHUFD:
20183 case X86ISD::PSHUFHW:
20184 case X86ISD::PSHUFLW:
20185 case X86ISD::MOVSS:
20186 case X86ISD::MOVSD:
20187 case X86ISD::VPERMILP:
20188 case X86ISD::VPERM2X128:
20189 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20190 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20196 /// isTypeDesirableForOp - Return true if the target has native support for
20197 /// the specified value type and it is 'desirable' to use the type for the
20198 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20199 /// instruction encodings are longer and some i16 instructions are slow.
20200 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20201 if (!isTypeLegal(VT))
20203 if (VT != MVT::i16)
20210 case ISD::SIGN_EXTEND:
20211 case ISD::ZERO_EXTEND:
20212 case ISD::ANY_EXTEND:
20225 /// IsDesirableToPromoteOp - This method query the target whether it is
20226 /// beneficial for dag combiner to promote the specified node. If true, it
20227 /// should return the desired promotion type by reference.
20228 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20229 EVT VT = Op.getValueType();
20230 if (VT != MVT::i16)
20233 bool Promote = false;
20234 bool Commute = false;
20235 switch (Op.getOpcode()) {
20238 LoadSDNode *LD = cast<LoadSDNode>(Op);
20239 // If the non-extending load has a single use and it's not live out, then it
20240 // might be folded.
20241 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20242 Op.hasOneUse()*/) {
20243 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20244 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20245 // The only case where we'd want to promote LOAD (rather then it being
20246 // promoted as an operand is when it's only use is liveout.
20247 if (UI->getOpcode() != ISD::CopyToReg)
20254 case ISD::SIGN_EXTEND:
20255 case ISD::ZERO_EXTEND:
20256 case ISD::ANY_EXTEND:
20261 SDValue N0 = Op.getOperand(0);
20262 // Look out for (store (shl (load), x)).
20263 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20276 SDValue N0 = Op.getOperand(0);
20277 SDValue N1 = Op.getOperand(1);
20278 if (!Commute && MayFoldLoad(N1))
20280 // Avoid disabling potential load folding opportunities.
20281 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20283 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20293 //===----------------------------------------------------------------------===//
20294 // X86 Inline Assembly Support
20295 //===----------------------------------------------------------------------===//
20298 // Helper to match a string separated by whitespace.
20299 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20300 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20302 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20303 StringRef piece(*args[i]);
20304 if (!s.startswith(piece)) // Check if the piece matches.
20307 s = s.substr(piece.size());
20308 StringRef::size_type pos = s.find_first_not_of(" \t");
20309 if (pos == 0) // We matched a prefix.
20317 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20320 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20322 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20323 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20324 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20325 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20327 if (AsmPieces.size() == 3)
20329 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20336 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20337 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20339 std::string AsmStr = IA->getAsmString();
20341 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20342 if (!Ty || Ty->getBitWidth() % 16 != 0)
20345 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20346 SmallVector<StringRef, 4> AsmPieces;
20347 SplitString(AsmStr, AsmPieces, ";\n");
20349 switch (AsmPieces.size()) {
20350 default: return false;
20352 // FIXME: this should verify that we are targeting a 486 or better. If not,
20353 // we will turn this bswap into something that will be lowered to logical
20354 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20355 // lower so don't worry about this.
20357 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20358 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20359 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20360 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20361 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20362 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20363 // No need to check constraints, nothing other than the equivalent of
20364 // "=r,0" would be valid here.
20365 return IntrinsicLowering::LowerToByteSwap(CI);
20368 // rorw $$8, ${0:w} --> llvm.bswap.i16
20369 if (CI->getType()->isIntegerTy(16) &&
20370 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20371 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20372 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20374 const std::string &ConstraintsStr = IA->getConstraintString();
20375 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20376 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20377 if (clobbersFlagRegisters(AsmPieces))
20378 return IntrinsicLowering::LowerToByteSwap(CI);
20382 if (CI->getType()->isIntegerTy(32) &&
20383 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20384 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20385 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20386 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20388 const std::string &ConstraintsStr = IA->getConstraintString();
20389 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20390 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20391 if (clobbersFlagRegisters(AsmPieces))
20392 return IntrinsicLowering::LowerToByteSwap(CI);
20395 if (CI->getType()->isIntegerTy(64)) {
20396 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20397 if (Constraints.size() >= 2 &&
20398 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20399 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20400 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20401 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20402 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20403 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20404 return IntrinsicLowering::LowerToByteSwap(CI);
20412 /// getConstraintType - Given a constraint letter, return the type of
20413 /// constraint it is for this target.
20414 X86TargetLowering::ConstraintType
20415 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20416 if (Constraint.size() == 1) {
20417 switch (Constraint[0]) {
20428 return C_RegisterClass;
20452 return TargetLowering::getConstraintType(Constraint);
20455 /// Examine constraint type and operand type and determine a weight value.
20456 /// This object must already have been set up with the operand type
20457 /// and the current alternative constraint selected.
20458 TargetLowering::ConstraintWeight
20459 X86TargetLowering::getSingleConstraintMatchWeight(
20460 AsmOperandInfo &info, const char *constraint) const {
20461 ConstraintWeight weight = CW_Invalid;
20462 Value *CallOperandVal = info.CallOperandVal;
20463 // If we don't have a value, we can't do a match,
20464 // but allow it at the lowest weight.
20465 if (!CallOperandVal)
20467 Type *type = CallOperandVal->getType();
20468 // Look at the constraint type.
20469 switch (*constraint) {
20471 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20482 if (CallOperandVal->getType()->isIntegerTy())
20483 weight = CW_SpecificReg;
20488 if (type->isFloatingPointTy())
20489 weight = CW_SpecificReg;
20492 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20493 weight = CW_SpecificReg;
20497 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20498 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20499 weight = CW_Register;
20502 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20503 if (C->getZExtValue() <= 31)
20504 weight = CW_Constant;
20508 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20509 if (C->getZExtValue() <= 63)
20510 weight = CW_Constant;
20514 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20515 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20516 weight = CW_Constant;
20520 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20521 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20522 weight = CW_Constant;
20526 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20527 if (C->getZExtValue() <= 3)
20528 weight = CW_Constant;
20532 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20533 if (C->getZExtValue() <= 0xff)
20534 weight = CW_Constant;
20539 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20540 weight = CW_Constant;
20544 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20545 if ((C->getSExtValue() >= -0x80000000LL) &&
20546 (C->getSExtValue() <= 0x7fffffffLL))
20547 weight = CW_Constant;
20551 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20552 if (C->getZExtValue() <= 0xffffffff)
20553 weight = CW_Constant;
20560 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20561 /// with another that has more specific requirements based on the type of the
20562 /// corresponding operand.
20563 const char *X86TargetLowering::
20564 LowerXConstraint(EVT ConstraintVT) const {
20565 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20566 // 'f' like normal targets.
20567 if (ConstraintVT.isFloatingPoint()) {
20568 if (Subtarget->hasSSE2())
20570 if (Subtarget->hasSSE1())
20574 return TargetLowering::LowerXConstraint(ConstraintVT);
20577 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20578 /// vector. If it is invalid, don't add anything to Ops.
20579 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20580 std::string &Constraint,
20581 std::vector<SDValue>&Ops,
20582 SelectionDAG &DAG) const {
20585 // Only support length 1 constraints for now.
20586 if (Constraint.length() > 1) return;
20588 char ConstraintLetter = Constraint[0];
20589 switch (ConstraintLetter) {
20592 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20593 if (C->getZExtValue() <= 31) {
20594 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20601 if (C->getZExtValue() <= 63) {
20602 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20608 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20609 if (isInt<8>(C->getSExtValue())) {
20610 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20616 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20617 if (C->getZExtValue() <= 255) {
20618 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20624 // 32-bit signed value
20625 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20626 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20627 C->getSExtValue())) {
20628 // Widen to 64 bits here to get it sign extended.
20629 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20632 // FIXME gcc accepts some relocatable values here too, but only in certain
20633 // memory models; it's complicated.
20638 // 32-bit unsigned value
20639 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20640 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20641 C->getZExtValue())) {
20642 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20646 // FIXME gcc accepts some relocatable values here too, but only in certain
20647 // memory models; it's complicated.
20651 // Literal immediates are always ok.
20652 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20653 // Widen to 64 bits here to get it sign extended.
20654 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20658 // In any sort of PIC mode addresses need to be computed at runtime by
20659 // adding in a register or some sort of table lookup. These can't
20660 // be used as immediates.
20661 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20664 // If we are in non-pic codegen mode, we allow the address of a global (with
20665 // an optional displacement) to be used with 'i'.
20666 GlobalAddressSDNode *GA = nullptr;
20667 int64_t Offset = 0;
20669 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20671 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20672 Offset += GA->getOffset();
20674 } else if (Op.getOpcode() == ISD::ADD) {
20675 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20676 Offset += C->getZExtValue();
20677 Op = Op.getOperand(0);
20680 } else if (Op.getOpcode() == ISD::SUB) {
20681 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20682 Offset += -C->getZExtValue();
20683 Op = Op.getOperand(0);
20688 // Otherwise, this isn't something we can handle, reject it.
20692 const GlobalValue *GV = GA->getGlobal();
20693 // If we require an extra load to get this address, as in PIC mode, we
20694 // can't accept it.
20695 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20696 getTargetMachine())))
20699 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20700 GA->getValueType(0), Offset);
20705 if (Result.getNode()) {
20706 Ops.push_back(Result);
20709 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20712 std::pair<unsigned, const TargetRegisterClass*>
20713 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20715 // First, see if this is a constraint that directly corresponds to an LLVM
20717 if (Constraint.size() == 1) {
20718 // GCC Constraint Letters
20719 switch (Constraint[0]) {
20721 // TODO: Slight differences here in allocation order and leaving
20722 // RIP in the class. Do they matter any more here than they do
20723 // in the normal allocation?
20724 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20725 if (Subtarget->is64Bit()) {
20726 if (VT == MVT::i32 || VT == MVT::f32)
20727 return std::make_pair(0U, &X86::GR32RegClass);
20728 if (VT == MVT::i16)
20729 return std::make_pair(0U, &X86::GR16RegClass);
20730 if (VT == MVT::i8 || VT == MVT::i1)
20731 return std::make_pair(0U, &X86::GR8RegClass);
20732 if (VT == MVT::i64 || VT == MVT::f64)
20733 return std::make_pair(0U, &X86::GR64RegClass);
20736 // 32-bit fallthrough
20737 case 'Q': // Q_REGS
20738 if (VT == MVT::i32 || VT == MVT::f32)
20739 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20740 if (VT == MVT::i16)
20741 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20742 if (VT == MVT::i8 || VT == MVT::i1)
20743 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20744 if (VT == MVT::i64)
20745 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20747 case 'r': // GENERAL_REGS
20748 case 'l': // INDEX_REGS
20749 if (VT == MVT::i8 || VT == MVT::i1)
20750 return std::make_pair(0U, &X86::GR8RegClass);
20751 if (VT == MVT::i16)
20752 return std::make_pair(0U, &X86::GR16RegClass);
20753 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20754 return std::make_pair(0U, &X86::GR32RegClass);
20755 return std::make_pair(0U, &X86::GR64RegClass);
20756 case 'R': // LEGACY_REGS
20757 if (VT == MVT::i8 || VT == MVT::i1)
20758 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20759 if (VT == MVT::i16)
20760 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20761 if (VT == MVT::i32 || !Subtarget->is64Bit())
20762 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20763 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20764 case 'f': // FP Stack registers.
20765 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20766 // value to the correct fpstack register class.
20767 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20768 return std::make_pair(0U, &X86::RFP32RegClass);
20769 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20770 return std::make_pair(0U, &X86::RFP64RegClass);
20771 return std::make_pair(0U, &X86::RFP80RegClass);
20772 case 'y': // MMX_REGS if MMX allowed.
20773 if (!Subtarget->hasMMX()) break;
20774 return std::make_pair(0U, &X86::VR64RegClass);
20775 case 'Y': // SSE_REGS if SSE2 allowed
20776 if (!Subtarget->hasSSE2()) break;
20778 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20779 if (!Subtarget->hasSSE1()) break;
20781 switch (VT.SimpleTy) {
20783 // Scalar SSE types.
20786 return std::make_pair(0U, &X86::FR32RegClass);
20789 return std::make_pair(0U, &X86::FR64RegClass);
20797 return std::make_pair(0U, &X86::VR128RegClass);
20805 return std::make_pair(0U, &X86::VR256RegClass);
20810 return std::make_pair(0U, &X86::VR512RegClass);
20816 // Use the default implementation in TargetLowering to convert the register
20817 // constraint into a member of a register class.
20818 std::pair<unsigned, const TargetRegisterClass*> Res;
20819 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20821 // Not found as a standard register?
20823 // Map st(0) -> st(7) -> ST0
20824 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20825 tolower(Constraint[1]) == 's' &&
20826 tolower(Constraint[2]) == 't' &&
20827 Constraint[3] == '(' &&
20828 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20829 Constraint[5] == ')' &&
20830 Constraint[6] == '}') {
20832 Res.first = X86::ST0+Constraint[4]-'0';
20833 Res.second = &X86::RFP80RegClass;
20837 // GCC allows "st(0)" to be called just plain "st".
20838 if (StringRef("{st}").equals_lower(Constraint)) {
20839 Res.first = X86::ST0;
20840 Res.second = &X86::RFP80RegClass;
20845 if (StringRef("{flags}").equals_lower(Constraint)) {
20846 Res.first = X86::EFLAGS;
20847 Res.second = &X86::CCRRegClass;
20851 // 'A' means EAX + EDX.
20852 if (Constraint == "A") {
20853 Res.first = X86::EAX;
20854 Res.second = &X86::GR32_ADRegClass;
20860 // Otherwise, check to see if this is a register class of the wrong value
20861 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20862 // turn into {ax},{dx}.
20863 if (Res.second->hasType(VT))
20864 return Res; // Correct type already, nothing to do.
20866 // All of the single-register GCC register classes map their values onto
20867 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20868 // really want an 8-bit or 32-bit register, map to the appropriate register
20869 // class and return the appropriate register.
20870 if (Res.second == &X86::GR16RegClass) {
20871 if (VT == MVT::i8 || VT == MVT::i1) {
20872 unsigned DestReg = 0;
20873 switch (Res.first) {
20875 case X86::AX: DestReg = X86::AL; break;
20876 case X86::DX: DestReg = X86::DL; break;
20877 case X86::CX: DestReg = X86::CL; break;
20878 case X86::BX: DestReg = X86::BL; break;
20881 Res.first = DestReg;
20882 Res.second = &X86::GR8RegClass;
20884 } else if (VT == MVT::i32 || VT == MVT::f32) {
20885 unsigned DestReg = 0;
20886 switch (Res.first) {
20888 case X86::AX: DestReg = X86::EAX; break;
20889 case X86::DX: DestReg = X86::EDX; break;
20890 case X86::CX: DestReg = X86::ECX; break;
20891 case X86::BX: DestReg = X86::EBX; break;
20892 case X86::SI: DestReg = X86::ESI; break;
20893 case X86::DI: DestReg = X86::EDI; break;
20894 case X86::BP: DestReg = X86::EBP; break;
20895 case X86::SP: DestReg = X86::ESP; break;
20898 Res.first = DestReg;
20899 Res.second = &X86::GR32RegClass;
20901 } else if (VT == MVT::i64 || VT == MVT::f64) {
20902 unsigned DestReg = 0;
20903 switch (Res.first) {
20905 case X86::AX: DestReg = X86::RAX; break;
20906 case X86::DX: DestReg = X86::RDX; break;
20907 case X86::CX: DestReg = X86::RCX; break;
20908 case X86::BX: DestReg = X86::RBX; break;
20909 case X86::SI: DestReg = X86::RSI; break;
20910 case X86::DI: DestReg = X86::RDI; break;
20911 case X86::BP: DestReg = X86::RBP; break;
20912 case X86::SP: DestReg = X86::RSP; break;
20915 Res.first = DestReg;
20916 Res.second = &X86::GR64RegClass;
20919 } else if (Res.second == &X86::FR32RegClass ||
20920 Res.second == &X86::FR64RegClass ||
20921 Res.second == &X86::VR128RegClass ||
20922 Res.second == &X86::VR256RegClass ||
20923 Res.second == &X86::FR32XRegClass ||
20924 Res.second == &X86::FR64XRegClass ||
20925 Res.second == &X86::VR128XRegClass ||
20926 Res.second == &X86::VR256XRegClass ||
20927 Res.second == &X86::VR512RegClass) {
20928 // Handle references to XMM physical registers that got mapped into the
20929 // wrong class. This can happen with constraints like {xmm0} where the
20930 // target independent register mapper will just pick the first match it can
20931 // find, ignoring the required type.
20933 if (VT == MVT::f32 || VT == MVT::i32)
20934 Res.second = &X86::FR32RegClass;
20935 else if (VT == MVT::f64 || VT == MVT::i64)
20936 Res.second = &X86::FR64RegClass;
20937 else if (X86::VR128RegClass.hasType(VT))
20938 Res.second = &X86::VR128RegClass;
20939 else if (X86::VR256RegClass.hasType(VT))
20940 Res.second = &X86::VR256RegClass;
20941 else if (X86::VR512RegClass.hasType(VT))
20942 Res.second = &X86::VR512RegClass;
20948 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20950 // Scaling factors are not free at all.
20951 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20952 // will take 2 allocations in the out of order engine instead of 1
20953 // for plain addressing mode, i.e. inst (reg1).
20955 // vaddps (%rsi,%drx), %ymm0, %ymm1
20956 // Requires two allocations (one for the load, one for the computation)
20958 // vaddps (%rsi), %ymm0, %ymm1
20959 // Requires just 1 allocation, i.e., freeing allocations for other operations
20960 // and having less micro operations to execute.
20962 // For some X86 architectures, this is even worse because for instance for
20963 // stores, the complex addressing mode forces the instruction to use the
20964 // "load" ports instead of the dedicated "store" port.
20965 // E.g., on Haswell:
20966 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
20967 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
20968 if (isLegalAddressingMode(AM, Ty))
20969 // Scale represents reg2 * scale, thus account for 1
20970 // as soon as we use a second register.
20971 return AM.Scale != 0;