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 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86CallingConv.h"
20 #include "X86InstrBuilder.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.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/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/LLVMContext.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/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63 SelectionDAG &DAG, SDLoc dl,
64 unsigned vectorWidth) {
65 assert((vectorWidth == 128 || vectorWidth == 256) &&
66 "Unsupported vector width");
67 EVT VT = Vec.getValueType();
68 EVT ElVT = VT.getVectorElementType();
69 unsigned Factor = VT.getSizeInBits()/vectorWidth;
70 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71 VT.getVectorNumElements()/Factor);
73 // Extract from UNDEF is UNDEF.
74 if (Vec.getOpcode() == ISD::UNDEF)
75 return DAG.getUNDEF(ResultVT);
77 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
78 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80 // This is the index of the first element of the vectorWidth-bit chunk
82 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
85 // If the input is a buildvector just emit a smaller one.
86 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
90 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104 SelectionDAG &DAG, SDLoc dl) {
105 assert((Vec.getValueType().is256BitVector() ||
106 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112 SelectionDAG &DAG, SDLoc dl) {
113 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118 unsigned IdxVal, SelectionDAG &DAG,
119 SDLoc dl, unsigned vectorWidth) {
120 assert((vectorWidth == 128 || vectorWidth == 256) &&
121 "Unsupported vector width");
122 // Inserting UNDEF is Result
123 if (Vec.getOpcode() == ISD::UNDEF)
125 EVT VT = Vec.getValueType();
126 EVT ElVT = VT.getVectorElementType();
127 EVT ResultVT = Result.getValueType();
129 // Insert the relevant vectorWidth bits.
130 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
132 // This is the index of the first element of the vectorWidth-bit chunk
134 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference. Idx is an index in the 128 bits
145 /// we want. It need not be aligned to a 128-bit bounday. That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148 unsigned IdxVal, SelectionDAG &DAG,
150 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155 unsigned IdxVal, SelectionDAG &DAG,
157 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166 unsigned NumElems, SelectionDAG &DAG,
168 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173 unsigned NumElems, SelectionDAG &DAG,
175 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181 bool is64Bit = Subtarget->is64Bit();
183 if (Subtarget->isTargetMacho()) {
185 return new X86_64MachoTargetObjectFile();
186 return new TargetLoweringObjectFileMachO();
189 if (Subtarget->isTargetLinux())
190 return new X86LinuxTargetObjectFile();
191 if (Subtarget->isTargetELF())
192 return new TargetLoweringObjectFileELF();
193 if (Subtarget->isTargetCOFF())
194 return new TargetLoweringObjectFileCOFF();
195 llvm_unreachable("unknown subtarget type");
198 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
199 : TargetLowering(TM, createTLOF(TM)) {
200 Subtarget = &TM.getSubtarget<X86Subtarget>();
201 X86ScalarSSEf64 = Subtarget->hasSSE2();
202 X86ScalarSSEf32 = Subtarget->hasSSE1();
203 TD = getDataLayout();
205 resetOperationActions();
208 void X86TargetLowering::resetOperationActions() {
209 const TargetMachine &TM = getTargetMachine();
210 static bool FirstTimeThrough = true;
212 // If none of the target options have changed, then we don't need to reset the
213 // operation actions.
214 if (!FirstTimeThrough && TO == TM.Options) return;
216 if (!FirstTimeThrough) {
217 // Reinitialize the actions.
219 FirstTimeThrough = false;
224 // Set up the TargetLowering object.
225 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227 // X86 is weird, it always uses i8 for shift amounts and setcc results.
228 setBooleanContents(ZeroOrOneBooleanContent);
229 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
230 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232 // For 64-bit since we have so many registers use the ILP scheduler, for
233 // 32-bit code use the register pressure specific scheduling.
234 // For Atom, always use ILP scheduling.
235 if (Subtarget->isAtom())
236 setSchedulingPreference(Sched::ILP);
237 else if (Subtarget->is64Bit())
238 setSchedulingPreference(Sched::ILP);
240 setSchedulingPreference(Sched::RegPressure);
241 const X86RegisterInfo *RegInfo =
242 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
243 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245 // Bypass expensive divides on Atom when compiling with O2
246 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
247 addBypassSlowDiv(32, 8);
248 if (Subtarget->is64Bit())
249 addBypassSlowDiv(64, 16);
252 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
253 // Setup Windows compiler runtime calls.
254 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
255 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
256 setLibcallName(RTLIB::SREM_I64, "_allrem");
257 setLibcallName(RTLIB::UREM_I64, "_aullrem");
258 setLibcallName(RTLIB::MUL_I64, "_allmul");
259 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
260 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
265 // The _ftol2 runtime function has an unusual calling conv, which
266 // is modeled by a special pseudo-instruction.
267 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
268 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
269 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
270 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
273 if (Subtarget->isTargetDarwin()) {
274 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
275 setUseUnderscoreSetJmp(false);
276 setUseUnderscoreLongJmp(false);
277 } else if (Subtarget->isTargetMingw()) {
278 // MS runtime is weird: it exports _setjmp, but longjmp!
279 setUseUnderscoreSetJmp(true);
280 setUseUnderscoreLongJmp(false);
282 setUseUnderscoreSetJmp(true);
283 setUseUnderscoreLongJmp(true);
286 // Set up the register classes.
287 addRegisterClass(MVT::i8, &X86::GR8RegClass);
288 addRegisterClass(MVT::i16, &X86::GR16RegClass);
289 addRegisterClass(MVT::i32, &X86::GR32RegClass);
290 if (Subtarget->is64Bit())
291 addRegisterClass(MVT::i64, &X86::GR64RegClass);
293 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
295 // We don't accept any truncstore of integer registers.
296 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
297 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
298 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
299 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
300 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
301 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
303 // SETOEQ and SETUNE require checking two conditions.
304 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
305 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
306 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
307 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
311 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
313 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
314 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
315 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
317 if (Subtarget->is64Bit()) {
318 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
319 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
320 } else if (!TM.Options.UseSoftFloat) {
321 // We have an algorithm for SSE2->double, and we turn this into a
322 // 64-bit FILD followed by conditional FADD for other targets.
323 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
324 // We have an algorithm for SSE2, and we turn this into a 64-bit
325 // FILD for other targets.
326 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
329 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
331 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
332 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
334 if (!TM.Options.UseSoftFloat) {
335 // SSE has no i16 to fp conversion, only i32
336 if (X86ScalarSSEf32) {
337 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
338 // f32 and f64 cases are Legal, f80 case is not
339 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
341 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
349 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
350 // are Legal, f80 is custom lowered.
351 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
352 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
354 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
356 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
357 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
359 if (X86ScalarSSEf32) {
360 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
361 // f32 and f64 cases are Legal, f80 case is not
362 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
364 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
365 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
368 // Handle FP_TO_UINT by promoting the destination to a larger signed
370 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
371 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
372 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
374 if (Subtarget->is64Bit()) {
375 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
376 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
377 } else if (!TM.Options.UseSoftFloat) {
378 // Since AVX is a superset of SSE3, only check for SSE here.
379 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
380 // Expand FP_TO_UINT into a select.
381 // FIXME: We would like to use a Custom expander here eventually to do
382 // the optimal thing for SSE vs. the default expansion in the legalizer.
383 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
385 // With SSE3 we can use fisttpll to convert to a signed i64; without
386 // SSE, we're stuck with a fistpll.
387 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
390 if (isTargetFTOL()) {
391 // Use the _ftol2 runtime function, which has a pseudo-instruction
392 // to handle its weird calling convention.
393 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
396 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
397 if (!X86ScalarSSEf64) {
398 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
399 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
400 if (Subtarget->is64Bit()) {
401 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
402 // Without SSE, i64->f64 goes through memory.
403 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
407 // Scalar integer divide and remainder are lowered to use operations that
408 // produce two results, to match the available instructions. This exposes
409 // the two-result form to trivial CSE, which is able to combine x/y and x%y
410 // into a single instruction.
412 // Scalar integer multiply-high is also lowered to use two-result
413 // operations, to match the available instructions. However, plain multiply
414 // (low) operations are left as Legal, as there are single-result
415 // instructions for this in x86. Using the two-result multiply instructions
416 // when both high and low results are needed must be arranged by dagcombine.
417 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
419 setOperationAction(ISD::MULHS, VT, Expand);
420 setOperationAction(ISD::MULHU, VT, Expand);
421 setOperationAction(ISD::SDIV, VT, Expand);
422 setOperationAction(ISD::UDIV, VT, Expand);
423 setOperationAction(ISD::SREM, VT, Expand);
424 setOperationAction(ISD::UREM, VT, Expand);
426 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
427 setOperationAction(ISD::ADDC, VT, Custom);
428 setOperationAction(ISD::ADDE, VT, Custom);
429 setOperationAction(ISD::SUBC, VT, Custom);
430 setOperationAction(ISD::SUBE, VT, Custom);
433 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
434 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
435 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
436 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
437 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
438 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
442 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
443 if (Subtarget->is64Bit())
444 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
448 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
449 setOperationAction(ISD::FREM , MVT::f32 , Expand);
450 setOperationAction(ISD::FREM , MVT::f64 , Expand);
451 setOperationAction(ISD::FREM , MVT::f80 , Expand);
452 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
454 // Promote the i8 variants and force them on up to i32 which has a shorter
456 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
457 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
458 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
459 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
460 if (Subtarget->hasBMI()) {
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
463 if (Subtarget->is64Bit())
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
466 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
467 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
468 if (Subtarget->is64Bit())
469 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
472 if (Subtarget->hasLZCNT()) {
473 // When promoting the i8 variants, force them to i32 for a shorter
475 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
476 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
477 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
478 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
481 if (Subtarget->is64Bit())
482 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
484 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
485 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
486 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
487 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
490 if (Subtarget->is64Bit()) {
491 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
492 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
496 if (Subtarget->hasPOPCNT()) {
497 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
499 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
500 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
501 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
502 if (Subtarget->is64Bit())
503 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
506 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
507 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
509 // These should be promoted to a larger select which is supported.
510 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
511 // X86 wants to expand cmov itself.
512 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
513 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
514 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
515 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
516 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
517 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
518 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
519 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
520 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
521 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
522 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
523 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
524 if (Subtarget->is64Bit()) {
525 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
528 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
529 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
530 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
531 // support continuation, user-level threading, and etc.. As a result, no
532 // other SjLj exception interfaces are implemented and please don't build
533 // your own exception handling based on them.
534 // LLVM/Clang supports zero-cost DWARF exception handling.
535 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
536 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
539 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
540 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
541 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
542 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
543 if (Subtarget->is64Bit())
544 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
545 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
546 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
547 if (Subtarget->is64Bit()) {
548 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
549 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
550 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
551 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
552 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
554 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
555 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
556 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
557 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
558 if (Subtarget->is64Bit()) {
559 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
560 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
561 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
564 if (Subtarget->hasSSE1())
565 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
567 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
569 // Expand certain atomics
570 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
572 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
573 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
574 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
577 if (!Subtarget->is64Bit()) {
578 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
579 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
580 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
581 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
592 if (Subtarget->hasCmpxchg16b()) {
593 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
596 // FIXME - use subtarget debug flags
597 if (!Subtarget->isTargetDarwin() &&
598 !Subtarget->isTargetELF() &&
599 !Subtarget->isTargetCygMing()) {
600 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
603 if (Subtarget->is64Bit()) {
604 setExceptionPointerRegister(X86::RAX);
605 setExceptionSelectorRegister(X86::RDX);
607 setExceptionPointerRegister(X86::EAX);
608 setExceptionSelectorRegister(X86::EDX);
610 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
611 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
613 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
614 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
616 setOperationAction(ISD::TRAP, MVT::Other, Legal);
617 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
619 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
620 setOperationAction(ISD::VASTART , MVT::Other, Custom);
621 setOperationAction(ISD::VAEND , MVT::Other, Expand);
622 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
623 // TargetInfo::X86_64ABIBuiltinVaList
624 setOperationAction(ISD::VAARG , MVT::Other, Custom);
625 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
627 // TargetInfo::CharPtrBuiltinVaList
628 setOperationAction(ISD::VAARG , MVT::Other, Expand);
629 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
632 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
633 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
635 if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
636 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
637 MVT::i64 : MVT::i32, Custom);
638 else if (TM.Options.EnableSegmentedStacks)
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
642 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643 MVT::i64 : MVT::i32, Expand);
645 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
646 // f32 and f64 use SSE.
647 // Set up the FP register classes.
648 addRegisterClass(MVT::f32, &X86::FR32RegClass);
649 addRegisterClass(MVT::f64, &X86::FR64RegClass);
651 // Use ANDPD to simulate FABS.
652 setOperationAction(ISD::FABS , MVT::f64, Custom);
653 setOperationAction(ISD::FABS , MVT::f32, Custom);
655 // Use XORP to simulate FNEG.
656 setOperationAction(ISD::FNEG , MVT::f64, Custom);
657 setOperationAction(ISD::FNEG , MVT::f32, Custom);
659 // Use ANDPD and ORPD to simulate FCOPYSIGN.
660 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
661 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
663 // Lower this to FGETSIGNx86 plus an AND.
664 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
665 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
667 // We don't support sin/cos/fmod
668 setOperationAction(ISD::FSIN , MVT::f64, Expand);
669 setOperationAction(ISD::FCOS , MVT::f64, Expand);
670 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
671 setOperationAction(ISD::FSIN , MVT::f32, Expand);
672 setOperationAction(ISD::FCOS , MVT::f32, Expand);
673 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
675 // Expand FP immediates into loads from the stack, except for the special
677 addLegalFPImmediate(APFloat(+0.0)); // xorpd
678 addLegalFPImmediate(APFloat(+0.0f)); // xorps
679 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
680 // Use SSE for f32, x87 for f64.
681 // Set up the FP register classes.
682 addRegisterClass(MVT::f32, &X86::FR32RegClass);
683 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
685 // Use ANDPS to simulate FABS.
686 setOperationAction(ISD::FABS , MVT::f32, Custom);
688 // Use XORP to simulate FNEG.
689 setOperationAction(ISD::FNEG , MVT::f32, Custom);
691 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
693 // Use ANDPS and ORPS to simulate FCOPYSIGN.
694 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
695 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
697 // We don't support sin/cos/fmod
698 setOperationAction(ISD::FSIN , MVT::f32, Expand);
699 setOperationAction(ISD::FCOS , MVT::f32, Expand);
700 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
702 // Special cases we handle for FP constants.
703 addLegalFPImmediate(APFloat(+0.0f)); // xorps
704 addLegalFPImmediate(APFloat(+0.0)); // FLD0
705 addLegalFPImmediate(APFloat(+1.0)); // FLD1
706 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
707 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
709 if (!TM.Options.UnsafeFPMath) {
710 setOperationAction(ISD::FSIN , MVT::f64, Expand);
711 setOperationAction(ISD::FCOS , MVT::f64, Expand);
712 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
714 } else if (!TM.Options.UseSoftFloat) {
715 // f32 and f64 in x87.
716 // Set up the FP register classes.
717 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
718 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
720 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
721 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
722 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
723 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
725 if (!TM.Options.UnsafeFPMath) {
726 setOperationAction(ISD::FSIN , MVT::f64, Expand);
727 setOperationAction(ISD::FSIN , MVT::f32, Expand);
728 setOperationAction(ISD::FCOS , MVT::f64, Expand);
729 setOperationAction(ISD::FCOS , MVT::f32, Expand);
730 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
731 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
733 addLegalFPImmediate(APFloat(+0.0)); // FLD0
734 addLegalFPImmediate(APFloat(+1.0)); // FLD1
735 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
736 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
737 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
738 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
739 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
740 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
743 // We don't support FMA.
744 setOperationAction(ISD::FMA, MVT::f64, Expand);
745 setOperationAction(ISD::FMA, MVT::f32, Expand);
747 // Long double always uses X87.
748 if (!TM.Options.UseSoftFloat) {
749 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
750 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
751 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
753 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
754 addLegalFPImmediate(TmpFlt); // FLD0
756 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
759 APFloat TmpFlt2(+1.0);
760 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
762 addLegalFPImmediate(TmpFlt2); // FLD1
763 TmpFlt2.changeSign();
764 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
767 if (!TM.Options.UnsafeFPMath) {
768 setOperationAction(ISD::FSIN , MVT::f80, Expand);
769 setOperationAction(ISD::FCOS , MVT::f80, Expand);
770 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
773 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
774 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
775 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
776 setOperationAction(ISD::FRINT, MVT::f80, Expand);
777 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
778 setOperationAction(ISD::FMA, MVT::f80, Expand);
781 // Always use a library call for pow.
782 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
783 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
784 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
786 setOperationAction(ISD::FLOG, MVT::f80, Expand);
787 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
788 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
789 setOperationAction(ISD::FEXP, MVT::f80, Expand);
790 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
792 // First set operation action for all vector types to either promote
793 // (for widening) or expand (for scalarization). Then we will selectively
794 // turn on ones that can be effectively codegen'd.
795 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
796 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
797 MVT VT = (MVT::SimpleValueType)i;
798 setOperationAction(ISD::ADD , VT, Expand);
799 setOperationAction(ISD::SUB , VT, Expand);
800 setOperationAction(ISD::FADD, VT, Expand);
801 setOperationAction(ISD::FNEG, VT, Expand);
802 setOperationAction(ISD::FSUB, VT, Expand);
803 setOperationAction(ISD::MUL , VT, Expand);
804 setOperationAction(ISD::FMUL, VT, Expand);
805 setOperationAction(ISD::SDIV, VT, Expand);
806 setOperationAction(ISD::UDIV, VT, Expand);
807 setOperationAction(ISD::FDIV, VT, Expand);
808 setOperationAction(ISD::SREM, VT, Expand);
809 setOperationAction(ISD::UREM, VT, Expand);
810 setOperationAction(ISD::LOAD, VT, Expand);
811 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
812 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
813 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
814 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
815 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
816 setOperationAction(ISD::FABS, VT, Expand);
817 setOperationAction(ISD::FSIN, VT, Expand);
818 setOperationAction(ISD::FSINCOS, VT, Expand);
819 setOperationAction(ISD::FCOS, VT, Expand);
820 setOperationAction(ISD::FSINCOS, VT, Expand);
821 setOperationAction(ISD::FREM, VT, Expand);
822 setOperationAction(ISD::FMA, VT, Expand);
823 setOperationAction(ISD::FPOWI, VT, Expand);
824 setOperationAction(ISD::FSQRT, VT, Expand);
825 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
826 setOperationAction(ISD::FFLOOR, VT, Expand);
827 setOperationAction(ISD::FCEIL, VT, Expand);
828 setOperationAction(ISD::FTRUNC, VT, Expand);
829 setOperationAction(ISD::FRINT, VT, Expand);
830 setOperationAction(ISD::FNEARBYINT, VT, Expand);
831 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
832 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833 setOperationAction(ISD::SDIVREM, VT, Expand);
834 setOperationAction(ISD::UDIVREM, VT, Expand);
835 setOperationAction(ISD::FPOW, VT, Expand);
836 setOperationAction(ISD::CTPOP, VT, Expand);
837 setOperationAction(ISD::CTTZ, VT, Expand);
838 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
839 setOperationAction(ISD::CTLZ, VT, Expand);
840 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
841 setOperationAction(ISD::SHL, VT, Expand);
842 setOperationAction(ISD::SRA, VT, Expand);
843 setOperationAction(ISD::SRL, VT, Expand);
844 setOperationAction(ISD::ROTL, VT, Expand);
845 setOperationAction(ISD::ROTR, VT, Expand);
846 setOperationAction(ISD::BSWAP, VT, Expand);
847 setOperationAction(ISD::SETCC, VT, Expand);
848 setOperationAction(ISD::FLOG, VT, Expand);
849 setOperationAction(ISD::FLOG2, VT, Expand);
850 setOperationAction(ISD::FLOG10, VT, Expand);
851 setOperationAction(ISD::FEXP, VT, Expand);
852 setOperationAction(ISD::FEXP2, VT, Expand);
853 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
854 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
855 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
857 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
858 setOperationAction(ISD::TRUNCATE, VT, Expand);
859 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
860 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
861 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
862 setOperationAction(ISD::VSELECT, VT, Expand);
863 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
864 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
865 setTruncStoreAction(VT,
866 (MVT::SimpleValueType)InnerVT, Expand);
867 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
869 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
872 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
873 // with -msoft-float, disable use of MMX as well.
874 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
875 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
876 // No operations on x86mmx supported, everything uses intrinsics.
879 // MMX-sized vectors (other than x86mmx) are expected to be expanded
880 // into smaller operations.
881 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
882 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
883 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
884 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
885 setOperationAction(ISD::AND, MVT::v8i8, Expand);
886 setOperationAction(ISD::AND, MVT::v4i16, Expand);
887 setOperationAction(ISD::AND, MVT::v2i32, Expand);
888 setOperationAction(ISD::AND, MVT::v1i64, Expand);
889 setOperationAction(ISD::OR, MVT::v8i8, Expand);
890 setOperationAction(ISD::OR, MVT::v4i16, Expand);
891 setOperationAction(ISD::OR, MVT::v2i32, Expand);
892 setOperationAction(ISD::OR, MVT::v1i64, Expand);
893 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
894 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
895 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
896 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
901 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
902 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
903 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
904 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
905 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
911 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
912 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
915 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
916 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
917 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
918 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
919 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
920 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
921 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
922 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
923 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
924 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
925 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
928 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
929 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
932 // registers cannot be used even for integer operations.
933 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
934 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
935 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
936 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
939 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
940 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
941 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
942 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
943 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
944 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
945 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
946 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
947 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
948 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
949 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
950 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
951 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
952 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
953 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
954 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
955 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
957 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
958 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
959 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
960 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
963 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
968 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
969 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
970 MVT VT = (MVT::SimpleValueType)i;
971 // Do not attempt to custom lower non-power-of-2 vectors
972 if (!isPowerOf2_32(VT.getVectorNumElements()))
974 // Do not attempt to custom lower non-128-bit vectors
975 if (!VT.is128BitVector())
977 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
978 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
979 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
982 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
983 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
984 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
985 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
987 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
989 if (Subtarget->is64Bit()) {
990 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
995 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996 MVT VT = (MVT::SimpleValueType)i;
998 // Do not attempt to promote non-128-bit vectors
999 if (!VT.is128BitVector())
1002 setOperationAction(ISD::AND, VT, Promote);
1003 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1004 setOperationAction(ISD::OR, VT, Promote);
1005 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1006 setOperationAction(ISD::XOR, VT, Promote);
1007 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1008 setOperationAction(ISD::LOAD, VT, Promote);
1009 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1010 setOperationAction(ISD::SELECT, VT, Promote);
1011 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1014 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1016 // Custom lower v2i64 and v2f64 selects.
1017 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1018 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1019 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1020 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1022 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1023 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1025 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1026 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1027 // As there is no 64-bit GPR available, we need build a special custom
1028 // sequence to convert from v2i32 to v2f32.
1029 if (!Subtarget->is64Bit())
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1032 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1033 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1035 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1038 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1039 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1040 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1041 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1042 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1043 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1044 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1045 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1046 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1047 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1048 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1050 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1053 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1057 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1061 // FIXME: Do we need to handle scalar-to-vector here?
1062 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1070 // i8 and i16 vectors are custom , because the source register and source
1071 // source memory operand types are not the same width. f32 vectors are
1072 // custom since the immediate controlling the insert encodes additional
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1075 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1076 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1077 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1080 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1081 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1082 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1084 // FIXME: these should be Legal but thats only for the case where
1085 // the index is constant. For now custom expand to deal with that.
1086 if (Subtarget->is64Bit()) {
1087 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1088 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1092 if (Subtarget->hasSSE2()) {
1093 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1094 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1096 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1099 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1100 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1102 // In the customized shift lowering, the legal cases in AVX2 will be
1104 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1105 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1107 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1108 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1110 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1112 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1113 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1116 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1117 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1124 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1125 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1126 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1128 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1139 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1141 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1152 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1154 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1156 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1157 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1158 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1159 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1161 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1162 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1164 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1166 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1167 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1169 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1182 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1183 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1186 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1187 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1188 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1194 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1201 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1204 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1206 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1208 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1209 setOperationAction(ISD::FMA, MVT::f32, Legal);
1210 setOperationAction(ISD::FMA, MVT::f64, Legal);
1213 if (Subtarget->hasInt256()) {
1214 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1215 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1216 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1217 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1219 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1220 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1221 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1222 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1224 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1226 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1227 // Don't lower v32i8 because there is no 128-bit byte mul
1229 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1231 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1233 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1234 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1235 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1236 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1238 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1239 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1240 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1241 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1243 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1244 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1245 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1246 // Don't lower v32i8 because there is no 128-bit byte mul
1249 // In the customized shift lowering, the legal cases in AVX2 will be
1251 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1257 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1259 // Custom lower several nodes for 256-bit types.
1260 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262 MVT VT = (MVT::SimpleValueType)i;
1264 // Extract subvector is special because the value type
1265 // (result) is 128-bit but the source is 256-bit wide.
1266 if (VT.is128BitVector())
1267 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1269 // Do not attempt to custom lower other non-256-bit vectors
1270 if (!VT.is256BitVector())
1273 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1274 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1275 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1276 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1278 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1279 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1282 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284 MVT VT = (MVT::SimpleValueType)i;
1286 // Do not attempt to promote non-256-bit vectors
1287 if (!VT.is256BitVector())
1290 setOperationAction(ISD::AND, VT, Promote);
1291 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1292 setOperationAction(ISD::OR, VT, Promote);
1293 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1294 setOperationAction(ISD::XOR, VT, Promote);
1295 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1296 setOperationAction(ISD::LOAD, VT, Promote);
1297 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1298 setOperationAction(ISD::SELECT, VT, Promote);
1299 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1303 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1309 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1310 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1311 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1313 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1314 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1315 setOperationAction(ISD::XOR, MVT::i1, Legal);
1316 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1317 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1318 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1319 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1320 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1321 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1323 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1324 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1325 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1326 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1327 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1328 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1330 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1331 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1332 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1333 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1335 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1336 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1338 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1340 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1341 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1342 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1343 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1344 if (Subtarget->is64Bit()) {
1345 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1346 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1347 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1348 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1350 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1351 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1352 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1353 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1354 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1355 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1356 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1357 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1359 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1360 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1361 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1362 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1363 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1364 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1365 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1366 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1367 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1368 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1369 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1370 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1372 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1373 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1374 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1375 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1376 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1377 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1379 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1380 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1382 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1384 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1385 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1386 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1387 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1388 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1389 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1390 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1392 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1393 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1395 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1396 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1398 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1400 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1401 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1403 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1404 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1406 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1407 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1409 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1410 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1411 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1412 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1413 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1414 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1416 // Custom lower several nodes.
1417 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1418 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1419 MVT VT = (MVT::SimpleValueType)i;
1421 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1422 // Extract subvector is special because the value type
1423 // (result) is 256/128-bit but the source is 512-bit wide.
1424 if (VT.is128BitVector() || VT.is256BitVector())
1425 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1427 if (VT.getVectorElementType() == MVT::i1)
1428 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1430 // Do not attempt to custom lower other non-512-bit vectors
1431 if (!VT.is512BitVector())
1434 if ( EltSize >= 32) {
1435 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1436 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1437 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1438 setOperationAction(ISD::VSELECT, VT, Legal);
1439 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1440 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1441 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1444 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1445 MVT VT = (MVT::SimpleValueType)i;
1447 // Do not attempt to promote non-256-bit vectors
1448 if (!VT.is512BitVector())
1451 setOperationAction(ISD::SELECT, VT, Promote);
1452 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1456 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1457 // of this type with custom code.
1458 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1459 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1460 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1464 // We want to custom lower some of our intrinsics.
1465 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1466 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1467 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1469 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1470 // handle type legalization for these operations here.
1472 // FIXME: We really should do custom legalization for addition and
1473 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1474 // than generic legalization for 64-bit multiplication-with-overflow, though.
1475 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1476 // Add/Sub/Mul with overflow operations are custom lowered.
1478 setOperationAction(ISD::SADDO, VT, Custom);
1479 setOperationAction(ISD::UADDO, VT, Custom);
1480 setOperationAction(ISD::SSUBO, VT, Custom);
1481 setOperationAction(ISD::USUBO, VT, Custom);
1482 setOperationAction(ISD::SMULO, VT, Custom);
1483 setOperationAction(ISD::UMULO, VT, Custom);
1486 // There are no 8-bit 3-address imul/mul instructions
1487 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1488 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1490 if (!Subtarget->is64Bit()) {
1491 // These libcalls are not available in 32-bit.
1492 setLibcallName(RTLIB::SHL_I128, 0);
1493 setLibcallName(RTLIB::SRL_I128, 0);
1494 setLibcallName(RTLIB::SRA_I128, 0);
1497 // Combine sin / cos into one node or libcall if possible.
1498 if (Subtarget->hasSinCos()) {
1499 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1500 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1501 if (Subtarget->isTargetDarwin()) {
1502 // For MacOSX, we don't want to the normal expansion of a libcall to
1503 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1505 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1506 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1510 // We have target-specific dag combine patterns for the following nodes:
1511 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1512 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1513 setTargetDAGCombine(ISD::VSELECT);
1514 setTargetDAGCombine(ISD::SELECT);
1515 setTargetDAGCombine(ISD::SHL);
1516 setTargetDAGCombine(ISD::SRA);
1517 setTargetDAGCombine(ISD::SRL);
1518 setTargetDAGCombine(ISD::OR);
1519 setTargetDAGCombine(ISD::AND);
1520 setTargetDAGCombine(ISD::ADD);
1521 setTargetDAGCombine(ISD::FADD);
1522 setTargetDAGCombine(ISD::FSUB);
1523 setTargetDAGCombine(ISD::FMA);
1524 setTargetDAGCombine(ISD::SUB);
1525 setTargetDAGCombine(ISD::LOAD);
1526 setTargetDAGCombine(ISD::STORE);
1527 setTargetDAGCombine(ISD::ZERO_EXTEND);
1528 setTargetDAGCombine(ISD::ANY_EXTEND);
1529 setTargetDAGCombine(ISD::SIGN_EXTEND);
1530 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1531 setTargetDAGCombine(ISD::TRUNCATE);
1532 setTargetDAGCombine(ISD::SINT_TO_FP);
1533 setTargetDAGCombine(ISD::SETCC);
1534 if (Subtarget->is64Bit())
1535 setTargetDAGCombine(ISD::MUL);
1536 setTargetDAGCombine(ISD::XOR);
1538 computeRegisterProperties();
1540 // On Darwin, -Os means optimize for size without hurting performance,
1541 // do not reduce the limit.
1542 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1543 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1544 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1545 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1546 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1547 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1548 setPrefLoopAlignment(4); // 2^4 bytes.
1550 // Predictable cmov don't hurt on atom because it's in-order.
1551 PredictableSelectIsExpensive = !Subtarget->isAtom();
1553 setPrefFunctionAlignment(4); // 2^4 bytes.
1556 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1560 const TargetMachine &TM = getTargetMachine();
1561 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512())
1562 switch(VT.getVectorNumElements()) {
1563 case 8: return MVT::v8i1;
1564 case 16: return MVT::v16i1;
1567 return VT.changeVectorElementTypeToInteger();
1570 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1571 /// the desired ByVal argument alignment.
1572 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1575 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1576 if (VTy->getBitWidth() == 128)
1578 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1579 unsigned EltAlign = 0;
1580 getMaxByValAlign(ATy->getElementType(), EltAlign);
1581 if (EltAlign > MaxAlign)
1582 MaxAlign = EltAlign;
1583 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1584 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1585 unsigned EltAlign = 0;
1586 getMaxByValAlign(STy->getElementType(i), EltAlign);
1587 if (EltAlign > MaxAlign)
1588 MaxAlign = EltAlign;
1595 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1596 /// function arguments in the caller parameter area. For X86, aggregates
1597 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1598 /// are at 4-byte boundaries.
1599 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1600 if (Subtarget->is64Bit()) {
1601 // Max of 8 and alignment of type.
1602 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1609 if (Subtarget->hasSSE1())
1610 getMaxByValAlign(Ty, Align);
1614 /// getOptimalMemOpType - Returns the target specific optimal type for load
1615 /// and store operations as a result of memset, memcpy, and memmove
1616 /// lowering. If DstAlign is zero that means it's safe to destination
1617 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1618 /// means there isn't a need to check it against alignment requirement,
1619 /// probably because the source does not need to be loaded. If 'IsMemset' is
1620 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1621 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1622 /// source is constant so it does not need to be loaded.
1623 /// It returns EVT::Other if the type should be determined using generic
1624 /// target-independent logic.
1626 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1627 unsigned DstAlign, unsigned SrcAlign,
1628 bool IsMemset, bool ZeroMemset,
1630 MachineFunction &MF) const {
1631 const Function *F = MF.getFunction();
1632 if ((!IsMemset || ZeroMemset) &&
1633 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1634 Attribute::NoImplicitFloat)) {
1636 (Subtarget->isUnalignedMemAccessFast() ||
1637 ((DstAlign == 0 || DstAlign >= 16) &&
1638 (SrcAlign == 0 || SrcAlign >= 16)))) {
1640 if (Subtarget->hasInt256())
1642 if (Subtarget->hasFp256())
1645 if (Subtarget->hasSSE2())
1647 if (Subtarget->hasSSE1())
1649 } else if (!MemcpyStrSrc && Size >= 8 &&
1650 !Subtarget->is64Bit() &&
1651 Subtarget->hasSSE2()) {
1652 // Do not use f64 to lower memcpy if source is string constant. It's
1653 // better to use i32 to avoid the loads.
1657 if (Subtarget->is64Bit() && Size >= 8)
1662 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1664 return X86ScalarSSEf32;
1665 else if (VT == MVT::f64)
1666 return X86ScalarSSEf64;
1671 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1673 *Fast = Subtarget->isUnalignedMemAccessFast();
1677 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1678 /// current function. The returned value is a member of the
1679 /// MachineJumpTableInfo::JTEntryKind enum.
1680 unsigned X86TargetLowering::getJumpTableEncoding() const {
1681 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1683 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1684 Subtarget->isPICStyleGOT())
1685 return MachineJumpTableInfo::EK_Custom32;
1687 // Otherwise, use the normal jump table encoding heuristics.
1688 return TargetLowering::getJumpTableEncoding();
1692 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1693 const MachineBasicBlock *MBB,
1694 unsigned uid,MCContext &Ctx) const{
1695 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1696 Subtarget->isPICStyleGOT());
1697 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1699 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1700 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1703 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1705 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1706 SelectionDAG &DAG) const {
1707 if (!Subtarget->is64Bit())
1708 // This doesn't have SDLoc associated with it, but is not really the
1709 // same as a Register.
1710 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1714 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1715 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1717 const MCExpr *X86TargetLowering::
1718 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1719 MCContext &Ctx) const {
1720 // X86-64 uses RIP relative addressing based on the jump table label.
1721 if (Subtarget->isPICStyleRIPRel())
1722 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1724 // Otherwise, the reference is relative to the PIC base.
1725 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1728 // FIXME: Why this routine is here? Move to RegInfo!
1729 std::pair<const TargetRegisterClass*, uint8_t>
1730 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1731 const TargetRegisterClass *RRC = 0;
1733 switch (VT.SimpleTy) {
1735 return TargetLowering::findRepresentativeClass(VT);
1736 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1737 RRC = Subtarget->is64Bit() ?
1738 (const TargetRegisterClass*)&X86::GR64RegClass :
1739 (const TargetRegisterClass*)&X86::GR32RegClass;
1742 RRC = &X86::VR64RegClass;
1744 case MVT::f32: case MVT::f64:
1745 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1746 case MVT::v4f32: case MVT::v2f64:
1747 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1749 RRC = &X86::VR128RegClass;
1752 return std::make_pair(RRC, Cost);
1755 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1756 unsigned &Offset) const {
1757 if (!Subtarget->isTargetLinux())
1760 if (Subtarget->is64Bit()) {
1761 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1763 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1775 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1776 unsigned DestAS) const {
1777 assert(SrcAS != DestAS && "Expected different address spaces!");
1779 return SrcAS < 256 && DestAS < 256;
1782 //===----------------------------------------------------------------------===//
1783 // Return Value Calling Convention Implementation
1784 //===----------------------------------------------------------------------===//
1786 #include "X86GenCallingConv.inc"
1789 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1790 MachineFunction &MF, bool isVarArg,
1791 const SmallVectorImpl<ISD::OutputArg> &Outs,
1792 LLVMContext &Context) const {
1793 SmallVector<CCValAssign, 16> RVLocs;
1794 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1796 return CCInfo.CheckReturn(Outs, RetCC_X86);
1799 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1800 static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1805 X86TargetLowering::LowerReturn(SDValue Chain,
1806 CallingConv::ID CallConv, bool isVarArg,
1807 const SmallVectorImpl<ISD::OutputArg> &Outs,
1808 const SmallVectorImpl<SDValue> &OutVals,
1809 SDLoc dl, SelectionDAG &DAG) const {
1810 MachineFunction &MF = DAG.getMachineFunction();
1811 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1813 SmallVector<CCValAssign, 16> RVLocs;
1814 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1815 RVLocs, *DAG.getContext());
1816 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1819 SmallVector<SDValue, 6> RetOps;
1820 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1821 // Operand #1 = Bytes To Pop
1822 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1825 // Copy the result values into the output registers.
1826 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1827 CCValAssign &VA = RVLocs[i];
1828 assert(VA.isRegLoc() && "Can only return in registers!");
1829 SDValue ValToCopy = OutVals[i];
1830 EVT ValVT = ValToCopy.getValueType();
1832 // Promote values to the appropriate types
1833 if (VA.getLocInfo() == CCValAssign::SExt)
1834 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1835 else if (VA.getLocInfo() == CCValAssign::ZExt)
1836 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1837 else if (VA.getLocInfo() == CCValAssign::AExt)
1838 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1839 else if (VA.getLocInfo() == CCValAssign::BCvt)
1840 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1842 // If this is x86-64, and we disabled SSE, we can't return FP values,
1843 // or SSE or MMX vectors.
1844 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1845 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1846 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1847 report_fatal_error("SSE register return with SSE disabled");
1849 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1850 // llvm-gcc has never done it right and no one has noticed, so this
1851 // should be OK for now.
1852 if (ValVT == MVT::f64 &&
1853 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1854 report_fatal_error("SSE2 register return with SSE2 disabled");
1856 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1857 // the RET instruction and handled by the FP Stackifier.
1858 if (VA.getLocReg() == X86::ST0 ||
1859 VA.getLocReg() == X86::ST1) {
1860 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1861 // change the value to the FP stack register class.
1862 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1863 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1864 RetOps.push_back(ValToCopy);
1865 // Don't emit a copytoreg.
1869 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1870 // which is returned in RAX / RDX.
1871 if (Subtarget->is64Bit()) {
1872 if (ValVT == MVT::x86mmx) {
1873 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1874 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1875 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1877 // If we don't have SSE2 available, convert to v4f32 so the generated
1878 // register is legal.
1879 if (!Subtarget->hasSSE2())
1880 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1885 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1886 Flag = Chain.getValue(1);
1887 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1890 // The x86-64 ABIs require that for returning structs by value we copy
1891 // the sret argument into %rax/%eax (depending on ABI) for the return.
1892 // Win32 requires us to put the sret argument to %eax as well.
1893 // We saved the argument into a virtual register in the entry block,
1894 // so now we copy the value out and into %rax/%eax.
1895 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1896 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1897 MachineFunction &MF = DAG.getMachineFunction();
1898 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1899 unsigned Reg = FuncInfo->getSRetReturnReg();
1901 "SRetReturnReg should have been set in LowerFormalArguments().");
1902 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1905 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1906 X86::RAX : X86::EAX;
1907 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1908 Flag = Chain.getValue(1);
1910 // RAX/EAX now acts like a return value.
1911 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1914 RetOps[0] = Chain; // Update chain.
1916 // Add the flag if we have it.
1918 RetOps.push_back(Flag);
1920 return DAG.getNode(X86ISD::RET_FLAG, dl,
1921 MVT::Other, &RetOps[0], RetOps.size());
1924 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1925 if (N->getNumValues() != 1)
1927 if (!N->hasNUsesOfValue(1, 0))
1930 SDValue TCChain = Chain;
1931 SDNode *Copy = *N->use_begin();
1932 if (Copy->getOpcode() == ISD::CopyToReg) {
1933 // If the copy has a glue operand, we conservatively assume it isn't safe to
1934 // perform a tail call.
1935 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1937 TCChain = Copy->getOperand(0);
1938 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1941 bool HasRet = false;
1942 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1944 if (UI->getOpcode() != X86ISD::RET_FLAG)
1957 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1958 ISD::NodeType ExtendKind) const {
1960 // TODO: Is this also valid on 32-bit?
1961 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1962 ReturnMVT = MVT::i8;
1964 ReturnMVT = MVT::i32;
1966 MVT MinVT = getRegisterType(ReturnMVT);
1967 return VT.bitsLT(MinVT) ? MinVT : VT;
1970 /// LowerCallResult - Lower the result values of a call into the
1971 /// appropriate copies out of appropriate physical registers.
1974 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1975 CallingConv::ID CallConv, bool isVarArg,
1976 const SmallVectorImpl<ISD::InputArg> &Ins,
1977 SDLoc dl, SelectionDAG &DAG,
1978 SmallVectorImpl<SDValue> &InVals) const {
1980 // Assign locations to each value returned by this call.
1981 SmallVector<CCValAssign, 16> RVLocs;
1982 bool Is64Bit = Subtarget->is64Bit();
1983 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1984 getTargetMachine(), RVLocs, *DAG.getContext());
1985 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1987 // Copy all of the result registers out of their specified physreg.
1988 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1989 CCValAssign &VA = RVLocs[i];
1990 EVT CopyVT = VA.getValVT();
1992 // If this is x86-64, and we disabled SSE, we can't return FP values
1993 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1994 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1995 report_fatal_error("SSE register return with SSE disabled");
2000 // If this is a call to a function that returns an fp value on the floating
2001 // point stack, we must guarantee the value is popped from the stack, so
2002 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2003 // if the return value is not used. We use the FpPOP_RETVAL instruction
2005 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2006 // If we prefer to use the value in xmm registers, copy it out as f80 and
2007 // use a truncate to move it from fp stack reg to xmm reg.
2008 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2009 SDValue Ops[] = { Chain, InFlag };
2010 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2011 MVT::Other, MVT::Glue, Ops), 1);
2012 Val = Chain.getValue(0);
2014 // Round the f80 to the right size, which also moves it to the appropriate
2016 if (CopyVT != VA.getValVT())
2017 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2018 // This truncation won't change the value.
2019 DAG.getIntPtrConstant(1));
2021 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2022 CopyVT, InFlag).getValue(1);
2023 Val = Chain.getValue(0);
2025 InFlag = Chain.getValue(2);
2026 InVals.push_back(Val);
2032 //===----------------------------------------------------------------------===//
2033 // C & StdCall & Fast Calling Convention implementation
2034 //===----------------------------------------------------------------------===//
2035 // StdCall calling convention seems to be standard for many Windows' API
2036 // routines and around. It differs from C calling convention just a little:
2037 // callee should clean up the stack, not caller. Symbols should be also
2038 // decorated in some fancy way :) It doesn't support any vector arguments.
2039 // For info on fast calling convention see Fast Calling Convention (tail call)
2040 // implementation LowerX86_32FastCCCallTo.
2042 /// CallIsStructReturn - Determines whether a call uses struct return
2044 enum StructReturnType {
2049 static StructReturnType
2050 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2052 return NotStructReturn;
2054 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2055 if (!Flags.isSRet())
2056 return NotStructReturn;
2057 if (Flags.isInReg())
2058 return RegStructReturn;
2059 return StackStructReturn;
2062 /// ArgsAreStructReturn - Determines whether a function uses struct
2063 /// return semantics.
2064 static StructReturnType
2065 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2067 return NotStructReturn;
2069 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2070 if (!Flags.isSRet())
2071 return NotStructReturn;
2072 if (Flags.isInReg())
2073 return RegStructReturn;
2074 return StackStructReturn;
2077 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2078 /// by "Src" to address "Dst" with size and alignment information specified by
2079 /// the specific parameter attribute. The copy will be passed as a byval
2080 /// function parameter.
2082 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2083 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2085 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2087 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2088 /*isVolatile*/false, /*AlwaysInline=*/true,
2089 MachinePointerInfo(), MachinePointerInfo());
2092 /// IsTailCallConvention - Return true if the calling convention is one that
2093 /// supports tail call optimization.
2094 static bool IsTailCallConvention(CallingConv::ID CC) {
2095 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2096 CC == CallingConv::HiPE);
2099 /// \brief Return true if the calling convention is a C calling convention.
2100 static bool IsCCallConvention(CallingConv::ID CC) {
2101 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2102 CC == CallingConv::X86_64_SysV);
2105 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2106 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2110 CallingConv::ID CalleeCC = CS.getCallingConv();
2111 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2117 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2118 /// a tailcall target by changing its ABI.
2119 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2120 bool GuaranteedTailCallOpt) {
2121 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2125 X86TargetLowering::LowerMemArgument(SDValue Chain,
2126 CallingConv::ID CallConv,
2127 const SmallVectorImpl<ISD::InputArg> &Ins,
2128 SDLoc dl, SelectionDAG &DAG,
2129 const CCValAssign &VA,
2130 MachineFrameInfo *MFI,
2132 // Create the nodes corresponding to a load from this parameter slot.
2133 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2134 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2135 getTargetMachine().Options.GuaranteedTailCallOpt);
2136 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2139 // If value is passed by pointer we have address passed instead of the value
2141 if (VA.getLocInfo() == CCValAssign::Indirect)
2142 ValVT = VA.getLocVT();
2144 ValVT = VA.getValVT();
2146 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2147 // changed with more analysis.
2148 // In case of tail call optimization mark all arguments mutable. Since they
2149 // could be overwritten by lowering of arguments in case of a tail call.
2150 if (Flags.isByVal()) {
2151 unsigned Bytes = Flags.getByValSize();
2152 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2153 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2154 return DAG.getFrameIndex(FI, getPointerTy());
2156 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2157 VA.getLocMemOffset(), isImmutable);
2158 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2159 return DAG.getLoad(ValVT, dl, Chain, FIN,
2160 MachinePointerInfo::getFixedStack(FI),
2161 false, false, false, 0);
2166 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2167 CallingConv::ID CallConv,
2169 const SmallVectorImpl<ISD::InputArg> &Ins,
2172 SmallVectorImpl<SDValue> &InVals)
2174 MachineFunction &MF = DAG.getMachineFunction();
2175 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2177 const Function* Fn = MF.getFunction();
2178 if (Fn->hasExternalLinkage() &&
2179 Subtarget->isTargetCygMing() &&
2180 Fn->getName() == "main")
2181 FuncInfo->setForceFramePointer(true);
2183 MachineFrameInfo *MFI = MF.getFrameInfo();
2184 bool Is64Bit = Subtarget->is64Bit();
2185 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2187 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2188 "Var args not supported with calling convention fastcc, ghc or hipe");
2190 // Assign locations to all of the incoming arguments.
2191 SmallVector<CCValAssign, 16> ArgLocs;
2192 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2193 ArgLocs, *DAG.getContext());
2195 // Allocate shadow area for Win64
2197 CCInfo.AllocateStack(32, 8);
2199 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2201 unsigned LastVal = ~0U;
2203 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2204 CCValAssign &VA = ArgLocs[i];
2205 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2207 assert(VA.getValNo() != LastVal &&
2208 "Don't support value assigned to multiple locs yet");
2210 LastVal = VA.getValNo();
2212 if (VA.isRegLoc()) {
2213 EVT RegVT = VA.getLocVT();
2214 const TargetRegisterClass *RC;
2215 if (RegVT == MVT::i32)
2216 RC = &X86::GR32RegClass;
2217 else if (Is64Bit && RegVT == MVT::i64)
2218 RC = &X86::GR64RegClass;
2219 else if (RegVT == MVT::f32)
2220 RC = &X86::FR32RegClass;
2221 else if (RegVT == MVT::f64)
2222 RC = &X86::FR64RegClass;
2223 else if (RegVT.is512BitVector())
2224 RC = &X86::VR512RegClass;
2225 else if (RegVT.is256BitVector())
2226 RC = &X86::VR256RegClass;
2227 else if (RegVT.is128BitVector())
2228 RC = &X86::VR128RegClass;
2229 else if (RegVT == MVT::x86mmx)
2230 RC = &X86::VR64RegClass;
2231 else if (RegVT == MVT::i1)
2232 RC = &X86::VK1RegClass;
2233 else if (RegVT == MVT::v8i1)
2234 RC = &X86::VK8RegClass;
2235 else if (RegVT == MVT::v16i1)
2236 RC = &X86::VK16RegClass;
2238 llvm_unreachable("Unknown argument type!");
2240 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2241 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2243 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2244 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2246 if (VA.getLocInfo() == CCValAssign::SExt)
2247 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2248 DAG.getValueType(VA.getValVT()));
2249 else if (VA.getLocInfo() == CCValAssign::ZExt)
2250 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2251 DAG.getValueType(VA.getValVT()));
2252 else if (VA.getLocInfo() == CCValAssign::BCvt)
2253 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2255 if (VA.isExtInLoc()) {
2256 // Handle MMX values passed in XMM regs.
2257 if (RegVT.isVector())
2258 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2260 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2263 assert(VA.isMemLoc());
2264 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2267 // If value is passed via pointer - do a load.
2268 if (VA.getLocInfo() == CCValAssign::Indirect)
2269 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2270 MachinePointerInfo(), false, false, false, 0);
2272 InVals.push_back(ArgValue);
2275 // The x86-64 ABIs require that for returning structs by value we copy
2276 // the sret argument into %rax/%eax (depending on ABI) for the return.
2277 // Win32 requires us to put the sret argument to %eax as well.
2278 // Save the argument into a virtual register so that we can access it
2279 // from the return points.
2280 if (MF.getFunction()->hasStructRetAttr() &&
2281 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2282 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2283 unsigned Reg = FuncInfo->getSRetReturnReg();
2285 MVT PtrTy = getPointerTy();
2286 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2287 FuncInfo->setSRetReturnReg(Reg);
2289 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2290 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2293 unsigned StackSize = CCInfo.getNextStackOffset();
2294 // Align stack specially for tail calls.
2295 if (FuncIsMadeTailCallSafe(CallConv,
2296 MF.getTarget().Options.GuaranteedTailCallOpt))
2297 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2299 // If the function takes variable number of arguments, make a frame index for
2300 // the start of the first vararg value... for expansion of llvm.va_start.
2302 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2303 CallConv != CallingConv::X86_ThisCall)) {
2304 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2307 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2309 // FIXME: We should really autogenerate these arrays
2310 static const uint16_t GPR64ArgRegsWin64[] = {
2311 X86::RCX, X86::RDX, X86::R8, X86::R9
2313 static const uint16_t GPR64ArgRegs64Bit[] = {
2314 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2316 static const uint16_t XMMArgRegs64Bit[] = {
2317 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2318 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2320 const uint16_t *GPR64ArgRegs;
2321 unsigned NumXMMRegs = 0;
2324 // The XMM registers which might contain var arg parameters are shadowed
2325 // in their paired GPR. So we only need to save the GPR to their home
2327 TotalNumIntRegs = 4;
2328 GPR64ArgRegs = GPR64ArgRegsWin64;
2330 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2331 GPR64ArgRegs = GPR64ArgRegs64Bit;
2333 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2336 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2339 bool NoImplicitFloatOps = Fn->getAttributes().
2340 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2341 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2342 "SSE register cannot be used when SSE is disabled!");
2343 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2344 NoImplicitFloatOps) &&
2345 "SSE register cannot be used when SSE is disabled!");
2346 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2347 !Subtarget->hasSSE1())
2348 // Kernel mode asks for SSE to be disabled, so don't push them
2350 TotalNumXMMRegs = 0;
2353 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2354 // Get to the caller-allocated home save location. Add 8 to account
2355 // for the return address.
2356 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2357 FuncInfo->setRegSaveFrameIndex(
2358 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2359 // Fixup to set vararg frame on shadow area (4 x i64).
2361 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2363 // For X86-64, if there are vararg parameters that are passed via
2364 // registers, then we must store them to their spots on the stack so
2365 // they may be loaded by deferencing the result of va_next.
2366 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2367 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2368 FuncInfo->setRegSaveFrameIndex(
2369 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2373 // Store the integer parameter registers.
2374 SmallVector<SDValue, 8> MemOps;
2375 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2377 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2378 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2379 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2380 DAG.getIntPtrConstant(Offset));
2381 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2382 &X86::GR64RegClass);
2383 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2385 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2386 MachinePointerInfo::getFixedStack(
2387 FuncInfo->getRegSaveFrameIndex(), Offset),
2389 MemOps.push_back(Store);
2393 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2394 // Now store the XMM (fp + vector) parameter registers.
2395 SmallVector<SDValue, 11> SaveXMMOps;
2396 SaveXMMOps.push_back(Chain);
2398 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2399 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2400 SaveXMMOps.push_back(ALVal);
2402 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2403 FuncInfo->getRegSaveFrameIndex()));
2404 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2405 FuncInfo->getVarArgsFPOffset()));
2407 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2408 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2409 &X86::VR128RegClass);
2410 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2411 SaveXMMOps.push_back(Val);
2413 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2415 &SaveXMMOps[0], SaveXMMOps.size()));
2418 if (!MemOps.empty())
2419 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2420 &MemOps[0], MemOps.size());
2424 // Some CCs need callee pop.
2425 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2426 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2427 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2429 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2430 // If this is an sret function, the return should pop the hidden pointer.
2431 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2432 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2433 argsAreStructReturn(Ins) == StackStructReturn)
2434 FuncInfo->setBytesToPopOnReturn(4);
2438 // RegSaveFrameIndex is X86-64 only.
2439 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2440 if (CallConv == CallingConv::X86_FastCall ||
2441 CallConv == CallingConv::X86_ThisCall)
2442 // fastcc functions can't have varargs.
2443 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2446 FuncInfo->setArgumentStackSize(StackSize);
2452 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2453 SDValue StackPtr, SDValue Arg,
2454 SDLoc dl, SelectionDAG &DAG,
2455 const CCValAssign &VA,
2456 ISD::ArgFlagsTy Flags) const {
2457 unsigned LocMemOffset = VA.getLocMemOffset();
2458 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2459 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2460 if (Flags.isByVal())
2461 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2463 return DAG.getStore(Chain, dl, Arg, PtrOff,
2464 MachinePointerInfo::getStack(LocMemOffset),
2468 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2469 /// optimization is performed and it is required.
2471 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2472 SDValue &OutRetAddr, SDValue Chain,
2473 bool IsTailCall, bool Is64Bit,
2474 int FPDiff, SDLoc dl) const {
2475 // Adjust the Return address stack slot.
2476 EVT VT = getPointerTy();
2477 OutRetAddr = getReturnAddressFrameIndex(DAG);
2479 // Load the "old" Return address.
2480 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2481 false, false, false, 0);
2482 return SDValue(OutRetAddr.getNode(), 1);
2485 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2486 /// optimization is performed and it is required (FPDiff!=0).
2488 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2489 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2490 unsigned SlotSize, int FPDiff, SDLoc dl) {
2491 // Store the return address to the appropriate stack slot.
2492 if (!FPDiff) return Chain;
2493 // Calculate the new stack slot for the return address.
2494 int NewReturnAddrFI =
2495 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2497 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2498 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2499 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2505 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2506 SmallVectorImpl<SDValue> &InVals) const {
2507 SelectionDAG &DAG = CLI.DAG;
2509 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2510 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2511 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2512 SDValue Chain = CLI.Chain;
2513 SDValue Callee = CLI.Callee;
2514 CallingConv::ID CallConv = CLI.CallConv;
2515 bool &isTailCall = CLI.IsTailCall;
2516 bool isVarArg = CLI.IsVarArg;
2518 MachineFunction &MF = DAG.getMachineFunction();
2519 bool Is64Bit = Subtarget->is64Bit();
2520 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2521 StructReturnType SR = callIsStructReturn(Outs);
2522 bool IsSibcall = false;
2524 if (MF.getTarget().Options.DisableTailCalls)
2528 // Check if it's really possible to do a tail call.
2529 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2530 isVarArg, SR != NotStructReturn,
2531 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2532 Outs, OutVals, Ins, DAG);
2534 // Sibcalls are automatically detected tailcalls which do not require
2536 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2543 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2544 "Var args not supported with calling convention fastcc, ghc or hipe");
2546 // Analyze operands of the call, assigning locations to each operand.
2547 SmallVector<CCValAssign, 16> ArgLocs;
2548 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2549 ArgLocs, *DAG.getContext());
2551 // Allocate shadow area for Win64
2553 CCInfo.AllocateStack(32, 8);
2555 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2557 // Get a count of how many bytes are to be pushed on the stack.
2558 unsigned NumBytes = CCInfo.getNextStackOffset();
2560 // This is a sibcall. The memory operands are available in caller's
2561 // own caller's stack.
2563 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2564 IsTailCallConvention(CallConv))
2565 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2568 if (isTailCall && !IsSibcall) {
2569 // Lower arguments at fp - stackoffset + fpdiff.
2570 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2571 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2573 FPDiff = NumBytesCallerPushed - NumBytes;
2575 // Set the delta of movement of the returnaddr stackslot.
2576 // But only set if delta is greater than previous delta.
2577 if (FPDiff < X86Info->getTCReturnAddrDelta())
2578 X86Info->setTCReturnAddrDelta(FPDiff);
2582 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2585 SDValue RetAddrFrIdx;
2586 // Load return address for tail calls.
2587 if (isTailCall && FPDiff)
2588 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2589 Is64Bit, FPDiff, dl);
2591 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2592 SmallVector<SDValue, 8> MemOpChains;
2595 // Walk the register/memloc assignments, inserting copies/loads. In the case
2596 // of tail call optimization arguments are handle later.
2597 const X86RegisterInfo *RegInfo =
2598 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2599 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2600 CCValAssign &VA = ArgLocs[i];
2601 EVT RegVT = VA.getLocVT();
2602 SDValue Arg = OutVals[i];
2603 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2604 bool isByVal = Flags.isByVal();
2606 // Promote the value if needed.
2607 switch (VA.getLocInfo()) {
2608 default: llvm_unreachable("Unknown loc info!");
2609 case CCValAssign::Full: break;
2610 case CCValAssign::SExt:
2611 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2613 case CCValAssign::ZExt:
2614 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2616 case CCValAssign::AExt:
2617 if (RegVT.is128BitVector()) {
2618 // Special case: passing MMX values in XMM registers.
2619 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2620 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2621 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2623 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2625 case CCValAssign::BCvt:
2626 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2628 case CCValAssign::Indirect: {
2629 // Store the argument.
2630 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2631 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2632 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2633 MachinePointerInfo::getFixedStack(FI),
2640 if (VA.isRegLoc()) {
2641 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2642 if (isVarArg && IsWin64) {
2643 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2644 // shadow reg if callee is a varargs function.
2645 unsigned ShadowReg = 0;
2646 switch (VA.getLocReg()) {
2647 case X86::XMM0: ShadowReg = X86::RCX; break;
2648 case X86::XMM1: ShadowReg = X86::RDX; break;
2649 case X86::XMM2: ShadowReg = X86::R8; break;
2650 case X86::XMM3: ShadowReg = X86::R9; break;
2653 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2655 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2656 assert(VA.isMemLoc());
2657 if (StackPtr.getNode() == 0)
2658 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2660 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2661 dl, DAG, VA, Flags));
2665 if (!MemOpChains.empty())
2666 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2667 &MemOpChains[0], MemOpChains.size());
2669 if (Subtarget->isPICStyleGOT()) {
2670 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2673 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2674 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2676 // If we are tail calling and generating PIC/GOT style code load the
2677 // address of the callee into ECX. The value in ecx is used as target of
2678 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2679 // for tail calls on PIC/GOT architectures. Normally we would just put the
2680 // address of GOT into ebx and then call target@PLT. But for tail calls
2681 // ebx would be restored (since ebx is callee saved) before jumping to the
2684 // Note: The actual moving to ECX is done further down.
2685 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2686 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2687 !G->getGlobal()->hasProtectedVisibility())
2688 Callee = LowerGlobalAddress(Callee, DAG);
2689 else if (isa<ExternalSymbolSDNode>(Callee))
2690 Callee = LowerExternalSymbol(Callee, DAG);
2694 if (Is64Bit && isVarArg && !IsWin64) {
2695 // From AMD64 ABI document:
2696 // For calls that may call functions that use varargs or stdargs
2697 // (prototype-less calls or calls to functions containing ellipsis (...) in
2698 // the declaration) %al is used as hidden argument to specify the number
2699 // of SSE registers used. The contents of %al do not need to match exactly
2700 // the number of registers, but must be an ubound on the number of SSE
2701 // registers used and is in the range 0 - 8 inclusive.
2703 // Count the number of XMM registers allocated.
2704 static const uint16_t XMMArgRegs[] = {
2705 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2706 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2708 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2709 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2710 && "SSE registers cannot be used when SSE is disabled");
2712 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2713 DAG.getConstant(NumXMMRegs, MVT::i8)));
2716 // For tail calls lower the arguments to the 'real' stack slot.
2718 // Force all the incoming stack arguments to be loaded from the stack
2719 // before any new outgoing arguments are stored to the stack, because the
2720 // outgoing stack slots may alias the incoming argument stack slots, and
2721 // the alias isn't otherwise explicit. This is slightly more conservative
2722 // than necessary, because it means that each store effectively depends
2723 // on every argument instead of just those arguments it would clobber.
2724 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2726 SmallVector<SDValue, 8> MemOpChains2;
2729 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2730 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2731 CCValAssign &VA = ArgLocs[i];
2734 assert(VA.isMemLoc());
2735 SDValue Arg = OutVals[i];
2736 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2737 // Create frame index.
2738 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2739 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2740 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2741 FIN = DAG.getFrameIndex(FI, getPointerTy());
2743 if (Flags.isByVal()) {
2744 // Copy relative to framepointer.
2745 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2746 if (StackPtr.getNode() == 0)
2747 StackPtr = DAG.getCopyFromReg(Chain, dl,
2748 RegInfo->getStackRegister(),
2750 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2752 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2756 // Store relative to framepointer.
2757 MemOpChains2.push_back(
2758 DAG.getStore(ArgChain, dl, Arg, FIN,
2759 MachinePointerInfo::getFixedStack(FI),
2765 if (!MemOpChains2.empty())
2766 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2767 &MemOpChains2[0], MemOpChains2.size());
2769 // Store the return address to the appropriate stack slot.
2770 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2771 getPointerTy(), RegInfo->getSlotSize(),
2775 // Build a sequence of copy-to-reg nodes chained together with token chain
2776 // and flag operands which copy the outgoing args into registers.
2778 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2779 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2780 RegsToPass[i].second, InFlag);
2781 InFlag = Chain.getValue(1);
2784 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2785 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2786 // In the 64-bit large code model, we have to make all calls
2787 // through a register, since the call instruction's 32-bit
2788 // pc-relative offset may not be large enough to hold the whole
2790 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2791 // If the callee is a GlobalAddress node (quite common, every direct call
2792 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2795 // We should use extra load for direct calls to dllimported functions in
2797 const GlobalValue *GV = G->getGlobal();
2798 if (!GV->hasDLLImportLinkage()) {
2799 unsigned char OpFlags = 0;
2800 bool ExtraLoad = false;
2801 unsigned WrapperKind = ISD::DELETED_NODE;
2803 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2804 // external symbols most go through the PLT in PIC mode. If the symbol
2805 // has hidden or protected visibility, or if it is static or local, then
2806 // we don't need to use the PLT - we can directly call it.
2807 if (Subtarget->isTargetELF() &&
2808 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2809 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2810 OpFlags = X86II::MO_PLT;
2811 } else if (Subtarget->isPICStyleStubAny() &&
2812 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2813 (!Subtarget->getTargetTriple().isMacOSX() ||
2814 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2815 // PC-relative references to external symbols should go through $stub,
2816 // unless we're building with the leopard linker or later, which
2817 // automatically synthesizes these stubs.
2818 OpFlags = X86II::MO_DARWIN_STUB;
2819 } else if (Subtarget->isPICStyleRIPRel() &&
2820 isa<Function>(GV) &&
2821 cast<Function>(GV)->getAttributes().
2822 hasAttribute(AttributeSet::FunctionIndex,
2823 Attribute::NonLazyBind)) {
2824 // If the function is marked as non-lazy, generate an indirect call
2825 // which loads from the GOT directly. This avoids runtime overhead
2826 // at the cost of eager binding (and one extra byte of encoding).
2827 OpFlags = X86II::MO_GOTPCREL;
2828 WrapperKind = X86ISD::WrapperRIP;
2832 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2833 G->getOffset(), OpFlags);
2835 // Add a wrapper if needed.
2836 if (WrapperKind != ISD::DELETED_NODE)
2837 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2838 // Add extra indirection if needed.
2840 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2841 MachinePointerInfo::getGOT(),
2842 false, false, false, 0);
2844 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2845 unsigned char OpFlags = 0;
2847 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2848 // external symbols should go through the PLT.
2849 if (Subtarget->isTargetELF() &&
2850 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2851 OpFlags = X86II::MO_PLT;
2852 } else if (Subtarget->isPICStyleStubAny() &&
2853 (!Subtarget->getTargetTriple().isMacOSX() ||
2854 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2855 // PC-relative references to external symbols should go through $stub,
2856 // unless we're building with the leopard linker or later, which
2857 // automatically synthesizes these stubs.
2858 OpFlags = X86II::MO_DARWIN_STUB;
2861 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2865 // Returns a chain & a flag for retval copy to use.
2866 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2867 SmallVector<SDValue, 8> Ops;
2869 if (!IsSibcall && isTailCall) {
2870 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2871 DAG.getIntPtrConstant(0, true), InFlag, dl);
2872 InFlag = Chain.getValue(1);
2875 Ops.push_back(Chain);
2876 Ops.push_back(Callee);
2879 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2881 // Add argument registers to the end of the list so that they are known live
2883 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2884 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2885 RegsToPass[i].second.getValueType()));
2887 // Add a register mask operand representing the call-preserved registers.
2888 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2889 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2890 assert(Mask && "Missing call preserved mask for calling convention");
2891 Ops.push_back(DAG.getRegisterMask(Mask));
2893 if (InFlag.getNode())
2894 Ops.push_back(InFlag);
2898 //// If this is the first return lowered for this function, add the regs
2899 //// to the liveout set for the function.
2900 // This isn't right, although it's probably harmless on x86; liveouts
2901 // should be computed from returns not tail calls. Consider a void
2902 // function making a tail call to a function returning int.
2903 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2906 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2907 InFlag = Chain.getValue(1);
2909 // Create the CALLSEQ_END node.
2910 unsigned NumBytesForCalleeToPush;
2911 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2912 getTargetMachine().Options.GuaranteedTailCallOpt))
2913 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2914 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2915 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2916 SR == StackStructReturn)
2917 // If this is a call to a struct-return function, the callee
2918 // pops the hidden struct pointer, so we have to push it back.
2919 // This is common for Darwin/X86, Linux & Mingw32 targets.
2920 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2921 NumBytesForCalleeToPush = 4;
2923 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2925 // Returns a flag for retval copy to use.
2927 Chain = DAG.getCALLSEQ_END(Chain,
2928 DAG.getIntPtrConstant(NumBytes, true),
2929 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2932 InFlag = Chain.getValue(1);
2935 // Handle result values, copying them out of physregs into vregs that we
2937 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2938 Ins, dl, DAG, InVals);
2941 //===----------------------------------------------------------------------===//
2942 // Fast Calling Convention (tail call) implementation
2943 //===----------------------------------------------------------------------===//
2945 // Like std call, callee cleans arguments, convention except that ECX is
2946 // reserved for storing the tail called function address. Only 2 registers are
2947 // free for argument passing (inreg). Tail call optimization is performed
2949 // * tailcallopt is enabled
2950 // * caller/callee are fastcc
2951 // On X86_64 architecture with GOT-style position independent code only local
2952 // (within module) calls are supported at the moment.
2953 // To keep the stack aligned according to platform abi the function
2954 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2955 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2956 // If a tail called function callee has more arguments than the caller the
2957 // caller needs to make sure that there is room to move the RETADDR to. This is
2958 // achieved by reserving an area the size of the argument delta right after the
2959 // original REtADDR, but before the saved framepointer or the spilled registers
2960 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2972 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2973 /// for a 16 byte align requirement.
2975 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2976 SelectionDAG& DAG) const {
2977 MachineFunction &MF = DAG.getMachineFunction();
2978 const TargetMachine &TM = MF.getTarget();
2979 const X86RegisterInfo *RegInfo =
2980 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2981 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2982 unsigned StackAlignment = TFI.getStackAlignment();
2983 uint64_t AlignMask = StackAlignment - 1;
2984 int64_t Offset = StackSize;
2985 unsigned SlotSize = RegInfo->getSlotSize();
2986 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2987 // Number smaller than 12 so just add the difference.
2988 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2990 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2991 Offset = ((~AlignMask) & Offset) + StackAlignment +
2992 (StackAlignment-SlotSize);
2997 /// MatchingStackOffset - Return true if the given stack call argument is
2998 /// already available in the same position (relatively) of the caller's
2999 /// incoming argument stack.
3001 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3002 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3003 const X86InstrInfo *TII) {
3004 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3006 if (Arg.getOpcode() == ISD::CopyFromReg) {
3007 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3008 if (!TargetRegisterInfo::isVirtualRegister(VR))
3010 MachineInstr *Def = MRI->getVRegDef(VR);
3013 if (!Flags.isByVal()) {
3014 if (!TII->isLoadFromStackSlot(Def, FI))
3017 unsigned Opcode = Def->getOpcode();
3018 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3019 Def->getOperand(1).isFI()) {
3020 FI = Def->getOperand(1).getIndex();
3021 Bytes = Flags.getByValSize();
3025 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3026 if (Flags.isByVal())
3027 // ByVal argument is passed in as a pointer but it's now being
3028 // dereferenced. e.g.
3029 // define @foo(%struct.X* %A) {
3030 // tail call @bar(%struct.X* byval %A)
3033 SDValue Ptr = Ld->getBasePtr();
3034 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3037 FI = FINode->getIndex();
3038 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3039 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3040 FI = FINode->getIndex();
3041 Bytes = Flags.getByValSize();
3045 assert(FI != INT_MAX);
3046 if (!MFI->isFixedObjectIndex(FI))
3048 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3051 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3052 /// for tail call optimization. Targets which want to do tail call
3053 /// optimization should implement this function.
3055 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3056 CallingConv::ID CalleeCC,
3058 bool isCalleeStructRet,
3059 bool isCallerStructRet,
3061 const SmallVectorImpl<ISD::OutputArg> &Outs,
3062 const SmallVectorImpl<SDValue> &OutVals,
3063 const SmallVectorImpl<ISD::InputArg> &Ins,
3064 SelectionDAG &DAG) const {
3065 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3068 // If -tailcallopt is specified, make fastcc functions tail-callable.
3069 const MachineFunction &MF = DAG.getMachineFunction();
3070 const Function *CallerF = MF.getFunction();
3072 // If the function return type is x86_fp80 and the callee return type is not,
3073 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3074 // perform a tailcall optimization here.
3075 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3078 CallingConv::ID CallerCC = CallerF->getCallingConv();
3079 bool CCMatch = CallerCC == CalleeCC;
3080 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3081 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3083 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3084 if (IsTailCallConvention(CalleeCC) && CCMatch)
3089 // Look for obvious safe cases to perform tail call optimization that do not
3090 // require ABI changes. This is what gcc calls sibcall.
3092 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3093 // emit a special epilogue.
3094 const X86RegisterInfo *RegInfo =
3095 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3096 if (RegInfo->needsStackRealignment(MF))
3099 // Also avoid sibcall optimization if either caller or callee uses struct
3100 // return semantics.
3101 if (isCalleeStructRet || isCallerStructRet)
3104 // An stdcall/thiscall caller is expected to clean up its arguments; the
3105 // callee isn't going to do that.
3106 // FIXME: this is more restrictive than needed. We could produce a tailcall
3107 // when the stack adjustment matches. For example, with a thiscall that takes
3108 // only one argument.
3109 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3110 CallerCC == CallingConv::X86_ThisCall))
3113 // Do not sibcall optimize vararg calls unless all arguments are passed via
3115 if (isVarArg && !Outs.empty()) {
3117 // Optimizing for varargs on Win64 is unlikely to be safe without
3118 // additional testing.
3119 if (IsCalleeWin64 || IsCallerWin64)
3122 SmallVector<CCValAssign, 16> ArgLocs;
3123 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3124 getTargetMachine(), ArgLocs, *DAG.getContext());
3126 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3127 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3128 if (!ArgLocs[i].isRegLoc())
3132 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3133 // stack. Therefore, if it's not used by the call it is not safe to optimize
3134 // this into a sibcall.
3135 bool Unused = false;
3136 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3143 SmallVector<CCValAssign, 16> RVLocs;
3144 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3145 getTargetMachine(), RVLocs, *DAG.getContext());
3146 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3147 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3148 CCValAssign &VA = RVLocs[i];
3149 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3154 // If the calling conventions do not match, then we'd better make sure the
3155 // results are returned in the same way as what the caller expects.
3157 SmallVector<CCValAssign, 16> RVLocs1;
3158 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3159 getTargetMachine(), RVLocs1, *DAG.getContext());
3160 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3162 SmallVector<CCValAssign, 16> RVLocs2;
3163 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3164 getTargetMachine(), RVLocs2, *DAG.getContext());
3165 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3167 if (RVLocs1.size() != RVLocs2.size())
3169 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3170 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3172 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3174 if (RVLocs1[i].isRegLoc()) {
3175 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3178 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3184 // If the callee takes no arguments then go on to check the results of the
3186 if (!Outs.empty()) {
3187 // Check if stack adjustment is needed. For now, do not do this if any
3188 // argument is passed on the stack.
3189 SmallVector<CCValAssign, 16> ArgLocs;
3190 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3191 getTargetMachine(), ArgLocs, *DAG.getContext());
3193 // Allocate shadow area for Win64
3195 CCInfo.AllocateStack(32, 8);
3197 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3198 if (CCInfo.getNextStackOffset()) {
3199 MachineFunction &MF = DAG.getMachineFunction();
3200 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3203 // Check if the arguments are already laid out in the right way as
3204 // the caller's fixed stack objects.
3205 MachineFrameInfo *MFI = MF.getFrameInfo();
3206 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3207 const X86InstrInfo *TII =
3208 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3209 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3210 CCValAssign &VA = ArgLocs[i];
3211 SDValue Arg = OutVals[i];
3212 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3213 if (VA.getLocInfo() == CCValAssign::Indirect)
3215 if (!VA.isRegLoc()) {
3216 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3223 // If the tailcall address may be in a register, then make sure it's
3224 // possible to register allocate for it. In 32-bit, the call address can
3225 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3226 // callee-saved registers are restored. These happen to be the same
3227 // registers used to pass 'inreg' arguments so watch out for those.
3228 if (!Subtarget->is64Bit() &&
3229 ((!isa<GlobalAddressSDNode>(Callee) &&
3230 !isa<ExternalSymbolSDNode>(Callee)) ||
3231 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3232 unsigned NumInRegs = 0;
3233 // In PIC we need an extra register to formulate the address computation
3235 unsigned MaxInRegs =
3236 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3238 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3239 CCValAssign &VA = ArgLocs[i];
3242 unsigned Reg = VA.getLocReg();
3245 case X86::EAX: case X86::EDX: case X86::ECX:
3246 if (++NumInRegs == MaxInRegs)
3258 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3259 const TargetLibraryInfo *libInfo) const {
3260 return X86::createFastISel(funcInfo, libInfo);
3263 //===----------------------------------------------------------------------===//
3264 // Other Lowering Hooks
3265 //===----------------------------------------------------------------------===//
3267 static bool MayFoldLoad(SDValue Op) {
3268 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3271 static bool MayFoldIntoStore(SDValue Op) {
3272 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3275 static bool isTargetShuffle(unsigned Opcode) {
3277 default: return false;
3278 case X86ISD::PSHUFD:
3279 case X86ISD::PSHUFHW:
3280 case X86ISD::PSHUFLW:
3282 case X86ISD::PALIGNR:
3283 case X86ISD::MOVLHPS:
3284 case X86ISD::MOVLHPD:
3285 case X86ISD::MOVHLPS:
3286 case X86ISD::MOVLPS:
3287 case X86ISD::MOVLPD:
3288 case X86ISD::MOVSHDUP:
3289 case X86ISD::MOVSLDUP:
3290 case X86ISD::MOVDDUP:
3293 case X86ISD::UNPCKL:
3294 case X86ISD::UNPCKH:
3295 case X86ISD::VPERMILP:
3296 case X86ISD::VPERM2X128:
3297 case X86ISD::VPERMI:
3302 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3303 SDValue V1, SelectionDAG &DAG) {
3305 default: llvm_unreachable("Unknown x86 shuffle node");
3306 case X86ISD::MOVSHDUP:
3307 case X86ISD::MOVSLDUP:
3308 case X86ISD::MOVDDUP:
3309 return DAG.getNode(Opc, dl, VT, V1);
3313 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3314 SDValue V1, unsigned TargetMask,
3315 SelectionDAG &DAG) {
3317 default: llvm_unreachable("Unknown x86 shuffle node");
3318 case X86ISD::PSHUFD:
3319 case X86ISD::PSHUFHW:
3320 case X86ISD::PSHUFLW:
3321 case X86ISD::VPERMILP:
3322 case X86ISD::VPERMI:
3323 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3327 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3328 SDValue V1, SDValue V2, unsigned TargetMask,
3329 SelectionDAG &DAG) {
3331 default: llvm_unreachable("Unknown x86 shuffle node");
3332 case X86ISD::PALIGNR:
3334 case X86ISD::VPERM2X128:
3335 return DAG.getNode(Opc, dl, VT, V1, V2,
3336 DAG.getConstant(TargetMask, MVT::i8));
3340 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3341 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3343 default: llvm_unreachable("Unknown x86 shuffle node");
3344 case X86ISD::MOVLHPS:
3345 case X86ISD::MOVLHPD:
3346 case X86ISD::MOVHLPS:
3347 case X86ISD::MOVLPS:
3348 case X86ISD::MOVLPD:
3351 case X86ISD::UNPCKL:
3352 case X86ISD::UNPCKH:
3353 return DAG.getNode(Opc, dl, VT, V1, V2);
3357 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3358 MachineFunction &MF = DAG.getMachineFunction();
3359 const X86RegisterInfo *RegInfo =
3360 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3361 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3362 int ReturnAddrIndex = FuncInfo->getRAIndex();
3364 if (ReturnAddrIndex == 0) {
3365 // Set up a frame object for the return address.
3366 unsigned SlotSize = RegInfo->getSlotSize();
3367 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3370 FuncInfo->setRAIndex(ReturnAddrIndex);
3373 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3376 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3377 bool hasSymbolicDisplacement) {
3378 // Offset should fit into 32 bit immediate field.
3379 if (!isInt<32>(Offset))
3382 // If we don't have a symbolic displacement - we don't have any extra
3384 if (!hasSymbolicDisplacement)
3387 // FIXME: Some tweaks might be needed for medium code model.
3388 if (M != CodeModel::Small && M != CodeModel::Kernel)
3391 // For small code model we assume that latest object is 16MB before end of 31
3392 // bits boundary. We may also accept pretty large negative constants knowing
3393 // that all objects are in the positive half of address space.
3394 if (M == CodeModel::Small && Offset < 16*1024*1024)
3397 // For kernel code model we know that all object resist in the negative half
3398 // of 32bits address space. We may not accept negative offsets, since they may
3399 // be just off and we may accept pretty large positive ones.
3400 if (M == CodeModel::Kernel && Offset > 0)
3406 /// isCalleePop - Determines whether the callee is required to pop its
3407 /// own arguments. Callee pop is necessary to support tail calls.
3408 bool X86::isCalleePop(CallingConv::ID CallingConv,
3409 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3413 switch (CallingConv) {
3416 case CallingConv::X86_StdCall:
3418 case CallingConv::X86_FastCall:
3420 case CallingConv::X86_ThisCall:
3422 case CallingConv::Fast:
3424 case CallingConv::GHC:
3426 case CallingConv::HiPE:
3431 /// \brief Return true if the condition is an unsigned comparison operation.
3432 static bool isX86CCUnsigned(unsigned X86CC) {
3434 default: llvm_unreachable("Invalid integer condition!");
3435 case X86::COND_E: return true;
3436 case X86::COND_G: return false;
3437 case X86::COND_GE: return false;
3438 case X86::COND_L: return false;
3439 case X86::COND_LE: return false;
3440 case X86::COND_NE: return true;
3441 case X86::COND_B: return true;
3442 case X86::COND_A: return true;
3443 case X86::COND_BE: return true;
3444 case X86::COND_AE: return true;
3446 llvm_unreachable("covered switch fell through?!");
3449 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3450 /// specific condition code, returning the condition code and the LHS/RHS of the
3451 /// comparison to make.
3452 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3453 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3455 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3456 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3457 // X > -1 -> X == 0, jump !sign.
3458 RHS = DAG.getConstant(0, RHS.getValueType());
3459 return X86::COND_NS;
3461 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3462 // X < 0 -> X == 0, jump on sign.
3465 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3467 RHS = DAG.getConstant(0, RHS.getValueType());
3468 return X86::COND_LE;
3472 switch (SetCCOpcode) {
3473 default: llvm_unreachable("Invalid integer condition!");
3474 case ISD::SETEQ: return X86::COND_E;
3475 case ISD::SETGT: return X86::COND_G;
3476 case ISD::SETGE: return X86::COND_GE;
3477 case ISD::SETLT: return X86::COND_L;
3478 case ISD::SETLE: return X86::COND_LE;
3479 case ISD::SETNE: return X86::COND_NE;
3480 case ISD::SETULT: return X86::COND_B;
3481 case ISD::SETUGT: return X86::COND_A;
3482 case ISD::SETULE: return X86::COND_BE;
3483 case ISD::SETUGE: return X86::COND_AE;
3487 // First determine if it is required or is profitable to flip the operands.
3489 // If LHS is a foldable load, but RHS is not, flip the condition.
3490 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3491 !ISD::isNON_EXTLoad(RHS.getNode())) {
3492 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3493 std::swap(LHS, RHS);
3496 switch (SetCCOpcode) {
3502 std::swap(LHS, RHS);
3506 // On a floating point condition, the flags are set as follows:
3508 // 0 | 0 | 0 | X > Y
3509 // 0 | 0 | 1 | X < Y
3510 // 1 | 0 | 0 | X == Y
3511 // 1 | 1 | 1 | unordered
3512 switch (SetCCOpcode) {
3513 default: llvm_unreachable("Condcode should be pre-legalized away");
3515 case ISD::SETEQ: return X86::COND_E;
3516 case ISD::SETOLT: // flipped
3518 case ISD::SETGT: return X86::COND_A;
3519 case ISD::SETOLE: // flipped
3521 case ISD::SETGE: return X86::COND_AE;
3522 case ISD::SETUGT: // flipped
3524 case ISD::SETLT: return X86::COND_B;
3525 case ISD::SETUGE: // flipped
3527 case ISD::SETLE: return X86::COND_BE;
3529 case ISD::SETNE: return X86::COND_NE;
3530 case ISD::SETUO: return X86::COND_P;
3531 case ISD::SETO: return X86::COND_NP;
3533 case ISD::SETUNE: return X86::COND_INVALID;
3537 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3538 /// code. Current x86 isa includes the following FP cmov instructions:
3539 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3540 static bool hasFPCMov(unsigned X86CC) {
3556 /// isFPImmLegal - Returns true if the target can instruction select the
3557 /// specified FP immediate natively. If false, the legalizer will
3558 /// materialize the FP immediate as a load from a constant pool.
3559 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3560 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3561 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3567 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3568 /// the specified range (L, H].
3569 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3570 return (Val < 0) || (Val >= Low && Val < Hi);
3573 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3574 /// specified value.
3575 static bool isUndefOrEqual(int Val, int CmpVal) {
3576 return (Val < 0 || Val == CmpVal);
3579 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3580 /// from position Pos and ending in Pos+Size, falls within the specified
3581 /// sequential range (L, L+Pos]. or is undef.
3582 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3583 unsigned Pos, unsigned Size, int Low) {
3584 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3585 if (!isUndefOrEqual(Mask[i], Low))
3590 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3591 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3592 /// the second operand.
3593 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3594 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3595 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3596 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3597 return (Mask[0] < 2 && Mask[1] < 2);
3601 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PSHUFHW.
3603 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3604 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3607 // Lower quadword copied in order or undef.
3608 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3611 // Upper quadword shuffled.
3612 for (unsigned i = 4; i != 8; ++i)
3613 if (!isUndefOrInRange(Mask[i], 4, 8))
3616 if (VT == MVT::v16i16) {
3617 // Lower quadword copied in order or undef.
3618 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3621 // Upper quadword shuffled.
3622 for (unsigned i = 12; i != 16; ++i)
3623 if (!isUndefOrInRange(Mask[i], 12, 16))
3630 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3631 /// is suitable for input to PSHUFLW.
3632 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3633 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3636 // Upper quadword copied in order.
3637 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3640 // Lower quadword shuffled.
3641 for (unsigned i = 0; i != 4; ++i)
3642 if (!isUndefOrInRange(Mask[i], 0, 4))
3645 if (VT == MVT::v16i16) {
3646 // Upper quadword copied in order.
3647 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3650 // Lower quadword shuffled.
3651 for (unsigned i = 8; i != 12; ++i)
3652 if (!isUndefOrInRange(Mask[i], 8, 12))
3659 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3660 /// is suitable for input to PALIGNR.
3661 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3662 const X86Subtarget *Subtarget) {
3663 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3664 (VT.is256BitVector() && !Subtarget->hasInt256()))
3667 unsigned NumElts = VT.getVectorNumElements();
3668 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3669 unsigned NumLaneElts = NumElts/NumLanes;
3671 // Do not handle 64-bit element shuffles with palignr.
3672 if (NumLaneElts == 2)
3675 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3677 for (i = 0; i != NumLaneElts; ++i) {
3682 // Lane is all undef, go to next lane
3683 if (i == NumLaneElts)
3686 int Start = Mask[i+l];
3688 // Make sure its in this lane in one of the sources
3689 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3690 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3693 // If not lane 0, then we must match lane 0
3694 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3697 // Correct second source to be contiguous with first source
3698 if (Start >= (int)NumElts)
3699 Start -= NumElts - NumLaneElts;
3701 // Make sure we're shifting in the right direction.
3702 if (Start <= (int)(i+l))
3707 // Check the rest of the elements to see if they are consecutive.
3708 for (++i; i != NumLaneElts; ++i) {
3709 int Idx = Mask[i+l];
3711 // Make sure its in this lane
3712 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3713 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3716 // If not lane 0, then we must match lane 0
3717 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3720 if (Idx >= (int)NumElts)
3721 Idx -= NumElts - NumLaneElts;
3723 if (!isUndefOrEqual(Idx, Start+i))
3732 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3733 /// the two vector operands have swapped position.
3734 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3735 unsigned NumElems) {
3736 for (unsigned i = 0; i != NumElems; ++i) {
3740 else if (idx < (int)NumElems)
3741 Mask[i] = idx + NumElems;
3743 Mask[i] = idx - NumElems;
3747 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3748 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3749 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3750 /// reverse of what x86 shuffles want.
3751 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3753 unsigned NumElems = VT.getVectorNumElements();
3754 unsigned NumLanes = VT.getSizeInBits()/128;
3755 unsigned NumLaneElems = NumElems/NumLanes;
3757 if (NumLaneElems != 2 && NumLaneElems != 4)
3760 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3761 bool symetricMaskRequired =
3762 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3764 // VSHUFPSY divides the resulting vector into 4 chunks.
3765 // The sources are also splitted into 4 chunks, and each destination
3766 // chunk must come from a different source chunk.
3768 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3769 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3771 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3772 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3774 // VSHUFPDY divides the resulting vector into 4 chunks.
3775 // The sources are also splitted into 4 chunks, and each destination
3776 // chunk must come from a different source chunk.
3778 // SRC1 => X3 X2 X1 X0
3779 // SRC2 => Y3 Y2 Y1 Y0
3781 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3783 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3784 unsigned HalfLaneElems = NumLaneElems/2;
3785 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3786 for (unsigned i = 0; i != NumLaneElems; ++i) {
3787 int Idx = Mask[i+l];
3788 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3789 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3791 // For VSHUFPSY, the mask of the second half must be the same as the
3792 // first but with the appropriate offsets. This works in the same way as
3793 // VPERMILPS works with masks.
3794 if (!symetricMaskRequired || Idx < 0)
3796 if (MaskVal[i] < 0) {
3797 MaskVal[i] = Idx - l;
3800 if ((signed)(Idx - l) != MaskVal[i])
3808 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3809 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3810 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3811 if (!VT.is128BitVector())
3814 unsigned NumElems = VT.getVectorNumElements();
3819 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3820 return isUndefOrEqual(Mask[0], 6) &&
3821 isUndefOrEqual(Mask[1], 7) &&
3822 isUndefOrEqual(Mask[2], 2) &&
3823 isUndefOrEqual(Mask[3], 3);
3826 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3827 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3829 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3830 if (!VT.is128BitVector())
3833 unsigned NumElems = VT.getVectorNumElements();
3838 return isUndefOrEqual(Mask[0], 2) &&
3839 isUndefOrEqual(Mask[1], 3) &&
3840 isUndefOrEqual(Mask[2], 2) &&
3841 isUndefOrEqual(Mask[3], 3);
3844 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3845 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3846 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3847 if (!VT.is128BitVector())
3850 unsigned NumElems = VT.getVectorNumElements();
3852 if (NumElems != 2 && NumElems != 4)
3855 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3856 if (!isUndefOrEqual(Mask[i], i + NumElems))
3859 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3860 if (!isUndefOrEqual(Mask[i], i))
3866 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3867 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3868 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3869 if (!VT.is128BitVector())
3872 unsigned NumElems = VT.getVectorNumElements();
3874 if (NumElems != 2 && NumElems != 4)
3877 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3878 if (!isUndefOrEqual(Mask[i], i))
3881 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3882 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3889 // Some special combinations that can be optimized.
3892 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3893 SelectionDAG &DAG) {
3894 MVT VT = SVOp->getSimpleValueType(0);
3897 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3900 ArrayRef<int> Mask = SVOp->getMask();
3902 // These are the special masks that may be optimized.
3903 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3904 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3905 bool MatchEvenMask = true;
3906 bool MatchOddMask = true;
3907 for (int i=0; i<8; ++i) {
3908 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3909 MatchEvenMask = false;
3910 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3911 MatchOddMask = false;
3914 if (!MatchEvenMask && !MatchOddMask)
3917 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3919 SDValue Op0 = SVOp->getOperand(0);
3920 SDValue Op1 = SVOp->getOperand(1);
3922 if (MatchEvenMask) {
3923 // Shift the second operand right to 32 bits.
3924 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3925 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3927 // Shift the first operand left to 32 bits.
3928 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3929 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3931 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3932 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3935 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3937 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3938 bool HasInt256, bool V2IsSplat = false) {
3940 assert(VT.getSizeInBits() >= 128 &&
3941 "Unsupported vector type for unpckl");
3943 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3945 unsigned NumOf256BitLanes;
3946 unsigned NumElts = VT.getVectorNumElements();
3947 if (VT.is256BitVector()) {
3948 if (NumElts != 4 && NumElts != 8 &&
3949 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3952 NumOf256BitLanes = 1;
3953 } else if (VT.is512BitVector()) {
3954 assert(VT.getScalarType().getSizeInBits() >= 32 &&
3955 "Unsupported vector type for unpckh");
3957 NumOf256BitLanes = 2;
3960 NumOf256BitLanes = 1;
3963 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3964 unsigned NumLaneElts = NumEltsInStride/NumLanes;
3966 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
3967 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
3968 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3969 int BitI = Mask[l256*NumEltsInStride+l+i];
3970 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
3971 if (!isUndefOrEqual(BitI, j+l256*NumElts))
3973 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
3975 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
3983 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3984 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3985 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3986 bool HasInt256, bool V2IsSplat = false) {
3987 assert(VT.getSizeInBits() >= 128 &&
3988 "Unsupported vector type for unpckh");
3990 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3992 unsigned NumOf256BitLanes;
3993 unsigned NumElts = VT.getVectorNumElements();
3994 if (VT.is256BitVector()) {
3995 if (NumElts != 4 && NumElts != 8 &&
3996 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3999 NumOf256BitLanes = 1;
4000 } else if (VT.is512BitVector()) {
4001 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4002 "Unsupported vector type for unpckh");
4004 NumOf256BitLanes = 2;
4007 NumOf256BitLanes = 1;
4010 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4011 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4013 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4014 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4015 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4016 int BitI = Mask[l256*NumEltsInStride+l+i];
4017 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4018 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4020 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4022 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4030 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4031 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4033 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4034 unsigned NumElts = VT.getVectorNumElements();
4035 bool Is256BitVec = VT.is256BitVector();
4037 if (VT.is512BitVector())
4039 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4040 "Unsupported vector type for unpckh");
4042 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4043 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4046 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4047 // FIXME: Need a better way to get rid of this, there's no latency difference
4048 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4049 // the former later. We should also remove the "_undef" special mask.
4050 if (NumElts == 4 && Is256BitVec)
4053 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4054 // independently on 128-bit lanes.
4055 unsigned NumLanes = VT.getSizeInBits()/128;
4056 unsigned NumLaneElts = NumElts/NumLanes;
4058 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4059 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4060 int BitI = Mask[l+i];
4061 int BitI1 = Mask[l+i+1];
4063 if (!isUndefOrEqual(BitI, j))
4065 if (!isUndefOrEqual(BitI1, j))
4073 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4074 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4076 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4077 unsigned NumElts = VT.getVectorNumElements();
4079 if (VT.is512BitVector())
4082 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4083 "Unsupported vector type for unpckh");
4085 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4086 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4089 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4090 // independently on 128-bit lanes.
4091 unsigned NumLanes = VT.getSizeInBits()/128;
4092 unsigned NumLaneElts = NumElts/NumLanes;
4094 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4095 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4096 int BitI = Mask[l+i];
4097 int BitI1 = Mask[l+i+1];
4098 if (!isUndefOrEqual(BitI, j))
4100 if (!isUndefOrEqual(BitI1, j))
4107 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4108 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4109 /// MOVSD, and MOVD, i.e. setting the lowest element.
4110 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4111 if (VT.getVectorElementType().getSizeInBits() < 32)
4113 if (!VT.is128BitVector())
4116 unsigned NumElts = VT.getVectorNumElements();
4118 if (!isUndefOrEqual(Mask[0], NumElts))
4121 for (unsigned i = 1; i != NumElts; ++i)
4122 if (!isUndefOrEqual(Mask[i], i))
4128 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4129 /// as permutations between 128-bit chunks or halves. As an example: this
4131 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4132 /// The first half comes from the second half of V1 and the second half from the
4133 /// the second half of V2.
4134 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4135 if (!HasFp256 || !VT.is256BitVector())
4138 // The shuffle result is divided into half A and half B. In total the two
4139 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4140 // B must come from C, D, E or F.
4141 unsigned HalfSize = VT.getVectorNumElements()/2;
4142 bool MatchA = false, MatchB = false;
4144 // Check if A comes from one of C, D, E, F.
4145 for (unsigned Half = 0; Half != 4; ++Half) {
4146 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4152 // Check if B comes from one of C, D, E, F.
4153 for (unsigned Half = 0; Half != 4; ++Half) {
4154 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4160 return MatchA && MatchB;
4163 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4164 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4165 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4166 MVT VT = SVOp->getSimpleValueType(0);
4168 unsigned HalfSize = VT.getVectorNumElements()/2;
4170 unsigned FstHalf = 0, SndHalf = 0;
4171 for (unsigned i = 0; i < HalfSize; ++i) {
4172 if (SVOp->getMaskElt(i) > 0) {
4173 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4177 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4178 if (SVOp->getMaskElt(i) > 0) {
4179 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4184 return (FstHalf | (SndHalf << 4));
4187 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4188 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4189 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4193 unsigned NumElts = VT.getVectorNumElements();
4195 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4196 for (unsigned i = 0; i != NumElts; ++i) {
4199 Imm8 |= Mask[i] << (i*2);
4204 unsigned LaneSize = 4;
4205 SmallVector<int, 4> MaskVal(LaneSize, -1);
4207 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4208 for (unsigned i = 0; i != LaneSize; ++i) {
4209 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4213 if (MaskVal[i] < 0) {
4214 MaskVal[i] = Mask[i+l] - l;
4215 Imm8 |= MaskVal[i] << (i*2);
4218 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4225 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4226 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4227 /// Note that VPERMIL mask matching is different depending whether theunderlying
4228 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4229 /// to the same elements of the low, but to the higher half of the source.
4230 /// In VPERMILPD the two lanes could be shuffled independently of each other
4231 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4232 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4233 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4234 if (VT.getSizeInBits() < 256 || EltSize < 32)
4236 bool symetricMaskRequired = (EltSize == 32);
4237 unsigned NumElts = VT.getVectorNumElements();
4239 unsigned NumLanes = VT.getSizeInBits()/128;
4240 unsigned LaneSize = NumElts/NumLanes;
4241 // 2 or 4 elements in one lane
4243 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4244 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4245 for (unsigned i = 0; i != LaneSize; ++i) {
4246 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4248 if (symetricMaskRequired) {
4249 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4250 ExpectedMaskVal[i] = Mask[i+l] - l;
4253 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4261 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4262 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4263 /// element of vector 2 and the other elements to come from vector 1 in order.
4264 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4265 bool V2IsSplat = false, bool V2IsUndef = false) {
4266 if (!VT.is128BitVector())
4269 unsigned NumOps = VT.getVectorNumElements();
4270 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4273 if (!isUndefOrEqual(Mask[0], 0))
4276 for (unsigned i = 1; i != NumOps; ++i)
4277 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4278 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4279 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4285 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4286 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4287 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4288 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4289 const X86Subtarget *Subtarget) {
4290 if (!Subtarget->hasSSE3())
4293 unsigned NumElems = VT.getVectorNumElements();
4295 if ((VT.is128BitVector() && NumElems != 4) ||
4296 (VT.is256BitVector() && NumElems != 8) ||
4297 (VT.is512BitVector() && NumElems != 16))
4300 // "i+1" is the value the indexed mask element must have
4301 for (unsigned i = 0; i != NumElems; i += 2)
4302 if (!isUndefOrEqual(Mask[i], i+1) ||
4303 !isUndefOrEqual(Mask[i+1], i+1))
4309 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4310 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4311 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4312 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4313 const X86Subtarget *Subtarget) {
4314 if (!Subtarget->hasSSE3())
4317 unsigned NumElems = VT.getVectorNumElements();
4319 if ((VT.is128BitVector() && NumElems != 4) ||
4320 (VT.is256BitVector() && NumElems != 8) ||
4321 (VT.is512BitVector() && NumElems != 16))
4324 // "i" is the value the indexed mask element must have
4325 for (unsigned i = 0; i != NumElems; i += 2)
4326 if (!isUndefOrEqual(Mask[i], i) ||
4327 !isUndefOrEqual(Mask[i+1], i))
4333 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4334 /// specifies a shuffle of elements that is suitable for input to 256-bit
4335 /// version of MOVDDUP.
4336 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4337 if (!HasFp256 || !VT.is256BitVector())
4340 unsigned NumElts = VT.getVectorNumElements();
4344 for (unsigned i = 0; i != NumElts/2; ++i)
4345 if (!isUndefOrEqual(Mask[i], 0))
4347 for (unsigned i = NumElts/2; i != NumElts; ++i)
4348 if (!isUndefOrEqual(Mask[i], NumElts/2))
4353 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4354 /// specifies a shuffle of elements that is suitable for input to 128-bit
4355 /// version of MOVDDUP.
4356 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4357 if (!VT.is128BitVector())
4360 unsigned e = VT.getVectorNumElements() / 2;
4361 for (unsigned i = 0; i != e; ++i)
4362 if (!isUndefOrEqual(Mask[i], i))
4364 for (unsigned i = 0; i != e; ++i)
4365 if (!isUndefOrEqual(Mask[e+i], i))
4370 /// isVEXTRACTIndex - Return true if the specified
4371 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4372 /// suitable for instruction that extract 128 or 256 bit vectors
4373 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4374 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4375 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4378 // The index should be aligned on a vecWidth-bit boundary.
4380 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4382 MVT VT = N->getSimpleValueType(0);
4383 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4384 bool Result = (Index * ElSize) % vecWidth == 0;
4389 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4390 /// operand specifies a subvector insert that is suitable for input to
4391 /// insertion of 128 or 256-bit subvectors
4392 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4393 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4394 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4396 // The index should be aligned on a vecWidth-bit boundary.
4398 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4400 MVT VT = N->getSimpleValueType(0);
4401 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4402 bool Result = (Index * ElSize) % vecWidth == 0;
4407 bool X86::isVINSERT128Index(SDNode *N) {
4408 return isVINSERTIndex(N, 128);
4411 bool X86::isVINSERT256Index(SDNode *N) {
4412 return isVINSERTIndex(N, 256);
4415 bool X86::isVEXTRACT128Index(SDNode *N) {
4416 return isVEXTRACTIndex(N, 128);
4419 bool X86::isVEXTRACT256Index(SDNode *N) {
4420 return isVEXTRACTIndex(N, 256);
4423 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4424 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4425 /// Handles 128-bit and 256-bit.
4426 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4427 MVT VT = N->getSimpleValueType(0);
4429 assert((VT.getSizeInBits() >= 128) &&
4430 "Unsupported vector type for PSHUF/SHUFP");
4432 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4433 // independently on 128-bit lanes.
4434 unsigned NumElts = VT.getVectorNumElements();
4435 unsigned NumLanes = VT.getSizeInBits()/128;
4436 unsigned NumLaneElts = NumElts/NumLanes;
4438 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4439 "Only supports 2, 4 or 8 elements per lane");
4441 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4443 for (unsigned i = 0; i != NumElts; ++i) {
4444 int Elt = N->getMaskElt(i);
4445 if (Elt < 0) continue;
4446 Elt &= NumLaneElts - 1;
4447 unsigned ShAmt = (i << Shift) % 8;
4448 Mask |= Elt << ShAmt;
4454 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4455 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4456 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4457 MVT VT = N->getSimpleValueType(0);
4459 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4460 "Unsupported vector type for PSHUFHW");
4462 unsigned NumElts = VT.getVectorNumElements();
4465 for (unsigned l = 0; l != NumElts; l += 8) {
4466 // 8 nodes per lane, but we only care about the last 4.
4467 for (unsigned i = 0; i < 4; ++i) {
4468 int Elt = N->getMaskElt(l+i+4);
4469 if (Elt < 0) continue;
4470 Elt &= 0x3; // only 2-bits.
4471 Mask |= Elt << (i * 2);
4478 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4479 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4480 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4481 MVT VT = N->getSimpleValueType(0);
4483 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4484 "Unsupported vector type for PSHUFHW");
4486 unsigned NumElts = VT.getVectorNumElements();
4489 for (unsigned l = 0; l != NumElts; l += 8) {
4490 // 8 nodes per lane, but we only care about the first 4.
4491 for (unsigned i = 0; i < 4; ++i) {
4492 int Elt = N->getMaskElt(l+i);
4493 if (Elt < 0) continue;
4494 Elt &= 0x3; // only 2-bits
4495 Mask |= Elt << (i * 2);
4502 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4503 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4504 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4505 MVT VT = SVOp->getSimpleValueType(0);
4506 unsigned EltSize = VT.is512BitVector() ? 1 :
4507 VT.getVectorElementType().getSizeInBits() >> 3;
4509 unsigned NumElts = VT.getVectorNumElements();
4510 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4511 unsigned NumLaneElts = NumElts/NumLanes;
4515 for (i = 0; i != NumElts; ++i) {
4516 Val = SVOp->getMaskElt(i);
4520 if (Val >= (int)NumElts)
4521 Val -= NumElts - NumLaneElts;
4523 assert(Val - i > 0 && "PALIGNR imm should be positive");
4524 return (Val - i) * EltSize;
4527 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4528 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4529 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4530 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4533 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4535 MVT VecVT = N->getOperand(0).getSimpleValueType();
4536 MVT ElVT = VecVT.getVectorElementType();
4538 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4539 return Index / NumElemsPerChunk;
4542 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4543 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4544 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4545 llvm_unreachable("Illegal insert subvector for VINSERT");
4548 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4550 MVT VecVT = N->getSimpleValueType(0);
4551 MVT ElVT = VecVT.getVectorElementType();
4553 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4554 return Index / NumElemsPerChunk;
4557 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4558 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4559 /// and VINSERTI128 instructions.
4560 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4561 return getExtractVEXTRACTImmediate(N, 128);
4564 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4565 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4566 /// and VINSERTI64x4 instructions.
4567 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4568 return getExtractVEXTRACTImmediate(N, 256);
4571 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4572 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4573 /// and VINSERTI128 instructions.
4574 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4575 return getInsertVINSERTImmediate(N, 128);
4578 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4579 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4580 /// and VINSERTI64x4 instructions.
4581 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4582 return getInsertVINSERTImmediate(N, 256);
4585 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4587 bool X86::isZeroNode(SDValue Elt) {
4588 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4589 return CN->isNullValue();
4590 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4591 return CFP->getValueAPF().isPosZero();
4595 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4596 /// their permute mask.
4597 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4598 SelectionDAG &DAG) {
4599 MVT VT = SVOp->getSimpleValueType(0);
4600 unsigned NumElems = VT.getVectorNumElements();
4601 SmallVector<int, 8> MaskVec;
4603 for (unsigned i = 0; i != NumElems; ++i) {
4604 int Idx = SVOp->getMaskElt(i);
4606 if (Idx < (int)NumElems)
4611 MaskVec.push_back(Idx);
4613 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4614 SVOp->getOperand(0), &MaskVec[0]);
4617 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4618 /// match movhlps. The lower half elements should come from upper half of
4619 /// V1 (and in order), and the upper half elements should come from the upper
4620 /// half of V2 (and in order).
4621 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4622 if (!VT.is128BitVector())
4624 if (VT.getVectorNumElements() != 4)
4626 for (unsigned i = 0, e = 2; i != e; ++i)
4627 if (!isUndefOrEqual(Mask[i], i+2))
4629 for (unsigned i = 2; i != 4; ++i)
4630 if (!isUndefOrEqual(Mask[i], i+4))
4635 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4636 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4638 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4639 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4641 N = N->getOperand(0).getNode();
4642 if (!ISD::isNON_EXTLoad(N))
4645 *LD = cast<LoadSDNode>(N);
4649 // Test whether the given value is a vector value which will be legalized
4651 static bool WillBeConstantPoolLoad(SDNode *N) {
4652 if (N->getOpcode() != ISD::BUILD_VECTOR)
4655 // Check for any non-constant elements.
4656 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4657 switch (N->getOperand(i).getNode()->getOpcode()) {
4659 case ISD::ConstantFP:
4666 // Vectors of all-zeros and all-ones are materialized with special
4667 // instructions rather than being loaded.
4668 return !ISD::isBuildVectorAllZeros(N) &&
4669 !ISD::isBuildVectorAllOnes(N);
4672 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4673 /// match movlp{s|d}. The lower half elements should come from lower half of
4674 /// V1 (and in order), and the upper half elements should come from the upper
4675 /// half of V2 (and in order). And since V1 will become the source of the
4676 /// MOVLP, it must be either a vector load or a scalar load to vector.
4677 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4678 ArrayRef<int> Mask, MVT VT) {
4679 if (!VT.is128BitVector())
4682 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4684 // Is V2 is a vector load, don't do this transformation. We will try to use
4685 // load folding shufps op.
4686 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4689 unsigned NumElems = VT.getVectorNumElements();
4691 if (NumElems != 2 && NumElems != 4)
4693 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4694 if (!isUndefOrEqual(Mask[i], i))
4696 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4697 if (!isUndefOrEqual(Mask[i], i+NumElems))
4702 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4704 static bool isSplatVector(SDNode *N) {
4705 if (N->getOpcode() != ISD::BUILD_VECTOR)
4708 SDValue SplatValue = N->getOperand(0);
4709 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4710 if (N->getOperand(i) != SplatValue)
4715 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4716 /// to an zero vector.
4717 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4718 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4719 SDValue V1 = N->getOperand(0);
4720 SDValue V2 = N->getOperand(1);
4721 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4722 for (unsigned i = 0; i != NumElems; ++i) {
4723 int Idx = N->getMaskElt(i);
4724 if (Idx >= (int)NumElems) {
4725 unsigned Opc = V2.getOpcode();
4726 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4728 if (Opc != ISD::BUILD_VECTOR ||
4729 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4731 } else if (Idx >= 0) {
4732 unsigned Opc = V1.getOpcode();
4733 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4735 if (Opc != ISD::BUILD_VECTOR ||
4736 !X86::isZeroNode(V1.getOperand(Idx)))
4743 /// getZeroVector - Returns a vector of specified type with all zero elements.
4745 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4746 SelectionDAG &DAG, SDLoc dl) {
4747 assert(VT.isVector() && "Expected a vector type");
4749 // Always build SSE zero vectors as <4 x i32> bitcasted
4750 // to their dest type. This ensures they get CSE'd.
4752 if (VT.is128BitVector()) { // SSE
4753 if (Subtarget->hasSSE2()) { // SSE2
4754 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4755 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4757 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4758 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4760 } else if (VT.is256BitVector()) { // AVX
4761 if (Subtarget->hasInt256()) { // AVX2
4762 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4763 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4764 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4765 array_lengthof(Ops));
4767 // 256-bit logic and arithmetic instructions in AVX are all
4768 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4769 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4770 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4771 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4772 array_lengthof(Ops));
4774 } else if (VT.is512BitVector()) { // AVX-512
4775 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4776 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4777 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4778 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4780 llvm_unreachable("Unexpected vector type");
4782 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4785 /// getOnesVector - Returns a vector of specified type with all bits set.
4786 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4787 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4788 /// Then bitcast to their original type, ensuring they get CSE'd.
4789 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4791 assert(VT.isVector() && "Expected a vector type");
4793 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4795 if (VT.is256BitVector()) {
4796 if (HasInt256) { // AVX2
4797 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4798 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4799 array_lengthof(Ops));
4801 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4802 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4804 } else if (VT.is128BitVector()) {
4805 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4807 llvm_unreachable("Unexpected vector type");
4809 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4812 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4813 /// that point to V2 points to its first element.
4814 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4815 for (unsigned i = 0; i != NumElems; ++i) {
4816 if (Mask[i] > (int)NumElems) {
4822 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4823 /// operation of specified width.
4824 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4826 unsigned NumElems = VT.getVectorNumElements();
4827 SmallVector<int, 8> Mask;
4828 Mask.push_back(NumElems);
4829 for (unsigned i = 1; i != NumElems; ++i)
4831 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4834 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4835 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4837 unsigned NumElems = VT.getVectorNumElements();
4838 SmallVector<int, 8> Mask;
4839 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4841 Mask.push_back(i + NumElems);
4843 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4846 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4847 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4849 unsigned NumElems = VT.getVectorNumElements();
4850 SmallVector<int, 8> Mask;
4851 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4852 Mask.push_back(i + Half);
4853 Mask.push_back(i + NumElems + Half);
4855 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4858 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4859 // a generic shuffle instruction because the target has no such instructions.
4860 // Generate shuffles which repeat i16 and i8 several times until they can be
4861 // represented by v4f32 and then be manipulated by target suported shuffles.
4862 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4863 MVT VT = V.getSimpleValueType();
4864 int NumElems = VT.getVectorNumElements();
4867 while (NumElems > 4) {
4868 if (EltNo < NumElems/2) {
4869 V = getUnpackl(DAG, dl, VT, V, V);
4871 V = getUnpackh(DAG, dl, VT, V, V);
4872 EltNo -= NumElems/2;
4879 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4880 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4881 MVT VT = V.getSimpleValueType();
4884 if (VT.is128BitVector()) {
4885 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4886 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4887 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4889 } else if (VT.is256BitVector()) {
4890 // To use VPERMILPS to splat scalars, the second half of indicies must
4891 // refer to the higher part, which is a duplication of the lower one,
4892 // because VPERMILPS can only handle in-lane permutations.
4893 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4894 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4896 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4897 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4900 llvm_unreachable("Vector size not supported");
4902 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4905 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4906 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4907 MVT SrcVT = SV->getSimpleValueType(0);
4908 SDValue V1 = SV->getOperand(0);
4911 int EltNo = SV->getSplatIndex();
4912 int NumElems = SrcVT.getVectorNumElements();
4913 bool Is256BitVec = SrcVT.is256BitVector();
4915 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4916 "Unknown how to promote splat for type");
4918 // Extract the 128-bit part containing the splat element and update
4919 // the splat element index when it refers to the higher register.
4921 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4922 if (EltNo >= NumElems/2)
4923 EltNo -= NumElems/2;
4926 // All i16 and i8 vector types can't be used directly by a generic shuffle
4927 // instruction because the target has no such instruction. Generate shuffles
4928 // which repeat i16 and i8 several times until they fit in i32, and then can
4929 // be manipulated by target suported shuffles.
4930 MVT EltVT = SrcVT.getVectorElementType();
4931 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4932 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4934 // Recreate the 256-bit vector and place the same 128-bit vector
4935 // into the low and high part. This is necessary because we want
4936 // to use VPERM* to shuffle the vectors
4938 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4941 return getLegalSplat(DAG, V1, EltNo);
4944 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4945 /// vector of zero or undef vector. This produces a shuffle where the low
4946 /// element of V2 is swizzled into the zero/undef vector, landing at element
4947 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4948 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4950 const X86Subtarget *Subtarget,
4951 SelectionDAG &DAG) {
4952 MVT VT = V2.getSimpleValueType();
4954 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4955 unsigned NumElems = VT.getVectorNumElements();
4956 SmallVector<int, 16> MaskVec;
4957 for (unsigned i = 0; i != NumElems; ++i)
4958 // If this is the insertion idx, put the low elt of V2 here.
4959 MaskVec.push_back(i == Idx ? NumElems : i);
4960 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4963 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4964 /// target specific opcode. Returns true if the Mask could be calculated.
4965 /// Sets IsUnary to true if only uses one source.
4966 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4967 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4968 unsigned NumElems = VT.getVectorNumElements();
4972 switch(N->getOpcode()) {
4974 ImmN = N->getOperand(N->getNumOperands()-1);
4975 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4977 case X86ISD::UNPCKH:
4978 DecodeUNPCKHMask(VT, Mask);
4980 case X86ISD::UNPCKL:
4981 DecodeUNPCKLMask(VT, Mask);
4983 case X86ISD::MOVHLPS:
4984 DecodeMOVHLPSMask(NumElems, Mask);
4986 case X86ISD::MOVLHPS:
4987 DecodeMOVLHPSMask(NumElems, Mask);
4989 case X86ISD::PALIGNR:
4990 ImmN = N->getOperand(N->getNumOperands()-1);
4991 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4993 case X86ISD::PSHUFD:
4994 case X86ISD::VPERMILP:
4995 ImmN = N->getOperand(N->getNumOperands()-1);
4996 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4999 case X86ISD::PSHUFHW:
5000 ImmN = N->getOperand(N->getNumOperands()-1);
5001 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5004 case X86ISD::PSHUFLW:
5005 ImmN = N->getOperand(N->getNumOperands()-1);
5006 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5009 case X86ISD::VPERMI:
5010 ImmN = N->getOperand(N->getNumOperands()-1);
5011 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5015 case X86ISD::MOVSD: {
5016 // The index 0 always comes from the first element of the second source,
5017 // this is why MOVSS and MOVSD are used in the first place. The other
5018 // elements come from the other positions of the first source vector
5019 Mask.push_back(NumElems);
5020 for (unsigned i = 1; i != NumElems; ++i) {
5025 case X86ISD::VPERM2X128:
5026 ImmN = N->getOperand(N->getNumOperands()-1);
5027 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5028 if (Mask.empty()) return false;
5030 case X86ISD::MOVDDUP:
5031 case X86ISD::MOVLHPD:
5032 case X86ISD::MOVLPD:
5033 case X86ISD::MOVLPS:
5034 case X86ISD::MOVSHDUP:
5035 case X86ISD::MOVSLDUP:
5036 // Not yet implemented
5038 default: llvm_unreachable("unknown target shuffle node");
5044 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5045 /// element of the result of the vector shuffle.
5046 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5049 return SDValue(); // Limit search depth.
5051 SDValue V = SDValue(N, 0);
5052 EVT VT = V.getValueType();
5053 unsigned Opcode = V.getOpcode();
5055 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5056 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5057 int Elt = SV->getMaskElt(Index);
5060 return DAG.getUNDEF(VT.getVectorElementType());
5062 unsigned NumElems = VT.getVectorNumElements();
5063 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5064 : SV->getOperand(1);
5065 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5068 // Recurse into target specific vector shuffles to find scalars.
5069 if (isTargetShuffle(Opcode)) {
5070 MVT ShufVT = V.getSimpleValueType();
5071 unsigned NumElems = ShufVT.getVectorNumElements();
5072 SmallVector<int, 16> ShuffleMask;
5075 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5078 int Elt = ShuffleMask[Index];
5080 return DAG.getUNDEF(ShufVT.getVectorElementType());
5082 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5084 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5088 // Actual nodes that may contain scalar elements
5089 if (Opcode == ISD::BITCAST) {
5090 V = V.getOperand(0);
5091 EVT SrcVT = V.getValueType();
5092 unsigned NumElems = VT.getVectorNumElements();
5094 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5098 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5099 return (Index == 0) ? V.getOperand(0)
5100 : DAG.getUNDEF(VT.getVectorElementType());
5102 if (V.getOpcode() == ISD::BUILD_VECTOR)
5103 return V.getOperand(Index);
5108 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5109 /// shuffle operation which come from a consecutively from a zero. The
5110 /// search can start in two different directions, from left or right.
5111 /// We count undefs as zeros until PreferredNum is reached.
5112 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5113 unsigned NumElems, bool ZerosFromLeft,
5115 unsigned PreferredNum = -1U) {
5116 unsigned NumZeros = 0;
5117 for (unsigned i = 0; i != NumElems; ++i) {
5118 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5119 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5123 if (X86::isZeroNode(Elt))
5125 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5126 NumZeros = std::min(NumZeros + 1, PreferredNum);
5134 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5135 /// correspond consecutively to elements from one of the vector operands,
5136 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5138 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5139 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5140 unsigned NumElems, unsigned &OpNum) {
5141 bool SeenV1 = false;
5142 bool SeenV2 = false;
5144 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5145 int Idx = SVOp->getMaskElt(i);
5146 // Ignore undef indicies
5150 if (Idx < (int)NumElems)
5155 // Only accept consecutive elements from the same vector
5156 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5160 OpNum = SeenV1 ? 0 : 1;
5164 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5165 /// logical left shift of a vector.
5166 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5167 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5169 SVOp->getSimpleValueType(0).getVectorNumElements();
5170 unsigned NumZeros = getNumOfConsecutiveZeros(
5171 SVOp, NumElems, false /* check zeros from right */, DAG,
5172 SVOp->getMaskElt(0));
5178 // Considering the elements in the mask that are not consecutive zeros,
5179 // check if they consecutively come from only one of the source vectors.
5181 // V1 = {X, A, B, C} 0
5183 // vector_shuffle V1, V2 <1, 2, 3, X>
5185 if (!isShuffleMaskConsecutive(SVOp,
5186 0, // Mask Start Index
5187 NumElems-NumZeros, // Mask End Index(exclusive)
5188 NumZeros, // Where to start looking in the src vector
5189 NumElems, // Number of elements in vector
5190 OpSrc)) // Which source operand ?
5195 ShVal = SVOp->getOperand(OpSrc);
5199 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5200 /// logical left shift of a vector.
5201 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5202 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5204 SVOp->getSimpleValueType(0).getVectorNumElements();
5205 unsigned NumZeros = getNumOfConsecutiveZeros(
5206 SVOp, NumElems, true /* check zeros from left */, DAG,
5207 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5213 // Considering the elements in the mask that are not consecutive zeros,
5214 // check if they consecutively come from only one of the source vectors.
5216 // 0 { A, B, X, X } = V2
5218 // vector_shuffle V1, V2 <X, X, 4, 5>
5220 if (!isShuffleMaskConsecutive(SVOp,
5221 NumZeros, // Mask Start Index
5222 NumElems, // Mask End Index(exclusive)
5223 0, // Where to start looking in the src vector
5224 NumElems, // Number of elements in vector
5225 OpSrc)) // Which source operand ?
5230 ShVal = SVOp->getOperand(OpSrc);
5234 /// isVectorShift - Returns true if the shuffle can be implemented as a
5235 /// logical left or right shift of a vector.
5236 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5237 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5238 // Although the logic below support any bitwidth size, there are no
5239 // shift instructions which handle more than 128-bit vectors.
5240 if (!SVOp->getSimpleValueType(0).is128BitVector())
5243 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5244 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5250 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5252 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5253 unsigned NumNonZero, unsigned NumZero,
5255 const X86Subtarget* Subtarget,
5256 const TargetLowering &TLI) {
5263 for (unsigned i = 0; i < 16; ++i) {
5264 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5265 if (ThisIsNonZero && First) {
5267 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5269 V = DAG.getUNDEF(MVT::v8i16);
5274 SDValue ThisElt(0, 0), LastElt(0, 0);
5275 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5276 if (LastIsNonZero) {
5277 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5278 MVT::i16, Op.getOperand(i-1));
5280 if (ThisIsNonZero) {
5281 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5282 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5283 ThisElt, DAG.getConstant(8, MVT::i8));
5285 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5289 if (ThisElt.getNode())
5290 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5291 DAG.getIntPtrConstant(i/2));
5295 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5298 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5300 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5301 unsigned NumNonZero, unsigned NumZero,
5303 const X86Subtarget* Subtarget,
5304 const TargetLowering &TLI) {
5311 for (unsigned i = 0; i < 8; ++i) {
5312 bool isNonZero = (NonZeros & (1 << i)) != 0;
5316 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5318 V = DAG.getUNDEF(MVT::v8i16);
5321 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5322 MVT::v8i16, V, Op.getOperand(i),
5323 DAG.getIntPtrConstant(i));
5330 /// getVShift - Return a vector logical shift node.
5332 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5333 unsigned NumBits, SelectionDAG &DAG,
5334 const TargetLowering &TLI, SDLoc dl) {
5335 assert(VT.is128BitVector() && "Unknown type for VShift");
5336 EVT ShVT = MVT::v2i64;
5337 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5338 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5339 return DAG.getNode(ISD::BITCAST, dl, VT,
5340 DAG.getNode(Opc, dl, ShVT, SrcOp,
5341 DAG.getConstant(NumBits,
5342 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5346 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5348 // Check if the scalar load can be widened into a vector load. And if
5349 // the address is "base + cst" see if the cst can be "absorbed" into
5350 // the shuffle mask.
5351 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5352 SDValue Ptr = LD->getBasePtr();
5353 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5355 EVT PVT = LD->getValueType(0);
5356 if (PVT != MVT::i32 && PVT != MVT::f32)
5361 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5362 FI = FINode->getIndex();
5364 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5365 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5366 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5367 Offset = Ptr.getConstantOperandVal(1);
5368 Ptr = Ptr.getOperand(0);
5373 // FIXME: 256-bit vector instructions don't require a strict alignment,
5374 // improve this code to support it better.
5375 unsigned RequiredAlign = VT.getSizeInBits()/8;
5376 SDValue Chain = LD->getChain();
5377 // Make sure the stack object alignment is at least 16 or 32.
5378 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5379 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5380 if (MFI->isFixedObjectIndex(FI)) {
5381 // Can't change the alignment. FIXME: It's possible to compute
5382 // the exact stack offset and reference FI + adjust offset instead.
5383 // If someone *really* cares about this. That's the way to implement it.
5386 MFI->setObjectAlignment(FI, RequiredAlign);
5390 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5391 // Ptr + (Offset & ~15).
5394 if ((Offset % RequiredAlign) & 3)
5396 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5398 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5399 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5401 int EltNo = (Offset - StartOffset) >> 2;
5402 unsigned NumElems = VT.getVectorNumElements();
5404 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5405 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5406 LD->getPointerInfo().getWithOffset(StartOffset),
5407 false, false, false, 0);
5409 SmallVector<int, 8> Mask;
5410 for (unsigned i = 0; i != NumElems; ++i)
5411 Mask.push_back(EltNo);
5413 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5419 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5420 /// vector of type 'VT', see if the elements can be replaced by a single large
5421 /// load which has the same value as a build_vector whose operands are 'elts'.
5423 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5425 /// FIXME: we'd also like to handle the case where the last elements are zero
5426 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5427 /// There's even a handy isZeroNode for that purpose.
5428 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5429 SDLoc &DL, SelectionDAG &DAG,
5430 bool isAfterLegalize) {
5431 EVT EltVT = VT.getVectorElementType();
5432 unsigned NumElems = Elts.size();
5434 LoadSDNode *LDBase = NULL;
5435 unsigned LastLoadedElt = -1U;
5437 // For each element in the initializer, see if we've found a load or an undef.
5438 // If we don't find an initial load element, or later load elements are
5439 // non-consecutive, bail out.
5440 for (unsigned i = 0; i < NumElems; ++i) {
5441 SDValue Elt = Elts[i];
5443 if (!Elt.getNode() ||
5444 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5447 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5449 LDBase = cast<LoadSDNode>(Elt.getNode());
5453 if (Elt.getOpcode() == ISD::UNDEF)
5456 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5457 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5462 // If we have found an entire vector of loads and undefs, then return a large
5463 // load of the entire vector width starting at the base pointer. If we found
5464 // consecutive loads for the low half, generate a vzext_load node.
5465 if (LastLoadedElt == NumElems - 1) {
5467 if (isAfterLegalize &&
5468 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5471 SDValue NewLd = SDValue();
5473 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5474 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5475 LDBase->getPointerInfo(),
5476 LDBase->isVolatile(), LDBase->isNonTemporal(),
5477 LDBase->isInvariant(), 0);
5478 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5479 LDBase->getPointerInfo(),
5480 LDBase->isVolatile(), LDBase->isNonTemporal(),
5481 LDBase->isInvariant(), LDBase->getAlignment());
5483 if (LDBase->hasAnyUseOfValue(1)) {
5484 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5486 SDValue(NewLd.getNode(), 1));
5487 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5488 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5489 SDValue(NewLd.getNode(), 1));
5494 if (NumElems == 4 && LastLoadedElt == 1 &&
5495 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5496 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5497 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5499 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5500 array_lengthof(Ops), MVT::i64,
5501 LDBase->getPointerInfo(),
5502 LDBase->getAlignment(),
5503 false/*isVolatile*/, true/*ReadMem*/,
5506 // Make sure the newly-created LOAD is in the same position as LDBase in
5507 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5508 // update uses of LDBase's output chain to use the TokenFactor.
5509 if (LDBase->hasAnyUseOfValue(1)) {
5510 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5511 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5512 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5513 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5514 SDValue(ResNode.getNode(), 1));
5517 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5522 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5523 /// to generate a splat value for the following cases:
5524 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5525 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5526 /// a scalar load, or a constant.
5527 /// The VBROADCAST node is returned when a pattern is found,
5528 /// or SDValue() otherwise.
5529 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5530 SelectionDAG &DAG) {
5531 if (!Subtarget->hasFp256())
5534 MVT VT = Op.getSimpleValueType();
5537 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5538 "Unsupported vector type for broadcast.");
5543 switch (Op.getOpcode()) {
5545 // Unknown pattern found.
5548 case ISD::BUILD_VECTOR: {
5549 // The BUILD_VECTOR node must be a splat.
5550 if (!isSplatVector(Op.getNode()))
5553 Ld = Op.getOperand(0);
5554 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5555 Ld.getOpcode() == ISD::ConstantFP);
5557 // The suspected load node has several users. Make sure that all
5558 // of its users are from the BUILD_VECTOR node.
5559 // Constants may have multiple users.
5560 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5565 case ISD::VECTOR_SHUFFLE: {
5566 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5568 // Shuffles must have a splat mask where the first element is
5570 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5573 SDValue Sc = Op.getOperand(0);
5574 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5575 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5577 if (!Subtarget->hasInt256())
5580 // Use the register form of the broadcast instruction available on AVX2.
5581 if (VT.getSizeInBits() >= 256)
5582 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5583 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5586 Ld = Sc.getOperand(0);
5587 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5588 Ld.getOpcode() == ISD::ConstantFP);
5590 // The scalar_to_vector node and the suspected
5591 // load node must have exactly one user.
5592 // Constants may have multiple users.
5594 // AVX-512 has register version of the broadcast
5595 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5596 Ld.getValueType().getSizeInBits() >= 32;
5597 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5604 bool IsGE256 = (VT.getSizeInBits() >= 256);
5606 // Handle the broadcasting a single constant scalar from the constant pool
5607 // into a vector. On Sandybridge it is still better to load a constant vector
5608 // from the constant pool and not to broadcast it from a scalar.
5609 if (ConstSplatVal && Subtarget->hasInt256()) {
5610 EVT CVT = Ld.getValueType();
5611 assert(!CVT.isVector() && "Must not broadcast a vector type");
5612 unsigned ScalarSize = CVT.getSizeInBits();
5614 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5615 const Constant *C = 0;
5616 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5617 C = CI->getConstantIntValue();
5618 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5619 C = CF->getConstantFPValue();
5621 assert(C && "Invalid constant type");
5623 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5624 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5625 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5626 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5627 MachinePointerInfo::getConstantPool(),
5628 false, false, false, Alignment);
5630 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5634 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5635 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5637 // Handle AVX2 in-register broadcasts.
5638 if (!IsLoad && Subtarget->hasInt256() &&
5639 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5640 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5642 // The scalar source must be a normal load.
5646 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5647 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5649 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5650 // double since there is no vbroadcastsd xmm
5651 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5652 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5653 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5656 // Unsupported broadcast.
5660 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5661 MVT VT = Op.getSimpleValueType();
5663 // Skip if insert_vec_elt is not supported.
5664 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5665 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5669 unsigned NumElems = Op.getNumOperands();
5673 SmallVector<unsigned, 4> InsertIndices;
5674 SmallVector<int, 8> Mask(NumElems, -1);
5676 for (unsigned i = 0; i != NumElems; ++i) {
5677 unsigned Opc = Op.getOperand(i).getOpcode();
5679 if (Opc == ISD::UNDEF)
5682 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5683 // Quit if more than 1 elements need inserting.
5684 if (InsertIndices.size() > 1)
5687 InsertIndices.push_back(i);
5691 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5692 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5694 // Quit if extracted from vector of different type.
5695 if (ExtractedFromVec.getValueType() != VT)
5698 // Quit if non-constant index.
5699 if (!isa<ConstantSDNode>(ExtIdx))
5702 if (VecIn1.getNode() == 0)
5703 VecIn1 = ExtractedFromVec;
5704 else if (VecIn1 != ExtractedFromVec) {
5705 if (VecIn2.getNode() == 0)
5706 VecIn2 = ExtractedFromVec;
5707 else if (VecIn2 != ExtractedFromVec)
5708 // Quit if more than 2 vectors to shuffle
5712 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5714 if (ExtractedFromVec == VecIn1)
5716 else if (ExtractedFromVec == VecIn2)
5717 Mask[i] = Idx + NumElems;
5720 if (VecIn1.getNode() == 0)
5723 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5724 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5725 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5726 unsigned Idx = InsertIndices[i];
5727 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5728 DAG.getIntPtrConstant(Idx));
5734 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5736 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5738 MVT VT = Op.getSimpleValueType();
5739 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5740 "Unexpected type in LowerBUILD_VECTORvXi1!");
5743 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5744 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5745 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5746 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5747 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5748 Ops, VT.getVectorNumElements());
5751 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5752 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5753 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5754 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5755 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5756 Ops, VT.getVectorNumElements());
5759 bool AllContants = true;
5760 uint64_t Immediate = 0;
5761 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5762 SDValue In = Op.getOperand(idx);
5763 if (In.getOpcode() == ISD::UNDEF)
5765 if (!isa<ConstantSDNode>(In)) {
5766 AllContants = false;
5769 if (cast<ConstantSDNode>(In)->getZExtValue())
5770 Immediate |= (1ULL << idx);
5774 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5775 DAG.getConstant(Immediate, MVT::i16));
5776 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5777 DAG.getIntPtrConstant(0));
5780 // Splat vector (with undefs)
5781 SDValue In = Op.getOperand(0);
5782 for (unsigned i = 1, e = Op.getNumOperands(); i != e; ++i) {
5783 if (Op.getOperand(i) != In && Op.getOperand(i).getOpcode() != ISD::UNDEF)
5784 llvm_unreachable("Unsupported predicate operation");
5787 SDValue EFLAGS, X86CC;
5788 if (In.getOpcode() == ISD::SETCC) {
5789 SDValue Op0 = In.getOperand(0);
5790 SDValue Op1 = In.getOperand(1);
5791 ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5792 bool isFP = Op1.getValueType().isFloatingPoint();
5793 unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5795 assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5797 X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5798 EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5799 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5800 } else if (In.getOpcode() == X86ISD::SETCC) {
5801 X86CC = In.getOperand(0);
5802 EFLAGS = In.getOperand(1);
5811 // res = allOnes ### CMOVNE -1, %res
5814 MVT InVT = In.getSimpleValueType();
5815 SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5816 EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5817 X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5820 if (VT == MVT::v16i1) {
5821 SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5822 SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5823 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5824 Cst0, Cst1, X86CC, EFLAGS);
5825 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5828 if (VT == MVT::v8i1) {
5829 SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5830 SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5831 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5832 Cst0, Cst1, X86CC, EFLAGS);
5833 CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5834 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5836 llvm_unreachable("Unsupported predicate operation");
5840 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5843 MVT VT = Op.getSimpleValueType();
5844 MVT ExtVT = VT.getVectorElementType();
5845 unsigned NumElems = Op.getNumOperands();
5847 // Generate vectors for predicate vectors.
5848 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5849 return LowerBUILD_VECTORvXi1(Op, DAG);
5851 // Vectors containing all zeros can be matched by pxor and xorps later
5852 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5853 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5854 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5855 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5858 return getZeroVector(VT, Subtarget, DAG, dl);
5861 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5862 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5863 // vpcmpeqd on 256-bit vectors.
5864 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5865 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5868 if (!VT.is512BitVector())
5869 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5872 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5873 if (Broadcast.getNode())
5876 unsigned EVTBits = ExtVT.getSizeInBits();
5878 unsigned NumZero = 0;
5879 unsigned NumNonZero = 0;
5880 unsigned NonZeros = 0;
5881 bool IsAllConstants = true;
5882 SmallSet<SDValue, 8> Values;
5883 for (unsigned i = 0; i < NumElems; ++i) {
5884 SDValue Elt = Op.getOperand(i);
5885 if (Elt.getOpcode() == ISD::UNDEF)
5888 if (Elt.getOpcode() != ISD::Constant &&
5889 Elt.getOpcode() != ISD::ConstantFP)
5890 IsAllConstants = false;
5891 if (X86::isZeroNode(Elt))
5894 NonZeros |= (1 << i);
5899 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5900 if (NumNonZero == 0)
5901 return DAG.getUNDEF(VT);
5903 // Special case for single non-zero, non-undef, element.
5904 if (NumNonZero == 1) {
5905 unsigned Idx = countTrailingZeros(NonZeros);
5906 SDValue Item = Op.getOperand(Idx);
5908 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5909 // the value are obviously zero, truncate the value to i32 and do the
5910 // insertion that way. Only do this if the value is non-constant or if the
5911 // value is a constant being inserted into element 0. It is cheaper to do
5912 // a constant pool load than it is to do a movd + shuffle.
5913 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5914 (!IsAllConstants || Idx == 0)) {
5915 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5917 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5918 EVT VecVT = MVT::v4i32;
5919 unsigned VecElts = 4;
5921 // Truncate the value (which may itself be a constant) to i32, and
5922 // convert it to a vector with movd (S2V+shuffle to zero extend).
5923 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5924 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5925 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5927 // Now we have our 32-bit value zero extended in the low element of
5928 // a vector. If Idx != 0, swizzle it into place.
5930 SmallVector<int, 4> Mask;
5931 Mask.push_back(Idx);
5932 for (unsigned i = 1; i != VecElts; ++i)
5934 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5937 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5941 // If we have a constant or non-constant insertion into the low element of
5942 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5943 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5944 // depending on what the source datatype is.
5947 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5949 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5950 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5951 if (VT.is256BitVector() || VT.is512BitVector()) {
5952 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5953 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5954 Item, DAG.getIntPtrConstant(0));
5956 assert(VT.is128BitVector() && "Expected an SSE value type!");
5957 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5958 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5959 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5962 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5963 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5964 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5965 if (VT.is256BitVector()) {
5966 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5967 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5969 assert(VT.is128BitVector() && "Expected an SSE value type!");
5970 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5972 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5976 // Is it a vector logical left shift?
5977 if (NumElems == 2 && Idx == 1 &&
5978 X86::isZeroNode(Op.getOperand(0)) &&
5979 !X86::isZeroNode(Op.getOperand(1))) {
5980 unsigned NumBits = VT.getSizeInBits();
5981 return getVShift(true, VT,
5982 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5983 VT, Op.getOperand(1)),
5984 NumBits/2, DAG, *this, dl);
5987 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5990 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5991 // is a non-constant being inserted into an element other than the low one,
5992 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5993 // movd/movss) to move this into the low element, then shuffle it into
5995 if (EVTBits == 32) {
5996 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5998 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5999 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6000 SmallVector<int, 8> MaskVec;
6001 for (unsigned i = 0; i != NumElems; ++i)
6002 MaskVec.push_back(i == Idx ? 0 : 1);
6003 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6007 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6008 if (Values.size() == 1) {
6009 if (EVTBits == 32) {
6010 // Instead of a shuffle like this:
6011 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6012 // Check if it's possible to issue this instead.
6013 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6014 unsigned Idx = countTrailingZeros(NonZeros);
6015 SDValue Item = Op.getOperand(Idx);
6016 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6017 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6022 // A vector full of immediates; various special cases are already
6023 // handled, so this is best done with a single constant-pool load.
6027 // For AVX-length vectors, build the individual 128-bit pieces and use
6028 // shuffles to put them in place.
6029 if (VT.is256BitVector()) {
6030 SmallVector<SDValue, 32> V;
6031 for (unsigned i = 0; i != NumElems; ++i)
6032 V.push_back(Op.getOperand(i));
6034 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6036 // Build both the lower and upper subvector.
6037 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6038 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6041 // Recreate the wider vector with the lower and upper part.
6042 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6045 // Let legalizer expand 2-wide build_vectors.
6046 if (EVTBits == 64) {
6047 if (NumNonZero == 1) {
6048 // One half is zero or undef.
6049 unsigned Idx = countTrailingZeros(NonZeros);
6050 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6051 Op.getOperand(Idx));
6052 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6057 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6058 if (EVTBits == 8 && NumElems == 16) {
6059 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6061 if (V.getNode()) return V;
6064 if (EVTBits == 16 && NumElems == 8) {
6065 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6067 if (V.getNode()) return V;
6070 // If element VT is == 32 bits, turn it into a number of shuffles.
6071 SmallVector<SDValue, 8> V(NumElems);
6072 if (NumElems == 4 && NumZero > 0) {
6073 for (unsigned i = 0; i < 4; ++i) {
6074 bool isZero = !(NonZeros & (1 << i));
6076 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6078 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6081 for (unsigned i = 0; i < 2; ++i) {
6082 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6085 V[i] = V[i*2]; // Must be a zero vector.
6088 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6091 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6094 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6099 bool Reverse1 = (NonZeros & 0x3) == 2;
6100 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6104 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6105 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6107 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6110 if (Values.size() > 1 && VT.is128BitVector()) {
6111 // Check for a build vector of consecutive loads.
6112 for (unsigned i = 0; i < NumElems; ++i)
6113 V[i] = Op.getOperand(i);
6115 // Check for elements which are consecutive loads.
6116 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6120 // Check for a build vector from mostly shuffle plus few inserting.
6121 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6125 // For SSE 4.1, use insertps to put the high elements into the low element.
6126 if (getSubtarget()->hasSSE41()) {
6128 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6129 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6131 Result = DAG.getUNDEF(VT);
6133 for (unsigned i = 1; i < NumElems; ++i) {
6134 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6135 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6136 Op.getOperand(i), DAG.getIntPtrConstant(i));
6141 // Otherwise, expand into a number of unpckl*, start by extending each of
6142 // our (non-undef) elements to the full vector width with the element in the
6143 // bottom slot of the vector (which generates no code for SSE).
6144 for (unsigned i = 0; i < NumElems; ++i) {
6145 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6146 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6148 V[i] = DAG.getUNDEF(VT);
6151 // Next, we iteratively mix elements, e.g. for v4f32:
6152 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6153 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6154 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6155 unsigned EltStride = NumElems >> 1;
6156 while (EltStride != 0) {
6157 for (unsigned i = 0; i < EltStride; ++i) {
6158 // If V[i+EltStride] is undef and this is the first round of mixing,
6159 // then it is safe to just drop this shuffle: V[i] is already in the
6160 // right place, the one element (since it's the first round) being
6161 // inserted as undef can be dropped. This isn't safe for successive
6162 // rounds because they will permute elements within both vectors.
6163 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6164 EltStride == NumElems/2)
6167 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6176 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6177 // to create 256-bit vectors from two other 128-bit ones.
6178 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6180 MVT ResVT = Op.getSimpleValueType();
6182 assert((ResVT.is256BitVector() ||
6183 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6185 SDValue V1 = Op.getOperand(0);
6186 SDValue V2 = Op.getOperand(1);
6187 unsigned NumElems = ResVT.getVectorNumElements();
6188 if(ResVT.is256BitVector())
6189 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6191 if (Op.getNumOperands() == 4) {
6192 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6193 ResVT.getVectorNumElements()/2);
6194 SDValue V3 = Op.getOperand(2);
6195 SDValue V4 = Op.getOperand(3);
6196 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6197 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6199 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6202 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6203 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6204 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6205 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6206 Op.getNumOperands() == 4)));
6208 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6209 // from two other 128-bit ones.
6211 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6212 return LowerAVXCONCAT_VECTORS(Op, DAG);
6215 // Try to lower a shuffle node into a simple blend instruction.
6217 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6218 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6219 SDValue V1 = SVOp->getOperand(0);
6220 SDValue V2 = SVOp->getOperand(1);
6222 MVT VT = SVOp->getSimpleValueType(0);
6223 MVT EltVT = VT.getVectorElementType();
6224 unsigned NumElems = VT.getVectorNumElements();
6226 // There is no blend with immediate in AVX-512.
6227 if (VT.is512BitVector())
6230 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6232 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6235 // Check the mask for BLEND and build the value.
6236 unsigned MaskValue = 0;
6237 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6238 unsigned NumLanes = (NumElems-1)/8 + 1;
6239 unsigned NumElemsInLane = NumElems / NumLanes;
6241 // Blend for v16i16 should be symetric for the both lanes.
6242 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6244 int SndLaneEltIdx = (NumLanes == 2) ?
6245 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6246 int EltIdx = SVOp->getMaskElt(i);
6248 if ((EltIdx < 0 || EltIdx == (int)i) &&
6249 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6252 if (((unsigned)EltIdx == (i + NumElems)) &&
6253 (SndLaneEltIdx < 0 ||
6254 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6255 MaskValue |= (1<<i);
6260 // Convert i32 vectors to floating point if it is not AVX2.
6261 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6263 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6264 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6266 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6267 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6270 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6271 DAG.getConstant(MaskValue, MVT::i32));
6272 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6275 // v8i16 shuffles - Prefer shuffles in the following order:
6276 // 1. [all] pshuflw, pshufhw, optional move
6277 // 2. [ssse3] 1 x pshufb
6278 // 3. [ssse3] 2 x pshufb + 1 x por
6279 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6281 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6282 SelectionDAG &DAG) {
6283 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6284 SDValue V1 = SVOp->getOperand(0);
6285 SDValue V2 = SVOp->getOperand(1);
6287 SmallVector<int, 8> MaskVals;
6289 // Determine if more than 1 of the words in each of the low and high quadwords
6290 // of the result come from the same quadword of one of the two inputs. Undef
6291 // mask values count as coming from any quadword, for better codegen.
6292 unsigned LoQuad[] = { 0, 0, 0, 0 };
6293 unsigned HiQuad[] = { 0, 0, 0, 0 };
6294 std::bitset<4> InputQuads;
6295 for (unsigned i = 0; i < 8; ++i) {
6296 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6297 int EltIdx = SVOp->getMaskElt(i);
6298 MaskVals.push_back(EltIdx);
6307 InputQuads.set(EltIdx / 4);
6310 int BestLoQuad = -1;
6311 unsigned MaxQuad = 1;
6312 for (unsigned i = 0; i < 4; ++i) {
6313 if (LoQuad[i] > MaxQuad) {
6315 MaxQuad = LoQuad[i];
6319 int BestHiQuad = -1;
6321 for (unsigned i = 0; i < 4; ++i) {
6322 if (HiQuad[i] > MaxQuad) {
6324 MaxQuad = HiQuad[i];
6328 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6329 // of the two input vectors, shuffle them into one input vector so only a
6330 // single pshufb instruction is necessary. If There are more than 2 input
6331 // quads, disable the next transformation since it does not help SSSE3.
6332 bool V1Used = InputQuads[0] || InputQuads[1];
6333 bool V2Used = InputQuads[2] || InputQuads[3];
6334 if (Subtarget->hasSSSE3()) {
6335 if (InputQuads.count() == 2 && V1Used && V2Used) {
6336 BestLoQuad = InputQuads[0] ? 0 : 1;
6337 BestHiQuad = InputQuads[2] ? 2 : 3;
6339 if (InputQuads.count() > 2) {
6345 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6346 // the shuffle mask. If a quad is scored as -1, that means that it contains
6347 // words from all 4 input quadwords.
6349 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6351 BestLoQuad < 0 ? 0 : BestLoQuad,
6352 BestHiQuad < 0 ? 1 : BestHiQuad
6354 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6355 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6356 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6357 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6359 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6360 // source words for the shuffle, to aid later transformations.
6361 bool AllWordsInNewV = true;
6362 bool InOrder[2] = { true, true };
6363 for (unsigned i = 0; i != 8; ++i) {
6364 int idx = MaskVals[i];
6366 InOrder[i/4] = false;
6367 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6369 AllWordsInNewV = false;
6373 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6374 if (AllWordsInNewV) {
6375 for (int i = 0; i != 8; ++i) {
6376 int idx = MaskVals[i];
6379 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6380 if ((idx != i) && idx < 4)
6382 if ((idx != i) && idx > 3)
6391 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6392 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6393 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6394 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6395 unsigned TargetMask = 0;
6396 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6397 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6398 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6399 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6400 getShufflePSHUFLWImmediate(SVOp);
6401 V1 = NewV.getOperand(0);
6402 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6406 // Promote splats to a larger type which usually leads to more efficient code.
6407 // FIXME: Is this true if pshufb is available?
6408 if (SVOp->isSplat())
6409 return PromoteSplat(SVOp, DAG);
6411 // If we have SSSE3, and all words of the result are from 1 input vector,
6412 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6413 // is present, fall back to case 4.
6414 if (Subtarget->hasSSSE3()) {
6415 SmallVector<SDValue,16> pshufbMask;
6417 // If we have elements from both input vectors, set the high bit of the
6418 // shuffle mask element to zero out elements that come from V2 in the V1
6419 // mask, and elements that come from V1 in the V2 mask, so that the two
6420 // results can be OR'd together.
6421 bool TwoInputs = V1Used && V2Used;
6422 for (unsigned i = 0; i != 8; ++i) {
6423 int EltIdx = MaskVals[i] * 2;
6424 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6425 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6426 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6427 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6429 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6430 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6431 DAG.getNode(ISD::BUILD_VECTOR, dl,
6432 MVT::v16i8, &pshufbMask[0], 16));
6434 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6436 // Calculate the shuffle mask for the second input, shuffle it, and
6437 // OR it with the first shuffled input.
6439 for (unsigned i = 0; i != 8; ++i) {
6440 int EltIdx = MaskVals[i] * 2;
6441 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6442 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6443 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6444 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6446 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6447 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6448 DAG.getNode(ISD::BUILD_VECTOR, dl,
6449 MVT::v16i8, &pshufbMask[0], 16));
6450 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6451 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6454 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6455 // and update MaskVals with new element order.
6456 std::bitset<8> InOrder;
6457 if (BestLoQuad >= 0) {
6458 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6459 for (int i = 0; i != 4; ++i) {
6460 int idx = MaskVals[i];
6463 } else if ((idx / 4) == BestLoQuad) {
6468 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6471 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6472 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6473 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6475 getShufflePSHUFLWImmediate(SVOp), DAG);
6479 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6480 // and update MaskVals with the new element order.
6481 if (BestHiQuad >= 0) {
6482 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6483 for (unsigned i = 4; i != 8; ++i) {
6484 int idx = MaskVals[i];
6487 } else if ((idx / 4) == BestHiQuad) {
6488 MaskV[i] = (idx & 3) + 4;
6492 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6495 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6496 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6497 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6499 getShufflePSHUFHWImmediate(SVOp), DAG);
6503 // In case BestHi & BestLo were both -1, which means each quadword has a word
6504 // from each of the four input quadwords, calculate the InOrder bitvector now
6505 // before falling through to the insert/extract cleanup.
6506 if (BestLoQuad == -1 && BestHiQuad == -1) {
6508 for (int i = 0; i != 8; ++i)
6509 if (MaskVals[i] < 0 || MaskVals[i] == i)
6513 // The other elements are put in the right place using pextrw and pinsrw.
6514 for (unsigned i = 0; i != 8; ++i) {
6517 int EltIdx = MaskVals[i];
6520 SDValue ExtOp = (EltIdx < 8) ?
6521 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6522 DAG.getIntPtrConstant(EltIdx)) :
6523 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6524 DAG.getIntPtrConstant(EltIdx - 8));
6525 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6526 DAG.getIntPtrConstant(i));
6531 // v16i8 shuffles - Prefer shuffles in the following order:
6532 // 1. [ssse3] 1 x pshufb
6533 // 2. [ssse3] 2 x pshufb + 1 x por
6534 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6535 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6536 const X86Subtarget* Subtarget,
6537 SelectionDAG &DAG) {
6538 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6539 SDValue V1 = SVOp->getOperand(0);
6540 SDValue V2 = SVOp->getOperand(1);
6542 ArrayRef<int> MaskVals = SVOp->getMask();
6544 // Promote splats to a larger type which usually leads to more efficient code.
6545 // FIXME: Is this true if pshufb is available?
6546 if (SVOp->isSplat())
6547 return PromoteSplat(SVOp, DAG);
6549 // If we have SSSE3, case 1 is generated when all result bytes come from
6550 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6551 // present, fall back to case 3.
6553 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6554 if (Subtarget->hasSSSE3()) {
6555 SmallVector<SDValue,16> pshufbMask;
6557 // If all result elements are from one input vector, then only translate
6558 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6560 // Otherwise, we have elements from both input vectors, and must zero out
6561 // elements that come from V2 in the first mask, and V1 in the second mask
6562 // so that we can OR them together.
6563 for (unsigned i = 0; i != 16; ++i) {
6564 int EltIdx = MaskVals[i];
6565 if (EltIdx < 0 || EltIdx >= 16)
6567 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6569 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6570 DAG.getNode(ISD::BUILD_VECTOR, dl,
6571 MVT::v16i8, &pshufbMask[0], 16));
6573 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6574 // the 2nd operand if it's undefined or zero.
6575 if (V2.getOpcode() == ISD::UNDEF ||
6576 ISD::isBuildVectorAllZeros(V2.getNode()))
6579 // Calculate the shuffle mask for the second input, shuffle it, and
6580 // OR it with the first shuffled input.
6582 for (unsigned i = 0; i != 16; ++i) {
6583 int EltIdx = MaskVals[i];
6584 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6585 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6587 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6588 DAG.getNode(ISD::BUILD_VECTOR, dl,
6589 MVT::v16i8, &pshufbMask[0], 16));
6590 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6593 // No SSSE3 - Calculate in place words and then fix all out of place words
6594 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6595 // the 16 different words that comprise the two doublequadword input vectors.
6596 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6597 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6599 for (int i = 0; i != 8; ++i) {
6600 int Elt0 = MaskVals[i*2];
6601 int Elt1 = MaskVals[i*2+1];
6603 // This word of the result is all undef, skip it.
6604 if (Elt0 < 0 && Elt1 < 0)
6607 // This word of the result is already in the correct place, skip it.
6608 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6611 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6612 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6615 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6616 // using a single extract together, load it and store it.
6617 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6618 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6619 DAG.getIntPtrConstant(Elt1 / 2));
6620 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6621 DAG.getIntPtrConstant(i));
6625 // If Elt1 is defined, extract it from the appropriate source. If the
6626 // source byte is not also odd, shift the extracted word left 8 bits
6627 // otherwise clear the bottom 8 bits if we need to do an or.
6629 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6630 DAG.getIntPtrConstant(Elt1 / 2));
6631 if ((Elt1 & 1) == 0)
6632 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6634 TLI.getShiftAmountTy(InsElt.getValueType())));
6636 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6637 DAG.getConstant(0xFF00, MVT::i16));
6639 // If Elt0 is defined, extract it from the appropriate source. If the
6640 // source byte is not also even, shift the extracted word right 8 bits. If
6641 // Elt1 was also defined, OR the extracted values together before
6642 // inserting them in the result.
6644 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6645 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6646 if ((Elt0 & 1) != 0)
6647 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6649 TLI.getShiftAmountTy(InsElt0.getValueType())));
6651 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6652 DAG.getConstant(0x00FF, MVT::i16));
6653 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6656 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6657 DAG.getIntPtrConstant(i));
6659 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6662 // v32i8 shuffles - Translate to VPSHUFB if possible.
6664 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6665 const X86Subtarget *Subtarget,
6666 SelectionDAG &DAG) {
6667 MVT VT = SVOp->getSimpleValueType(0);
6668 SDValue V1 = SVOp->getOperand(0);
6669 SDValue V2 = SVOp->getOperand(1);
6671 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6673 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6674 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6675 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6677 // VPSHUFB may be generated if
6678 // (1) one of input vector is undefined or zeroinitializer.
6679 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6680 // And (2) the mask indexes don't cross the 128-bit lane.
6681 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6682 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6685 if (V1IsAllZero && !V2IsAllZero) {
6686 CommuteVectorShuffleMask(MaskVals, 32);
6689 SmallVector<SDValue, 32> pshufbMask;
6690 for (unsigned i = 0; i != 32; i++) {
6691 int EltIdx = MaskVals[i];
6692 if (EltIdx < 0 || EltIdx >= 32)
6695 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6696 // Cross lane is not allowed.
6700 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6702 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6703 DAG.getNode(ISD::BUILD_VECTOR, dl,
6704 MVT::v32i8, &pshufbMask[0], 32));
6707 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6708 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6709 /// done when every pair / quad of shuffle mask elements point to elements in
6710 /// the right sequence. e.g.
6711 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6713 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6714 SelectionDAG &DAG) {
6715 MVT VT = SVOp->getSimpleValueType(0);
6717 unsigned NumElems = VT.getVectorNumElements();
6720 switch (VT.SimpleTy) {
6721 default: llvm_unreachable("Unexpected!");
6722 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6723 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6724 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6725 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6726 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6727 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6730 SmallVector<int, 8> MaskVec;
6731 for (unsigned i = 0; i != NumElems; i += Scale) {
6733 for (unsigned j = 0; j != Scale; ++j) {
6734 int EltIdx = SVOp->getMaskElt(i+j);
6738 StartIdx = (EltIdx / Scale);
6739 if (EltIdx != (int)(StartIdx*Scale + j))
6742 MaskVec.push_back(StartIdx);
6745 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6746 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6747 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6750 /// getVZextMovL - Return a zero-extending vector move low node.
6752 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6753 SDValue SrcOp, SelectionDAG &DAG,
6754 const X86Subtarget *Subtarget, SDLoc dl) {
6755 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6756 LoadSDNode *LD = NULL;
6757 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6758 LD = dyn_cast<LoadSDNode>(SrcOp);
6760 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6762 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6763 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6764 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6765 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6766 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6768 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6769 return DAG.getNode(ISD::BITCAST, dl, VT,
6770 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6771 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6779 return DAG.getNode(ISD::BITCAST, dl, VT,
6780 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6781 DAG.getNode(ISD::BITCAST, dl,
6785 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6786 /// which could not be matched by any known target speficic shuffle
6788 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6790 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6791 if (NewOp.getNode())
6794 MVT VT = SVOp->getSimpleValueType(0);
6796 unsigned NumElems = VT.getVectorNumElements();
6797 unsigned NumLaneElems = NumElems / 2;
6800 MVT EltVT = VT.getVectorElementType();
6801 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6804 SmallVector<int, 16> Mask;
6805 for (unsigned l = 0; l < 2; ++l) {
6806 // Build a shuffle mask for the output, discovering on the fly which
6807 // input vectors to use as shuffle operands (recorded in InputUsed).
6808 // If building a suitable shuffle vector proves too hard, then bail
6809 // out with UseBuildVector set.
6810 bool UseBuildVector = false;
6811 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6812 unsigned LaneStart = l * NumLaneElems;
6813 for (unsigned i = 0; i != NumLaneElems; ++i) {
6814 // The mask element. This indexes into the input.
6815 int Idx = SVOp->getMaskElt(i+LaneStart);
6817 // the mask element does not index into any input vector.
6822 // The input vector this mask element indexes into.
6823 int Input = Idx / NumLaneElems;
6825 // Turn the index into an offset from the start of the input vector.
6826 Idx -= Input * NumLaneElems;
6828 // Find or create a shuffle vector operand to hold this input.
6830 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6831 if (InputUsed[OpNo] == Input)
6832 // This input vector is already an operand.
6834 if (InputUsed[OpNo] < 0) {
6835 // Create a new operand for this input vector.
6836 InputUsed[OpNo] = Input;
6841 if (OpNo >= array_lengthof(InputUsed)) {
6842 // More than two input vectors used! Give up on trying to create a
6843 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6844 UseBuildVector = true;
6848 // Add the mask index for the new shuffle vector.
6849 Mask.push_back(Idx + OpNo * NumLaneElems);
6852 if (UseBuildVector) {
6853 SmallVector<SDValue, 16> SVOps;
6854 for (unsigned i = 0; i != NumLaneElems; ++i) {
6855 // The mask element. This indexes into the input.
6856 int Idx = SVOp->getMaskElt(i+LaneStart);
6858 SVOps.push_back(DAG.getUNDEF(EltVT));
6862 // The input vector this mask element indexes into.
6863 int Input = Idx / NumElems;
6865 // Turn the index into an offset from the start of the input vector.
6866 Idx -= Input * NumElems;
6868 // Extract the vector element by hand.
6869 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6870 SVOp->getOperand(Input),
6871 DAG.getIntPtrConstant(Idx)));
6874 // Construct the output using a BUILD_VECTOR.
6875 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6877 } else if (InputUsed[0] < 0) {
6878 // No input vectors were used! The result is undefined.
6879 Output[l] = DAG.getUNDEF(NVT);
6881 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6882 (InputUsed[0] % 2) * NumLaneElems,
6884 // If only one input was used, use an undefined vector for the other.
6885 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6886 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6887 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6888 // At least one input vector was used. Create a new shuffle vector.
6889 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6895 // Concatenate the result back
6896 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6899 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6900 /// 4 elements, and match them with several different shuffle types.
6902 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6903 SDValue V1 = SVOp->getOperand(0);
6904 SDValue V2 = SVOp->getOperand(1);
6906 MVT VT = SVOp->getSimpleValueType(0);
6908 assert(VT.is128BitVector() && "Unsupported vector size");
6910 std::pair<int, int> Locs[4];
6911 int Mask1[] = { -1, -1, -1, -1 };
6912 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6916 for (unsigned i = 0; i != 4; ++i) {
6917 int Idx = PermMask[i];
6919 Locs[i] = std::make_pair(-1, -1);
6921 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6923 Locs[i] = std::make_pair(0, NumLo);
6927 Locs[i] = std::make_pair(1, NumHi);
6929 Mask1[2+NumHi] = Idx;
6935 if (NumLo <= 2 && NumHi <= 2) {
6936 // If no more than two elements come from either vector. This can be
6937 // implemented with two shuffles. First shuffle gather the elements.
6938 // The second shuffle, which takes the first shuffle as both of its
6939 // vector operands, put the elements into the right order.
6940 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6942 int Mask2[] = { -1, -1, -1, -1 };
6944 for (unsigned i = 0; i != 4; ++i)
6945 if (Locs[i].first != -1) {
6946 unsigned Idx = (i < 2) ? 0 : 4;
6947 Idx += Locs[i].first * 2 + Locs[i].second;
6951 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6954 if (NumLo == 3 || NumHi == 3) {
6955 // Otherwise, we must have three elements from one vector, call it X, and
6956 // one element from the other, call it Y. First, use a shufps to build an
6957 // intermediate vector with the one element from Y and the element from X
6958 // that will be in the same half in the final destination (the indexes don't
6959 // matter). Then, use a shufps to build the final vector, taking the half
6960 // containing the element from Y from the intermediate, and the other half
6963 // Normalize it so the 3 elements come from V1.
6964 CommuteVectorShuffleMask(PermMask, 4);
6968 // Find the element from V2.
6970 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6971 int Val = PermMask[HiIndex];
6978 Mask1[0] = PermMask[HiIndex];
6980 Mask1[2] = PermMask[HiIndex^1];
6982 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6985 Mask1[0] = PermMask[0];
6986 Mask1[1] = PermMask[1];
6987 Mask1[2] = HiIndex & 1 ? 6 : 4;
6988 Mask1[3] = HiIndex & 1 ? 4 : 6;
6989 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6992 Mask1[0] = HiIndex & 1 ? 2 : 0;
6993 Mask1[1] = HiIndex & 1 ? 0 : 2;
6994 Mask1[2] = PermMask[2];
6995 Mask1[3] = PermMask[3];
7000 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7003 // Break it into (shuffle shuffle_hi, shuffle_lo).
7004 int LoMask[] = { -1, -1, -1, -1 };
7005 int HiMask[] = { -1, -1, -1, -1 };
7007 int *MaskPtr = LoMask;
7008 unsigned MaskIdx = 0;
7011 for (unsigned i = 0; i != 4; ++i) {
7018 int Idx = PermMask[i];
7020 Locs[i] = std::make_pair(-1, -1);
7021 } else if (Idx < 4) {
7022 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7023 MaskPtr[LoIdx] = Idx;
7026 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7027 MaskPtr[HiIdx] = Idx;
7032 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7033 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7034 int MaskOps[] = { -1, -1, -1, -1 };
7035 for (unsigned i = 0; i != 4; ++i)
7036 if (Locs[i].first != -1)
7037 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7038 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7041 static bool MayFoldVectorLoad(SDValue V) {
7042 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7043 V = V.getOperand(0);
7045 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7046 V = V.getOperand(0);
7047 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7048 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7049 // BUILD_VECTOR (load), undef
7050 V = V.getOperand(0);
7052 return MayFoldLoad(V);
7056 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7057 MVT VT = Op.getSimpleValueType();
7059 // Canonizalize to v2f64.
7060 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7061 return DAG.getNode(ISD::BITCAST, dl, VT,
7062 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7067 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7069 SDValue V1 = Op.getOperand(0);
7070 SDValue V2 = Op.getOperand(1);
7071 MVT VT = Op.getSimpleValueType();
7073 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7075 if (HasSSE2 && VT == MVT::v2f64)
7076 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7078 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7079 return DAG.getNode(ISD::BITCAST, dl, VT,
7080 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7081 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7082 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7086 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7087 SDValue V1 = Op.getOperand(0);
7088 SDValue V2 = Op.getOperand(1);
7089 MVT VT = Op.getSimpleValueType();
7091 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7092 "unsupported shuffle type");
7094 if (V2.getOpcode() == ISD::UNDEF)
7098 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7102 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7103 SDValue V1 = Op.getOperand(0);
7104 SDValue V2 = Op.getOperand(1);
7105 MVT VT = Op.getSimpleValueType();
7106 unsigned NumElems = VT.getVectorNumElements();
7108 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7109 // operand of these instructions is only memory, so check if there's a
7110 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7112 bool CanFoldLoad = false;
7114 // Trivial case, when V2 comes from a load.
7115 if (MayFoldVectorLoad(V2))
7118 // When V1 is a load, it can be folded later into a store in isel, example:
7119 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7121 // (MOVLPSmr addr:$src1, VR128:$src2)
7122 // So, recognize this potential and also use MOVLPS or MOVLPD
7123 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7126 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7128 if (HasSSE2 && NumElems == 2)
7129 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7132 // If we don't care about the second element, proceed to use movss.
7133 if (SVOp->getMaskElt(1) != -1)
7134 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7137 // movl and movlp will both match v2i64, but v2i64 is never matched by
7138 // movl earlier because we make it strict to avoid messing with the movlp load
7139 // folding logic (see the code above getMOVLP call). Match it here then,
7140 // this is horrible, but will stay like this until we move all shuffle
7141 // matching to x86 specific nodes. Note that for the 1st condition all
7142 // types are matched with movsd.
7144 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7145 // as to remove this logic from here, as much as possible
7146 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7147 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7148 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7151 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7153 // Invert the operand order and use SHUFPS to match it.
7154 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7155 getShuffleSHUFImmediate(SVOp), DAG);
7158 // Reduce a vector shuffle to zext.
7159 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7160 SelectionDAG &DAG) {
7161 // PMOVZX is only available from SSE41.
7162 if (!Subtarget->hasSSE41())
7165 MVT VT = Op.getSimpleValueType();
7167 // Only AVX2 support 256-bit vector integer extending.
7168 if (!Subtarget->hasInt256() && VT.is256BitVector())
7171 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7173 SDValue V1 = Op.getOperand(0);
7174 SDValue V2 = Op.getOperand(1);
7175 unsigned NumElems = VT.getVectorNumElements();
7177 // Extending is an unary operation and the element type of the source vector
7178 // won't be equal to or larger than i64.
7179 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7180 VT.getVectorElementType() == MVT::i64)
7183 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7184 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7185 while ((1U << Shift) < NumElems) {
7186 if (SVOp->getMaskElt(1U << Shift) == 1)
7189 // The maximal ratio is 8, i.e. from i8 to i64.
7194 // Check the shuffle mask.
7195 unsigned Mask = (1U << Shift) - 1;
7196 for (unsigned i = 0; i != NumElems; ++i) {
7197 int EltIdx = SVOp->getMaskElt(i);
7198 if ((i & Mask) != 0 && EltIdx != -1)
7200 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7204 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7205 MVT NeVT = MVT::getIntegerVT(NBits);
7206 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7208 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7211 // Simplify the operand as it's prepared to be fed into shuffle.
7212 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7213 if (V1.getOpcode() == ISD::BITCAST &&
7214 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7215 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7216 V1.getOperand(0).getOperand(0)
7217 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7218 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7219 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7220 ConstantSDNode *CIdx =
7221 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7222 // If it's foldable, i.e. normal load with single use, we will let code
7223 // selection to fold it. Otherwise, we will short the conversion sequence.
7224 if (CIdx && CIdx->getZExtValue() == 0 &&
7225 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7226 MVT FullVT = V.getSimpleValueType();
7227 MVT V1VT = V1.getSimpleValueType();
7228 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7229 // The "ext_vec_elt" node is wider than the result node.
7230 // In this case we should extract subvector from V.
7231 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7232 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7233 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7234 FullVT.getVectorNumElements()/Ratio);
7235 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7236 DAG.getIntPtrConstant(0));
7238 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7242 return DAG.getNode(ISD::BITCAST, DL, VT,
7243 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7247 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7248 SelectionDAG &DAG) {
7249 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7250 MVT VT = Op.getSimpleValueType();
7252 SDValue V1 = Op.getOperand(0);
7253 SDValue V2 = Op.getOperand(1);
7255 if (isZeroShuffle(SVOp))
7256 return getZeroVector(VT, Subtarget, DAG, dl);
7258 // Handle splat operations
7259 if (SVOp->isSplat()) {
7260 // Use vbroadcast whenever the splat comes from a foldable load
7261 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7262 if (Broadcast.getNode())
7266 // Check integer expanding shuffles.
7267 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7268 if (NewOp.getNode())
7271 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7273 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7274 VT == MVT::v16i16 || VT == MVT::v32i8) {
7275 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7276 if (NewOp.getNode())
7277 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7278 } else if ((VT == MVT::v4i32 ||
7279 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7280 // FIXME: Figure out a cleaner way to do this.
7281 // Try to make use of movq to zero out the top part.
7282 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7283 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7284 if (NewOp.getNode()) {
7285 MVT NewVT = NewOp.getSimpleValueType();
7286 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7287 NewVT, true, false))
7288 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7289 DAG, Subtarget, dl);
7291 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7292 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7293 if (NewOp.getNode()) {
7294 MVT NewVT = NewOp.getSimpleValueType();
7295 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7296 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7297 DAG, Subtarget, dl);
7305 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7306 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7307 SDValue V1 = Op.getOperand(0);
7308 SDValue V2 = Op.getOperand(1);
7309 MVT VT = Op.getSimpleValueType();
7311 unsigned NumElems = VT.getVectorNumElements();
7312 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7313 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7314 bool V1IsSplat = false;
7315 bool V2IsSplat = false;
7316 bool HasSSE2 = Subtarget->hasSSE2();
7317 bool HasFp256 = Subtarget->hasFp256();
7318 bool HasInt256 = Subtarget->hasInt256();
7319 MachineFunction &MF = DAG.getMachineFunction();
7320 bool OptForSize = MF.getFunction()->getAttributes().
7321 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7323 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7325 if (V1IsUndef && V2IsUndef)
7326 return DAG.getUNDEF(VT);
7328 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7330 // Vector shuffle lowering takes 3 steps:
7332 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7333 // narrowing and commutation of operands should be handled.
7334 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7336 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7337 // so the shuffle can be broken into other shuffles and the legalizer can
7338 // try the lowering again.
7340 // The general idea is that no vector_shuffle operation should be left to
7341 // be matched during isel, all of them must be converted to a target specific
7344 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7345 // narrowing and commutation of operands should be handled. The actual code
7346 // doesn't include all of those, work in progress...
7347 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7348 if (NewOp.getNode())
7351 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7353 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7354 // unpckh_undef). Only use pshufd if speed is more important than size.
7355 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7356 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7357 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7358 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7360 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7361 V2IsUndef && MayFoldVectorLoad(V1))
7362 return getMOVDDup(Op, dl, V1, DAG);
7364 if (isMOVHLPS_v_undef_Mask(M, VT))
7365 return getMOVHighToLow(Op, dl, DAG);
7367 // Use to match splats
7368 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7369 (VT == MVT::v2f64 || VT == MVT::v2i64))
7370 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7372 if (isPSHUFDMask(M, VT)) {
7373 // The actual implementation will match the mask in the if above and then
7374 // during isel it can match several different instructions, not only pshufd
7375 // as its name says, sad but true, emulate the behavior for now...
7376 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7377 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7379 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7381 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7382 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7384 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7385 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7388 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7392 if (isPALIGNRMask(M, VT, Subtarget))
7393 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7394 getShufflePALIGNRImmediate(SVOp),
7397 // Check if this can be converted into a logical shift.
7398 bool isLeft = false;
7401 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7402 if (isShift && ShVal.hasOneUse()) {
7403 // If the shifted value has multiple uses, it may be cheaper to use
7404 // v_set0 + movlhps or movhlps, etc.
7405 MVT EltVT = VT.getVectorElementType();
7406 ShAmt *= EltVT.getSizeInBits();
7407 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7410 if (isMOVLMask(M, VT)) {
7411 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7412 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7413 if (!isMOVLPMask(M, VT)) {
7414 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7415 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7417 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7418 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7422 // FIXME: fold these into legal mask.
7423 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7424 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7426 if (isMOVHLPSMask(M, VT))
7427 return getMOVHighToLow(Op, dl, DAG);
7429 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7430 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7432 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7433 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7435 if (isMOVLPMask(M, VT))
7436 return getMOVLP(Op, dl, DAG, HasSSE2);
7438 if (ShouldXformToMOVHLPS(M, VT) ||
7439 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7440 return CommuteVectorShuffle(SVOp, DAG);
7443 // No better options. Use a vshldq / vsrldq.
7444 MVT EltVT = VT.getVectorElementType();
7445 ShAmt *= EltVT.getSizeInBits();
7446 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7449 bool Commuted = false;
7450 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7451 // 1,1,1,1 -> v8i16 though.
7452 V1IsSplat = isSplatVector(V1.getNode());
7453 V2IsSplat = isSplatVector(V2.getNode());
7455 // Canonicalize the splat or undef, if present, to be on the RHS.
7456 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7457 CommuteVectorShuffleMask(M, NumElems);
7459 std::swap(V1IsSplat, V2IsSplat);
7463 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7464 // Shuffling low element of v1 into undef, just return v1.
7467 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7468 // the instruction selector will not match, so get a canonical MOVL with
7469 // swapped operands to undo the commute.
7470 return getMOVL(DAG, dl, VT, V2, V1);
7473 if (isUNPCKLMask(M, VT, HasInt256))
7474 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7476 if (isUNPCKHMask(M, VT, HasInt256))
7477 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7480 // Normalize mask so all entries that point to V2 points to its first
7481 // element then try to match unpck{h|l} again. If match, return a
7482 // new vector_shuffle with the corrected mask.p
7483 SmallVector<int, 8> NewMask(M.begin(), M.end());
7484 NormalizeMask(NewMask, NumElems);
7485 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7486 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7487 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7488 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7492 // Commute is back and try unpck* again.
7493 // FIXME: this seems wrong.
7494 CommuteVectorShuffleMask(M, NumElems);
7496 std::swap(V1IsSplat, V2IsSplat);
7499 if (isUNPCKLMask(M, VT, HasInt256))
7500 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7502 if (isUNPCKHMask(M, VT, HasInt256))
7503 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7506 // Normalize the node to match x86 shuffle ops if needed
7507 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7508 return CommuteVectorShuffle(SVOp, DAG);
7510 // The checks below are all present in isShuffleMaskLegal, but they are
7511 // inlined here right now to enable us to directly emit target specific
7512 // nodes, and remove one by one until they don't return Op anymore.
7514 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7515 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7516 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7517 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7520 if (isPSHUFHWMask(M, VT, HasInt256))
7521 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7522 getShufflePSHUFHWImmediate(SVOp),
7525 if (isPSHUFLWMask(M, VT, HasInt256))
7526 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7527 getShufflePSHUFLWImmediate(SVOp),
7530 if (isSHUFPMask(M, VT))
7531 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7532 getShuffleSHUFImmediate(SVOp), DAG);
7534 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7535 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7536 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7537 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7539 //===--------------------------------------------------------------------===//
7540 // Generate target specific nodes for 128 or 256-bit shuffles only
7541 // supported in the AVX instruction set.
7544 // Handle VMOVDDUPY permutations
7545 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7546 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7548 // Handle VPERMILPS/D* permutations
7549 if (isVPERMILPMask(M, VT)) {
7550 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7551 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7552 getShuffleSHUFImmediate(SVOp), DAG);
7553 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7554 getShuffleSHUFImmediate(SVOp), DAG);
7557 // Handle VPERM2F128/VPERM2I128 permutations
7558 if (isVPERM2X128Mask(M, VT, HasFp256))
7559 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7560 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7562 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7563 if (BlendOp.getNode())
7567 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7568 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7570 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7571 VT.is512BitVector()) {
7572 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7573 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7574 SmallVector<SDValue, 16> permclMask;
7575 for (unsigned i = 0; i != NumElems; ++i) {
7576 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7579 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7580 &permclMask[0], NumElems);
7582 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7583 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7584 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7585 return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7586 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7589 //===--------------------------------------------------------------------===//
7590 // Since no target specific shuffle was selected for this generic one,
7591 // lower it into other known shuffles. FIXME: this isn't true yet, but
7592 // this is the plan.
7595 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7596 if (VT == MVT::v8i16) {
7597 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7598 if (NewOp.getNode())
7602 if (VT == MVT::v16i8) {
7603 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7604 if (NewOp.getNode())
7608 if (VT == MVT::v32i8) {
7609 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7610 if (NewOp.getNode())
7614 // Handle all 128-bit wide vectors with 4 elements, and match them with
7615 // several different shuffle types.
7616 if (NumElems == 4 && VT.is128BitVector())
7617 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7619 // Handle general 256-bit shuffles
7620 if (VT.is256BitVector())
7621 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7626 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7627 MVT VT = Op.getSimpleValueType();
7630 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7633 if (VT.getSizeInBits() == 8) {
7634 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7635 Op.getOperand(0), Op.getOperand(1));
7636 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7637 DAG.getValueType(VT));
7638 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7641 if (VT.getSizeInBits() == 16) {
7642 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7643 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7645 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7646 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7647 DAG.getNode(ISD::BITCAST, dl,
7651 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7652 Op.getOperand(0), Op.getOperand(1));
7653 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7654 DAG.getValueType(VT));
7655 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7658 if (VT == MVT::f32) {
7659 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7660 // the result back to FR32 register. It's only worth matching if the
7661 // result has a single use which is a store or a bitcast to i32. And in
7662 // the case of a store, it's not worth it if the index is a constant 0,
7663 // because a MOVSSmr can be used instead, which is smaller and faster.
7664 if (!Op.hasOneUse())
7666 SDNode *User = *Op.getNode()->use_begin();
7667 if ((User->getOpcode() != ISD::STORE ||
7668 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7669 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7670 (User->getOpcode() != ISD::BITCAST ||
7671 User->getValueType(0) != MVT::i32))
7673 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7674 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7677 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7680 if (VT == MVT::i32 || VT == MVT::i64) {
7681 // ExtractPS/pextrq works with constant index.
7682 if (isa<ConstantSDNode>(Op.getOperand(1)))
7688 /// Extract one bit from mask vector, like v16i1 or v8i1.
7689 /// AVX-512 feature.
7690 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) {
7691 SDValue Vec = Op.getOperand(0);
7693 MVT VecVT = Vec.getSimpleValueType();
7694 SDValue Idx = Op.getOperand(1);
7695 MVT EltVT = Op.getSimpleValueType();
7697 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7699 // variable index can't be handled in mask registers,
7700 // extend vector to VR512
7701 if (!isa<ConstantSDNode>(Idx)) {
7702 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7703 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7704 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7705 ExtVT.getVectorElementType(), Ext, Idx);
7706 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7709 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7711 unsigned MaxSift = VecVT.getSizeInBits() - 1;
7712 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7713 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7714 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7715 DAG.getConstant(MaxSift, MVT::i8));
7717 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i1, Vec,
7718 DAG.getIntPtrConstant(0));
7722 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7723 SelectionDAG &DAG) const {
7725 SDValue Vec = Op.getOperand(0);
7726 MVT VecVT = Vec.getSimpleValueType();
7727 SDValue Idx = Op.getOperand(1);
7729 if (Op.getSimpleValueType() == MVT::i1)
7730 return ExtractBitFromMaskVector(Op, DAG);
7732 if (!isa<ConstantSDNode>(Idx)) {
7733 if (VecVT.is512BitVector() ||
7734 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7735 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7738 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7739 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7740 MaskEltVT.getSizeInBits());
7742 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7743 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7744 getZeroVector(MaskVT, Subtarget, DAG, dl),
7745 Idx, DAG.getConstant(0, getPointerTy()));
7746 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7747 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7748 Perm, DAG.getConstant(0, getPointerTy()));
7753 // If this is a 256-bit vector result, first extract the 128-bit vector and
7754 // then extract the element from the 128-bit vector.
7755 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7757 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7758 // Get the 128-bit vector.
7759 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7760 MVT EltVT = VecVT.getVectorElementType();
7762 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7764 //if (IdxVal >= NumElems/2)
7765 // IdxVal -= NumElems/2;
7766 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7767 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7768 DAG.getConstant(IdxVal, MVT::i32));
7771 assert(VecVT.is128BitVector() && "Unexpected vector length");
7773 if (Subtarget->hasSSE41()) {
7774 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7779 MVT VT = Op.getSimpleValueType();
7780 // TODO: handle v16i8.
7781 if (VT.getSizeInBits() == 16) {
7782 SDValue Vec = Op.getOperand(0);
7783 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7785 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7786 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7787 DAG.getNode(ISD::BITCAST, dl,
7790 // Transform it so it match pextrw which produces a 32-bit result.
7791 MVT EltVT = MVT::i32;
7792 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7793 Op.getOperand(0), Op.getOperand(1));
7794 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7795 DAG.getValueType(VT));
7796 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7799 if (VT.getSizeInBits() == 32) {
7800 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7804 // SHUFPS the element to the lowest double word, then movss.
7805 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7806 MVT VVT = Op.getOperand(0).getSimpleValueType();
7807 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7808 DAG.getUNDEF(VVT), Mask);
7809 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7810 DAG.getIntPtrConstant(0));
7813 if (VT.getSizeInBits() == 64) {
7814 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7815 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7816 // to match extract_elt for f64.
7817 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7821 // UNPCKHPD the element to the lowest double word, then movsd.
7822 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7823 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7824 int Mask[2] = { 1, -1 };
7825 MVT VVT = Op.getOperand(0).getSimpleValueType();
7826 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7827 DAG.getUNDEF(VVT), Mask);
7828 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7829 DAG.getIntPtrConstant(0));
7835 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7836 MVT VT = Op.getSimpleValueType();
7837 MVT EltVT = VT.getVectorElementType();
7840 SDValue N0 = Op.getOperand(0);
7841 SDValue N1 = Op.getOperand(1);
7842 SDValue N2 = Op.getOperand(2);
7844 if (!VT.is128BitVector())
7847 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7848 isa<ConstantSDNode>(N2)) {
7850 if (VT == MVT::v8i16)
7851 Opc = X86ISD::PINSRW;
7852 else if (VT == MVT::v16i8)
7853 Opc = X86ISD::PINSRB;
7855 Opc = X86ISD::PINSRB;
7857 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7859 if (N1.getValueType() != MVT::i32)
7860 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7861 if (N2.getValueType() != MVT::i32)
7862 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7863 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7866 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7867 // Bits [7:6] of the constant are the source select. This will always be
7868 // zero here. The DAG Combiner may combine an extract_elt index into these
7869 // bits. For example (insert (extract, 3), 2) could be matched by putting
7870 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7871 // Bits [5:4] of the constant are the destination select. This is the
7872 // value of the incoming immediate.
7873 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7874 // combine either bitwise AND or insert of float 0.0 to set these bits.
7875 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7876 // Create this as a scalar to vector..
7877 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7878 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7881 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7882 // PINSR* works with constant index.
7889 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7890 MVT VT = Op.getSimpleValueType();
7891 MVT EltVT = VT.getVectorElementType();
7894 SDValue N0 = Op.getOperand(0);
7895 SDValue N1 = Op.getOperand(1);
7896 SDValue N2 = Op.getOperand(2);
7898 // If this is a 256-bit vector result, first extract the 128-bit vector,
7899 // insert the element into the extracted half and then place it back.
7900 if (VT.is256BitVector() || VT.is512BitVector()) {
7901 if (!isa<ConstantSDNode>(N2))
7904 // Get the desired 128-bit vector half.
7905 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7906 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7908 // Insert the element into the desired half.
7909 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7910 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7912 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7913 DAG.getConstant(IdxIn128, MVT::i32));
7915 // Insert the changed part back to the 256-bit vector
7916 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7919 if (Subtarget->hasSSE41())
7920 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7922 if (EltVT == MVT::i8)
7925 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7926 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7927 // as its second argument.
7928 if (N1.getValueType() != MVT::i32)
7929 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7930 if (N2.getValueType() != MVT::i32)
7931 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7932 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7937 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7939 MVT OpVT = Op.getSimpleValueType();
7941 // If this is a 256-bit vector result, first insert into a 128-bit
7942 // vector and then insert into the 256-bit vector.
7943 if (!OpVT.is128BitVector()) {
7944 // Insert into a 128-bit vector.
7945 unsigned SizeFactor = OpVT.getSizeInBits()/128;
7946 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7947 OpVT.getVectorNumElements() / SizeFactor);
7949 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7951 // Insert the 128-bit vector.
7952 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7955 if (OpVT == MVT::v1i64 &&
7956 Op.getOperand(0).getValueType() == MVT::i64)
7957 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7959 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7960 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7961 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7962 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7965 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7966 // a simple subregister reference or explicit instructions to grab
7967 // upper bits of a vector.
7968 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7969 SelectionDAG &DAG) {
7971 SDValue In = Op.getOperand(0);
7972 SDValue Idx = Op.getOperand(1);
7973 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7974 MVT ResVT = Op.getSimpleValueType();
7975 MVT InVT = In.getSimpleValueType();
7977 if (Subtarget->hasFp256()) {
7978 if (ResVT.is128BitVector() &&
7979 (InVT.is256BitVector() || InVT.is512BitVector()) &&
7980 isa<ConstantSDNode>(Idx)) {
7981 return Extract128BitVector(In, IdxVal, DAG, dl);
7983 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7984 isa<ConstantSDNode>(Idx)) {
7985 return Extract256BitVector(In, IdxVal, DAG, dl);
7991 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7992 // simple superregister reference or explicit instructions to insert
7993 // the upper bits of a vector.
7994 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7995 SelectionDAG &DAG) {
7996 if (Subtarget->hasFp256()) {
7997 SDLoc dl(Op.getNode());
7998 SDValue Vec = Op.getNode()->getOperand(0);
7999 SDValue SubVec = Op.getNode()->getOperand(1);
8000 SDValue Idx = Op.getNode()->getOperand(2);
8002 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8003 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8004 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8005 isa<ConstantSDNode>(Idx)) {
8006 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8007 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8010 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8011 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8012 isa<ConstantSDNode>(Idx)) {
8013 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8014 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8020 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8021 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8022 // one of the above mentioned nodes. It has to be wrapped because otherwise
8023 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8024 // be used to form addressing mode. These wrapped nodes will be selected
8027 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8028 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8030 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8032 unsigned char OpFlag = 0;
8033 unsigned WrapperKind = X86ISD::Wrapper;
8034 CodeModel::Model M = getTargetMachine().getCodeModel();
8036 if (Subtarget->isPICStyleRIPRel() &&
8037 (M == CodeModel::Small || M == CodeModel::Kernel))
8038 WrapperKind = X86ISD::WrapperRIP;
8039 else if (Subtarget->isPICStyleGOT())
8040 OpFlag = X86II::MO_GOTOFF;
8041 else if (Subtarget->isPICStyleStubPIC())
8042 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8044 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8046 CP->getOffset(), OpFlag);
8048 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8049 // With PIC, the address is actually $g + Offset.
8051 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8052 DAG.getNode(X86ISD::GlobalBaseReg,
8053 SDLoc(), getPointerTy()),
8060 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8061 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8063 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8065 unsigned char OpFlag = 0;
8066 unsigned WrapperKind = X86ISD::Wrapper;
8067 CodeModel::Model M = getTargetMachine().getCodeModel();
8069 if (Subtarget->isPICStyleRIPRel() &&
8070 (M == CodeModel::Small || M == CodeModel::Kernel))
8071 WrapperKind = X86ISD::WrapperRIP;
8072 else if (Subtarget->isPICStyleGOT())
8073 OpFlag = X86II::MO_GOTOFF;
8074 else if (Subtarget->isPICStyleStubPIC())
8075 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8077 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8080 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8082 // With PIC, the address is actually $g + Offset.
8084 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8085 DAG.getNode(X86ISD::GlobalBaseReg,
8086 SDLoc(), getPointerTy()),
8093 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8094 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8096 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8098 unsigned char OpFlag = 0;
8099 unsigned WrapperKind = X86ISD::Wrapper;
8100 CodeModel::Model M = getTargetMachine().getCodeModel();
8102 if (Subtarget->isPICStyleRIPRel() &&
8103 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8104 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8105 OpFlag = X86II::MO_GOTPCREL;
8106 WrapperKind = X86ISD::WrapperRIP;
8107 } else if (Subtarget->isPICStyleGOT()) {
8108 OpFlag = X86II::MO_GOT;
8109 } else if (Subtarget->isPICStyleStubPIC()) {
8110 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8111 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8112 OpFlag = X86II::MO_DARWIN_NONLAZY;
8115 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8118 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8120 // With PIC, the address is actually $g + Offset.
8121 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8122 !Subtarget->is64Bit()) {
8123 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8124 DAG.getNode(X86ISD::GlobalBaseReg,
8125 SDLoc(), getPointerTy()),
8129 // For symbols that require a load from a stub to get the address, emit the
8131 if (isGlobalStubReference(OpFlag))
8132 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8133 MachinePointerInfo::getGOT(), false, false, false, 0);
8139 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8140 // Create the TargetBlockAddressAddress node.
8141 unsigned char OpFlags =
8142 Subtarget->ClassifyBlockAddressReference();
8143 CodeModel::Model M = getTargetMachine().getCodeModel();
8144 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8145 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8147 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8150 if (Subtarget->isPICStyleRIPRel() &&
8151 (M == CodeModel::Small || M == CodeModel::Kernel))
8152 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8154 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8156 // With PIC, the address is actually $g + Offset.
8157 if (isGlobalRelativeToPICBase(OpFlags)) {
8158 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8159 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8167 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8168 int64_t Offset, SelectionDAG &DAG) const {
8169 // Create the TargetGlobalAddress node, folding in the constant
8170 // offset if it is legal.
8171 unsigned char OpFlags =
8172 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8173 CodeModel::Model M = getTargetMachine().getCodeModel();
8175 if (OpFlags == X86II::MO_NO_FLAG &&
8176 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8177 // A direct static reference to a global.
8178 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8181 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8184 if (Subtarget->isPICStyleRIPRel() &&
8185 (M == CodeModel::Small || M == CodeModel::Kernel))
8186 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8188 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8190 // With PIC, the address is actually $g + Offset.
8191 if (isGlobalRelativeToPICBase(OpFlags)) {
8192 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8193 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8197 // For globals that require a load from a stub to get the address, emit the
8199 if (isGlobalStubReference(OpFlags))
8200 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8201 MachinePointerInfo::getGOT(), false, false, false, 0);
8203 // If there was a non-zero offset that we didn't fold, create an explicit
8206 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8207 DAG.getConstant(Offset, getPointerTy()));
8213 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8214 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8215 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8216 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8220 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8221 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8222 unsigned char OperandFlags, bool LocalDynamic = false) {
8223 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8224 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8226 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8227 GA->getValueType(0),
8231 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8235 SDValue Ops[] = { Chain, TGA, *InFlag };
8236 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8238 SDValue Ops[] = { Chain, TGA };
8239 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8242 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8243 MFI->setAdjustsStack(true);
8245 SDValue Flag = Chain.getValue(1);
8246 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8249 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8251 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8254 SDLoc dl(GA); // ? function entry point might be better
8255 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8256 DAG.getNode(X86ISD::GlobalBaseReg,
8257 SDLoc(), PtrVT), InFlag);
8258 InFlag = Chain.getValue(1);
8260 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8263 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8265 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8267 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8268 X86::RAX, X86II::MO_TLSGD);
8271 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8277 // Get the start address of the TLS block for this module.
8278 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8279 .getInfo<X86MachineFunctionInfo>();
8280 MFI->incNumLocalDynamicTLSAccesses();
8284 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8285 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8288 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8289 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8290 InFlag = Chain.getValue(1);
8291 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8292 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8295 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8299 unsigned char OperandFlags = X86II::MO_DTPOFF;
8300 unsigned WrapperKind = X86ISD::Wrapper;
8301 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8302 GA->getValueType(0),
8303 GA->getOffset(), OperandFlags);
8304 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8306 // Add x@dtpoff with the base.
8307 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8310 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8311 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8312 const EVT PtrVT, TLSModel::Model model,
8313 bool is64Bit, bool isPIC) {
8316 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8317 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8318 is64Bit ? 257 : 256));
8320 SDValue ThreadPointer =
8321 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8322 MachinePointerInfo(Ptr), false, false, false, 0);
8324 unsigned char OperandFlags = 0;
8325 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8327 unsigned WrapperKind = X86ISD::Wrapper;
8328 if (model == TLSModel::LocalExec) {
8329 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8330 } else if (model == TLSModel::InitialExec) {
8332 OperandFlags = X86II::MO_GOTTPOFF;
8333 WrapperKind = X86ISD::WrapperRIP;
8335 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8338 llvm_unreachable("Unexpected model");
8341 // emit "addl x@ntpoff,%eax" (local exec)
8342 // or "addl x@indntpoff,%eax" (initial exec)
8343 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8345 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8346 GA->getOffset(), OperandFlags);
8347 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8349 if (model == TLSModel::InitialExec) {
8350 if (isPIC && !is64Bit) {
8351 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8352 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8356 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8357 MachinePointerInfo::getGOT(), false, false, false, 0);
8360 // The address of the thread local variable is the add of the thread
8361 // pointer with the offset of the variable.
8362 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8366 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8368 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8369 const GlobalValue *GV = GA->getGlobal();
8371 if (Subtarget->isTargetELF()) {
8372 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8375 case TLSModel::GeneralDynamic:
8376 if (Subtarget->is64Bit())
8377 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8378 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8379 case TLSModel::LocalDynamic:
8380 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8381 Subtarget->is64Bit());
8382 case TLSModel::InitialExec:
8383 case TLSModel::LocalExec:
8384 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8385 Subtarget->is64Bit(),
8386 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8388 llvm_unreachable("Unknown TLS model.");
8391 if (Subtarget->isTargetDarwin()) {
8392 // Darwin only has one model of TLS. Lower to that.
8393 unsigned char OpFlag = 0;
8394 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8395 X86ISD::WrapperRIP : X86ISD::Wrapper;
8397 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8399 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8400 !Subtarget->is64Bit();
8402 OpFlag = X86II::MO_TLVP_PIC_BASE;
8404 OpFlag = X86II::MO_TLVP;
8406 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8407 GA->getValueType(0),
8408 GA->getOffset(), OpFlag);
8409 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8411 // With PIC32, the address is actually $g + Offset.
8413 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8414 DAG.getNode(X86ISD::GlobalBaseReg,
8415 SDLoc(), getPointerTy()),
8418 // Lowering the machine isd will make sure everything is in the right
8420 SDValue Chain = DAG.getEntryNode();
8421 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8422 SDValue Args[] = { Chain, Offset };
8423 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8425 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8426 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8427 MFI->setAdjustsStack(true);
8429 // And our return value (tls address) is in the standard call return value
8431 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8432 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8436 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8437 // Just use the implicit TLS architecture
8438 // Need to generate someting similar to:
8439 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8441 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8442 // mov rcx, qword [rdx+rcx*8]
8443 // mov eax, .tls$:tlsvar
8444 // [rax+rcx] contains the address
8445 // Windows 64bit: gs:0x58
8446 // Windows 32bit: fs:__tls_array
8448 // If GV is an alias then use the aliasee for determining
8449 // thread-localness.
8450 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8451 GV = GA->resolveAliasedGlobal(false);
8453 SDValue Chain = DAG.getEntryNode();
8455 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8456 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8457 // use its literal value of 0x2C.
8458 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8459 ? Type::getInt8PtrTy(*DAG.getContext(),
8461 : Type::getInt32PtrTy(*DAG.getContext(),
8464 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8465 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8466 DAG.getExternalSymbol("_tls_array", getPointerTy()));
8468 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8469 MachinePointerInfo(Ptr),
8470 false, false, false, 0);
8472 // Load the _tls_index variable
8473 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8474 if (Subtarget->is64Bit())
8475 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8476 IDX, MachinePointerInfo(), MVT::i32,
8479 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8480 false, false, false, 0);
8482 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8484 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8486 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8487 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8488 false, false, false, 0);
8490 // Get the offset of start of .tls section
8491 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8492 GA->getValueType(0),
8493 GA->getOffset(), X86II::MO_SECREL);
8494 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8496 // The address of the thread local variable is the add of the thread
8497 // pointer with the offset of the variable.
8498 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8501 llvm_unreachable("TLS not implemented for this target.");
8504 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8505 /// and take a 2 x i32 value to shift plus a shift amount.
8506 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8507 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8508 EVT VT = Op.getValueType();
8509 unsigned VTBits = VT.getSizeInBits();
8511 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8512 SDValue ShOpLo = Op.getOperand(0);
8513 SDValue ShOpHi = Op.getOperand(1);
8514 SDValue ShAmt = Op.getOperand(2);
8515 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8516 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8518 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8519 DAG.getConstant(VTBits - 1, MVT::i8));
8520 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8521 DAG.getConstant(VTBits - 1, MVT::i8))
8522 : DAG.getConstant(0, VT);
8525 if (Op.getOpcode() == ISD::SHL_PARTS) {
8526 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8527 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8529 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8530 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8533 // If the shift amount is larger or equal than the width of a part we can't
8534 // rely on the results of shld/shrd. Insert a test and select the appropriate
8535 // values for large shift amounts.
8536 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8537 DAG.getConstant(VTBits, MVT::i8));
8538 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8539 AndNode, DAG.getConstant(0, MVT::i8));
8542 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8543 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8544 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8546 if (Op.getOpcode() == ISD::SHL_PARTS) {
8547 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8548 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8550 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8551 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8554 SDValue Ops[2] = { Lo, Hi };
8555 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8558 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8559 SelectionDAG &DAG) const {
8560 EVT SrcVT = Op.getOperand(0).getValueType();
8562 if (SrcVT.isVector())
8565 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8566 "Unknown SINT_TO_FP to lower!");
8568 // These are really Legal; return the operand so the caller accepts it as
8570 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8572 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8573 Subtarget->is64Bit()) {
8578 unsigned Size = SrcVT.getSizeInBits()/8;
8579 MachineFunction &MF = DAG.getMachineFunction();
8580 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8581 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8582 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8584 MachinePointerInfo::getFixedStack(SSFI),
8586 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8589 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8591 SelectionDAG &DAG) const {
8595 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8597 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8599 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8601 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8603 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8604 MachineMemOperand *MMO;
8606 int SSFI = FI->getIndex();
8608 DAG.getMachineFunction()
8609 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8610 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8612 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8613 StackSlot = StackSlot.getOperand(1);
8615 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8616 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8618 Tys, Ops, array_lengthof(Ops),
8622 Chain = Result.getValue(1);
8623 SDValue InFlag = Result.getValue(2);
8625 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8626 // shouldn't be necessary except that RFP cannot be live across
8627 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8628 MachineFunction &MF = DAG.getMachineFunction();
8629 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8630 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8631 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8632 Tys = DAG.getVTList(MVT::Other);
8634 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8636 MachineMemOperand *MMO =
8637 DAG.getMachineFunction()
8638 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8639 MachineMemOperand::MOStore, SSFISize, SSFISize);
8641 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8642 Ops, array_lengthof(Ops),
8643 Op.getValueType(), MMO);
8644 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8645 MachinePointerInfo::getFixedStack(SSFI),
8646 false, false, false, 0);
8652 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8653 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8654 SelectionDAG &DAG) const {
8655 // This algorithm is not obvious. Here it is what we're trying to output:
8658 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8659 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8663 pshufd $0x4e, %xmm0, %xmm1
8669 LLVMContext *Context = DAG.getContext();
8671 // Build some magic constants.
8672 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8673 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8674 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8676 SmallVector<Constant*,2> CV1;
8678 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8679 APInt(64, 0x4330000000000000ULL))));
8681 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8682 APInt(64, 0x4530000000000000ULL))));
8683 Constant *C1 = ConstantVector::get(CV1);
8684 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8686 // Load the 64-bit value into an XMM register.
8687 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8689 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8690 MachinePointerInfo::getConstantPool(),
8691 false, false, false, 16);
8692 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8693 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8696 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8697 MachinePointerInfo::getConstantPool(),
8698 false, false, false, 16);
8699 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8700 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8703 if (Subtarget->hasSSE3()) {
8704 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8705 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8707 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8708 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8710 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8711 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8715 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8716 DAG.getIntPtrConstant(0));
8719 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8720 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8721 SelectionDAG &DAG) const {
8723 // FP constant to bias correct the final result.
8724 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8727 // Load the 32-bit value into an XMM register.
8728 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8731 // Zero out the upper parts of the register.
8732 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8734 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8735 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8736 DAG.getIntPtrConstant(0));
8738 // Or the load with the bias.
8739 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8740 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8741 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8743 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8744 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8745 MVT::v2f64, Bias)));
8746 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8747 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8748 DAG.getIntPtrConstant(0));
8750 // Subtract the bias.
8751 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8753 // Handle final rounding.
8754 EVT DestVT = Op.getValueType();
8756 if (DestVT.bitsLT(MVT::f64))
8757 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8758 DAG.getIntPtrConstant(0));
8759 if (DestVT.bitsGT(MVT::f64))
8760 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8762 // Handle final rounding.
8766 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8767 SelectionDAG &DAG) const {
8768 SDValue N0 = Op.getOperand(0);
8769 EVT SVT = N0.getValueType();
8772 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8773 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8774 "Custom UINT_TO_FP is not supported!");
8776 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8777 SVT.getVectorNumElements());
8778 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8779 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8782 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8783 SelectionDAG &DAG) const {
8784 SDValue N0 = Op.getOperand(0);
8787 if (Op.getValueType().isVector())
8788 return lowerUINT_TO_FP_vec(Op, DAG);
8790 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8791 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8792 // the optimization here.
8793 if (DAG.SignBitIsZero(N0))
8794 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8796 EVT SrcVT = N0.getValueType();
8797 EVT DstVT = Op.getValueType();
8798 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8799 return LowerUINT_TO_FP_i64(Op, DAG);
8800 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8801 return LowerUINT_TO_FP_i32(Op, DAG);
8802 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8805 // Make a 64-bit buffer, and use it to build an FILD.
8806 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8807 if (SrcVT == MVT::i32) {
8808 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8809 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8810 getPointerTy(), StackSlot, WordOff);
8811 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8812 StackSlot, MachinePointerInfo(),
8814 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8815 OffsetSlot, MachinePointerInfo(),
8817 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8821 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8822 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8823 StackSlot, MachinePointerInfo(),
8825 // For i64 source, we need to add the appropriate power of 2 if the input
8826 // was negative. This is the same as the optimization in
8827 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8828 // we must be careful to do the computation in x87 extended precision, not
8829 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8830 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8831 MachineMemOperand *MMO =
8832 DAG.getMachineFunction()
8833 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8834 MachineMemOperand::MOLoad, 8, 8);
8836 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8837 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8838 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8839 array_lengthof(Ops), MVT::i64, MMO);
8841 APInt FF(32, 0x5F800000ULL);
8843 // Check whether the sign bit is set.
8844 SDValue SignSet = DAG.getSetCC(dl,
8845 getSetCCResultType(*DAG.getContext(), MVT::i64),
8846 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8849 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8850 SDValue FudgePtr = DAG.getConstantPool(
8851 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8854 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8855 SDValue Zero = DAG.getIntPtrConstant(0);
8856 SDValue Four = DAG.getIntPtrConstant(4);
8857 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8859 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8861 // Load the value out, extending it from f32 to f80.
8862 // FIXME: Avoid the extend by constructing the right constant pool?
8863 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8864 FudgePtr, MachinePointerInfo::getConstantPool(),
8865 MVT::f32, false, false, 4);
8866 // Extend everything to 80 bits to force it to be done on x87.
8867 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8868 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8871 std::pair<SDValue,SDValue>
8872 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8873 bool IsSigned, bool IsReplace) const {
8876 EVT DstTy = Op.getValueType();
8878 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8879 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8883 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8884 DstTy.getSimpleVT() >= MVT::i16 &&
8885 "Unknown FP_TO_INT to lower!");
8887 // These are really Legal.
8888 if (DstTy == MVT::i32 &&
8889 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8890 return std::make_pair(SDValue(), SDValue());
8891 if (Subtarget->is64Bit() &&
8892 DstTy == MVT::i64 &&
8893 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8894 return std::make_pair(SDValue(), SDValue());
8896 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8897 // stack slot, or into the FTOL runtime function.
8898 MachineFunction &MF = DAG.getMachineFunction();
8899 unsigned MemSize = DstTy.getSizeInBits()/8;
8900 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8901 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8904 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8905 Opc = X86ISD::WIN_FTOL;
8907 switch (DstTy.getSimpleVT().SimpleTy) {
8908 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8909 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8910 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8911 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8914 SDValue Chain = DAG.getEntryNode();
8915 SDValue Value = Op.getOperand(0);
8916 EVT TheVT = Op.getOperand(0).getValueType();
8917 // FIXME This causes a redundant load/store if the SSE-class value is already
8918 // in memory, such as if it is on the callstack.
8919 if (isScalarFPTypeInSSEReg(TheVT)) {
8920 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8921 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8922 MachinePointerInfo::getFixedStack(SSFI),
8924 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8926 Chain, StackSlot, DAG.getValueType(TheVT)
8929 MachineMemOperand *MMO =
8930 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8931 MachineMemOperand::MOLoad, MemSize, MemSize);
8932 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8933 array_lengthof(Ops), DstTy, MMO);
8934 Chain = Value.getValue(1);
8935 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8936 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8939 MachineMemOperand *MMO =
8940 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8941 MachineMemOperand::MOStore, MemSize, MemSize);
8943 if (Opc != X86ISD::WIN_FTOL) {
8944 // Build the FP_TO_INT*_IN_MEM
8945 SDValue Ops[] = { Chain, Value, StackSlot };
8946 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8947 Ops, array_lengthof(Ops), DstTy,
8949 return std::make_pair(FIST, StackSlot);
8951 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8952 DAG.getVTList(MVT::Other, MVT::Glue),
8954 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8955 MVT::i32, ftol.getValue(1));
8956 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8957 MVT::i32, eax.getValue(2));
8958 SDValue Ops[] = { eax, edx };
8959 SDValue pair = IsReplace
8960 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8961 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8962 return std::make_pair(pair, SDValue());
8966 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8967 const X86Subtarget *Subtarget) {
8968 MVT VT = Op->getSimpleValueType(0);
8969 SDValue In = Op->getOperand(0);
8970 MVT InVT = In.getSimpleValueType();
8973 // Optimize vectors in AVX mode:
8976 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8977 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8978 // Concat upper and lower parts.
8981 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8982 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8983 // Concat upper and lower parts.
8986 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
8987 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8988 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8991 if (Subtarget->hasInt256())
8992 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8994 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8995 SDValue Undef = DAG.getUNDEF(InVT);
8996 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8997 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8998 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9000 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9001 VT.getVectorNumElements()/2);
9003 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9004 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9006 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9009 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9010 SelectionDAG &DAG) {
9011 MVT VT = Op->getValueType(0).getSimpleVT();
9012 SDValue In = Op->getOperand(0);
9013 MVT InVT = In.getValueType().getSimpleVT();
9015 unsigned int NumElts = VT.getVectorNumElements();
9016 if (NumElts != 8 && NumElts != 16)
9019 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9020 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9022 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9023 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9024 // Now we have only mask extension
9025 assert(InVT.getVectorElementType() == MVT::i1);
9026 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9027 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9028 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9029 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9030 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9031 MachinePointerInfo::getConstantPool(),
9032 false, false, false, Alignment);
9034 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9035 if (VT.is512BitVector())
9037 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9040 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9041 SelectionDAG &DAG) {
9042 if (Subtarget->hasFp256()) {
9043 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9051 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9052 SelectionDAG &DAG) {
9054 MVT VT = Op.getSimpleValueType();
9055 SDValue In = Op.getOperand(0);
9056 MVT SVT = In.getSimpleValueType();
9058 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9059 return LowerZERO_EXTEND_AVX512(Op, DAG);
9061 if (Subtarget->hasFp256()) {
9062 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9067 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9068 VT.getVectorNumElements() != SVT.getVectorNumElements());
9072 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9074 MVT VT = Op.getSimpleValueType();
9075 SDValue In = Op.getOperand(0);
9076 MVT InVT = In.getSimpleValueType();
9078 if (VT == MVT::i1) {
9079 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9080 "Invalid scalar TRUNCATE operation");
9081 In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(1, InVT));
9082 if (InVT.getSizeInBits() == 64)
9083 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9084 else if (InVT.getSizeInBits() < 32)
9085 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9086 return DAG.getNode(X86ISD::TRUNC, DL, VT, In);
9088 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9089 "Invalid TRUNCATE operation");
9091 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9092 if (VT.getVectorElementType().getSizeInBits() >=8)
9093 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9095 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9096 unsigned NumElts = InVT.getVectorNumElements();
9097 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9098 if (InVT.getSizeInBits() < 512) {
9099 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9100 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9103 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9104 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9105 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9106 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9107 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9108 MachinePointerInfo::getConstantPool(),
9109 false, false, false, Alignment);
9110 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9111 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9112 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9115 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9116 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9117 if (Subtarget->hasInt256()) {
9118 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9119 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9120 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9122 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9123 DAG.getIntPtrConstant(0));
9126 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9127 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9128 DAG.getIntPtrConstant(0));
9129 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9130 DAG.getIntPtrConstant(2));
9132 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9133 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9136 static const int ShufMask1[] = {0, 2, 0, 0};
9137 SDValue Undef = DAG.getUNDEF(VT);
9138 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9139 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9141 // The MOVLHPS mask:
9142 static const int ShufMask2[] = {0, 1, 4, 5};
9143 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9146 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9147 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9148 if (Subtarget->hasInt256()) {
9149 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9151 SmallVector<SDValue,32> pshufbMask;
9152 for (unsigned i = 0; i < 2; ++i) {
9153 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9154 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9155 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9156 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9157 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9158 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9159 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9160 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9161 for (unsigned j = 0; j < 8; ++j)
9162 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9164 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9165 &pshufbMask[0], 32);
9166 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9167 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9169 static const int ShufMask[] = {0, 2, -1, -1};
9170 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9172 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9173 DAG.getIntPtrConstant(0));
9174 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9177 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9178 DAG.getIntPtrConstant(0));
9180 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9181 DAG.getIntPtrConstant(4));
9183 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9184 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9187 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9188 -1, -1, -1, -1, -1, -1, -1, -1};
9190 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9191 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9192 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9194 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9195 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9197 // The MOVLHPS Mask:
9198 static const int ShufMask2[] = {0, 1, 4, 5};
9199 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9200 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9203 // Handle truncation of V256 to V128 using shuffles.
9204 if (!VT.is128BitVector() || !InVT.is256BitVector())
9207 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9209 unsigned NumElems = VT.getVectorNumElements();
9210 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9213 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9214 // Prepare truncation shuffle mask
9215 for (unsigned i = 0; i != NumElems; ++i)
9217 SDValue V = DAG.getVectorShuffle(NVT, DL,
9218 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9219 DAG.getUNDEF(NVT), &MaskVec[0]);
9220 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9221 DAG.getIntPtrConstant(0));
9224 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9225 SelectionDAG &DAG) const {
9226 MVT VT = Op.getSimpleValueType();
9227 if (VT.isVector()) {
9228 if (VT == MVT::v8i16)
9229 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9230 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9231 MVT::v8i32, Op.getOperand(0)));
9235 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9236 /*IsSigned=*/ true, /*IsReplace=*/ false);
9237 SDValue FIST = Vals.first, StackSlot = Vals.second;
9238 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9239 if (FIST.getNode() == 0) return Op;
9241 if (StackSlot.getNode())
9243 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9244 FIST, StackSlot, MachinePointerInfo(),
9245 false, false, false, 0);
9247 // The node is the result.
9251 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9252 SelectionDAG &DAG) const {
9253 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9254 /*IsSigned=*/ false, /*IsReplace=*/ false);
9255 SDValue FIST = Vals.first, StackSlot = Vals.second;
9256 assert(FIST.getNode() && "Unexpected failure");
9258 if (StackSlot.getNode())
9260 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9261 FIST, StackSlot, MachinePointerInfo(),
9262 false, false, false, 0);
9264 // The node is the result.
9268 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9270 MVT VT = Op.getSimpleValueType();
9271 SDValue In = Op.getOperand(0);
9272 MVT SVT = In.getSimpleValueType();
9274 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9276 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9277 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9278 In, DAG.getUNDEF(SVT)));
9281 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9282 LLVMContext *Context = DAG.getContext();
9284 MVT VT = Op.getSimpleValueType();
9286 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9287 if (VT.isVector()) {
9288 EltVT = VT.getVectorElementType();
9289 NumElts = VT.getVectorNumElements();
9292 if (EltVT == MVT::f64)
9293 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9294 APInt(64, ~(1ULL << 63))));
9296 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9297 APInt(32, ~(1U << 31))));
9298 C = ConstantVector::getSplat(NumElts, C);
9299 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9300 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9301 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9302 MachinePointerInfo::getConstantPool(),
9303 false, false, false, Alignment);
9304 if (VT.isVector()) {
9305 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9306 return DAG.getNode(ISD::BITCAST, dl, VT,
9307 DAG.getNode(ISD::AND, dl, ANDVT,
9308 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9310 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9312 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9315 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9316 LLVMContext *Context = DAG.getContext();
9318 MVT VT = Op.getSimpleValueType();
9320 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9321 if (VT.isVector()) {
9322 EltVT = VT.getVectorElementType();
9323 NumElts = VT.getVectorNumElements();
9326 if (EltVT == MVT::f64)
9327 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9328 APInt(64, 1ULL << 63)));
9330 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9331 APInt(32, 1U << 31)));
9332 C = ConstantVector::getSplat(NumElts, C);
9333 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9334 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9335 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9336 MachinePointerInfo::getConstantPool(),
9337 false, false, false, Alignment);
9338 if (VT.isVector()) {
9339 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9340 return DAG.getNode(ISD::BITCAST, dl, VT,
9341 DAG.getNode(ISD::XOR, dl, XORVT,
9342 DAG.getNode(ISD::BITCAST, dl, XORVT,
9344 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9347 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9350 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9351 LLVMContext *Context = DAG.getContext();
9352 SDValue Op0 = Op.getOperand(0);
9353 SDValue Op1 = Op.getOperand(1);
9355 MVT VT = Op.getSimpleValueType();
9356 MVT SrcVT = Op1.getSimpleValueType();
9358 // If second operand is smaller, extend it first.
9359 if (SrcVT.bitsLT(VT)) {
9360 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9363 // And if it is bigger, shrink it first.
9364 if (SrcVT.bitsGT(VT)) {
9365 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9369 // At this point the operands and the result should have the same
9370 // type, and that won't be f80 since that is not custom lowered.
9372 // First get the sign bit of second operand.
9373 SmallVector<Constant*,4> CV;
9374 if (SrcVT == MVT::f64) {
9375 const fltSemantics &Sem = APFloat::IEEEdouble;
9376 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9377 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9379 const fltSemantics &Sem = APFloat::IEEEsingle;
9380 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9381 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9382 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9383 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9385 Constant *C = ConstantVector::get(CV);
9386 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9387 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9388 MachinePointerInfo::getConstantPool(),
9389 false, false, false, 16);
9390 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9392 // Shift sign bit right or left if the two operands have different types.
9393 if (SrcVT.bitsGT(VT)) {
9394 // Op0 is MVT::f32, Op1 is MVT::f64.
9395 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9396 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9397 DAG.getConstant(32, MVT::i32));
9398 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9399 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9400 DAG.getIntPtrConstant(0));
9403 // Clear first operand sign bit.
9405 if (VT == MVT::f64) {
9406 const fltSemantics &Sem = APFloat::IEEEdouble;
9407 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9408 APInt(64, ~(1ULL << 63)))));
9409 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9411 const fltSemantics &Sem = APFloat::IEEEsingle;
9412 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9413 APInt(32, ~(1U << 31)))));
9414 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9415 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9416 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9418 C = ConstantVector::get(CV);
9419 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9420 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9421 MachinePointerInfo::getConstantPool(),
9422 false, false, false, 16);
9423 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9425 // Or the value with the sign bit.
9426 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9429 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9430 SDValue N0 = Op.getOperand(0);
9432 MVT VT = Op.getSimpleValueType();
9434 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9435 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9436 DAG.getConstant(1, VT));
9437 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9440 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9442 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9443 SelectionDAG &DAG) {
9444 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9446 if (!Subtarget->hasSSE41())
9449 if (!Op->hasOneUse())
9452 SDNode *N = Op.getNode();
9455 SmallVector<SDValue, 8> Opnds;
9456 DenseMap<SDValue, unsigned> VecInMap;
9457 EVT VT = MVT::Other;
9459 // Recognize a special case where a vector is casted into wide integer to
9461 Opnds.push_back(N->getOperand(0));
9462 Opnds.push_back(N->getOperand(1));
9464 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9465 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9466 // BFS traverse all OR'd operands.
9467 if (I->getOpcode() == ISD::OR) {
9468 Opnds.push_back(I->getOperand(0));
9469 Opnds.push_back(I->getOperand(1));
9470 // Re-evaluate the number of nodes to be traversed.
9471 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9475 // Quit if a non-EXTRACT_VECTOR_ELT
9476 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9479 // Quit if without a constant index.
9480 SDValue Idx = I->getOperand(1);
9481 if (!isa<ConstantSDNode>(Idx))
9484 SDValue ExtractedFromVec = I->getOperand(0);
9485 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9486 if (M == VecInMap.end()) {
9487 VT = ExtractedFromVec.getValueType();
9488 // Quit if not 128/256-bit vector.
9489 if (!VT.is128BitVector() && !VT.is256BitVector())
9491 // Quit if not the same type.
9492 if (VecInMap.begin() != VecInMap.end() &&
9493 VT != VecInMap.begin()->first.getValueType())
9495 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9497 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9500 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9501 "Not extracted from 128-/256-bit vector.");
9503 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9504 SmallVector<SDValue, 8> VecIns;
9506 for (DenseMap<SDValue, unsigned>::const_iterator
9507 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9508 // Quit if not all elements are used.
9509 if (I->second != FullMask)
9511 VecIns.push_back(I->first);
9514 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9516 // Cast all vectors into TestVT for PTEST.
9517 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9518 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9520 // If more than one full vectors are evaluated, OR them first before PTEST.
9521 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9522 // Each iteration will OR 2 nodes and append the result until there is only
9523 // 1 node left, i.e. the final OR'd value of all vectors.
9524 SDValue LHS = VecIns[Slot];
9525 SDValue RHS = VecIns[Slot + 1];
9526 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9529 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9530 VecIns.back(), VecIns.back());
9533 /// Emit nodes that will be selected as "test Op0,Op0", or something
9535 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9536 SelectionDAG &DAG) const {
9539 // CF and OF aren't always set the way we want. Determine which
9540 // of these we need.
9541 bool NeedCF = false;
9542 bool NeedOF = false;
9545 case X86::COND_A: case X86::COND_AE:
9546 case X86::COND_B: case X86::COND_BE:
9549 case X86::COND_G: case X86::COND_GE:
9550 case X86::COND_L: case X86::COND_LE:
9551 case X86::COND_O: case X86::COND_NO:
9556 // See if we can use the EFLAGS value from the operand instead of
9557 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9558 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9559 if (Op.getResNo() != 0 || NeedOF || NeedCF)
9560 // Emit a CMP with 0, which is the TEST pattern.
9561 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9562 DAG.getConstant(0, Op.getValueType()));
9564 unsigned Opcode = 0;
9565 unsigned NumOperands = 0;
9567 // Truncate operations may prevent the merge of the SETCC instruction
9568 // and the arithmetic instruction before it. Attempt to truncate the operands
9569 // of the arithmetic instruction and use a reduced bit-width instruction.
9570 bool NeedTruncation = false;
9571 SDValue ArithOp = Op;
9572 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9573 SDValue Arith = Op->getOperand(0);
9574 // Both the trunc and the arithmetic op need to have one user each.
9575 if (Arith->hasOneUse())
9576 switch (Arith.getOpcode()) {
9583 NeedTruncation = true;
9589 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9590 // which may be the result of a CAST. We use the variable 'Op', which is the
9591 // non-casted variable when we check for possible users.
9592 switch (ArithOp.getOpcode()) {
9594 // Due to an isel shortcoming, be conservative if this add is likely to be
9595 // selected as part of a load-modify-store instruction. When the root node
9596 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9597 // uses of other nodes in the match, such as the ADD in this case. This
9598 // leads to the ADD being left around and reselected, with the result being
9599 // two adds in the output. Alas, even if none our users are stores, that
9600 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9601 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9602 // climbing the DAG back to the root, and it doesn't seem to be worth the
9604 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9605 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9606 if (UI->getOpcode() != ISD::CopyToReg &&
9607 UI->getOpcode() != ISD::SETCC &&
9608 UI->getOpcode() != ISD::STORE)
9611 if (ConstantSDNode *C =
9612 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9613 // An add of one will be selected as an INC.
9614 if (C->getAPIntValue() == 1) {
9615 Opcode = X86ISD::INC;
9620 // An add of negative one (subtract of one) will be selected as a DEC.
9621 if (C->getAPIntValue().isAllOnesValue()) {
9622 Opcode = X86ISD::DEC;
9628 // Otherwise use a regular EFLAGS-setting add.
9629 Opcode = X86ISD::ADD;
9633 // If the primary and result isn't used, don't bother using X86ISD::AND,
9634 // because a TEST instruction will be better.
9635 bool NonFlagUse = false;
9636 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9637 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9639 unsigned UOpNo = UI.getOperandNo();
9640 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9641 // Look pass truncate.
9642 UOpNo = User->use_begin().getOperandNo();
9643 User = *User->use_begin();
9646 if (User->getOpcode() != ISD::BRCOND &&
9647 User->getOpcode() != ISD::SETCC &&
9648 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9661 // Due to the ISEL shortcoming noted above, be conservative if this op is
9662 // likely to be selected as part of a load-modify-store instruction.
9663 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9664 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9665 if (UI->getOpcode() == ISD::STORE)
9668 // Otherwise use a regular EFLAGS-setting instruction.
9669 switch (ArithOp.getOpcode()) {
9670 default: llvm_unreachable("unexpected operator!");
9671 case ISD::SUB: Opcode = X86ISD::SUB; break;
9672 case ISD::XOR: Opcode = X86ISD::XOR; break;
9673 case ISD::AND: Opcode = X86ISD::AND; break;
9675 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9676 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9677 if (EFLAGS.getNode())
9680 Opcode = X86ISD::OR;
9694 return SDValue(Op.getNode(), 1);
9700 // If we found that truncation is beneficial, perform the truncation and
9702 if (NeedTruncation) {
9703 EVT VT = Op.getValueType();
9704 SDValue WideVal = Op->getOperand(0);
9705 EVT WideVT = WideVal.getValueType();
9706 unsigned ConvertedOp = 0;
9707 // Use a target machine opcode to prevent further DAGCombine
9708 // optimizations that may separate the arithmetic operations
9709 // from the setcc node.
9710 switch (WideVal.getOpcode()) {
9712 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9713 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9714 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9715 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9716 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9720 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9721 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9722 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9723 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9724 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9730 // Emit a CMP with 0, which is the TEST pattern.
9731 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9732 DAG.getConstant(0, Op.getValueType()));
9734 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9735 SmallVector<SDValue, 4> Ops;
9736 for (unsigned i = 0; i != NumOperands; ++i)
9737 Ops.push_back(Op.getOperand(i));
9739 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9740 DAG.ReplaceAllUsesWith(Op, New);
9741 return SDValue(New.getNode(), 1);
9744 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9746 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9747 SelectionDAG &DAG) const {
9749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9750 if (C->getAPIntValue() == 0)
9751 return EmitTest(Op0, X86CC, DAG);
9753 if (Op0.getValueType() == MVT::i1) {
9754 Op0 = DAG.getNode(ISD::XOR, dl, MVT::i1, Op0, DAG.getConstant(-1, MVT::i1));
9755 return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op0, Op0);
9759 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9760 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9761 // Do the comparison at i32 if it's smaller. This avoids subregister
9762 // aliasing issues. Keep the smaller reference if we're optimizing for
9763 // size, however, as that'll allow better folding of memory operations.
9764 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9765 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9766 AttributeSet::FunctionIndex, Attribute::MinSize)) {
9768 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9769 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9770 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9772 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9773 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9774 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9776 return SDValue(Sub.getNode(), 1);
9778 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9781 /// Convert a comparison if required by the subtarget.
9782 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9783 SelectionDAG &DAG) const {
9784 // If the subtarget does not support the FUCOMI instruction, floating-point
9785 // comparisons have to be converted.
9786 if (Subtarget->hasCMov() ||
9787 Cmp.getOpcode() != X86ISD::CMP ||
9788 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9789 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9792 // The instruction selector will select an FUCOM instruction instead of
9793 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9794 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9795 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9797 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9798 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9799 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9800 DAG.getConstant(8, MVT::i8));
9801 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9802 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9805 static bool isAllOnes(SDValue V) {
9806 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9807 return C && C->isAllOnesValue();
9810 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9811 /// if it's possible.
9812 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9813 SDLoc dl, SelectionDAG &DAG) const {
9814 SDValue Op0 = And.getOperand(0);
9815 SDValue Op1 = And.getOperand(1);
9816 if (Op0.getOpcode() == ISD::TRUNCATE)
9817 Op0 = Op0.getOperand(0);
9818 if (Op1.getOpcode() == ISD::TRUNCATE)
9819 Op1 = Op1.getOperand(0);
9822 if (Op1.getOpcode() == ISD::SHL)
9823 std::swap(Op0, Op1);
9824 if (Op0.getOpcode() == ISD::SHL) {
9825 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9826 if (And00C->getZExtValue() == 1) {
9827 // If we looked past a truncate, check that it's only truncating away
9829 unsigned BitWidth = Op0.getValueSizeInBits();
9830 unsigned AndBitWidth = And.getValueSizeInBits();
9831 if (BitWidth > AndBitWidth) {
9833 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9834 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9838 RHS = Op0.getOperand(1);
9840 } else if (Op1.getOpcode() == ISD::Constant) {
9841 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9842 uint64_t AndRHSVal = AndRHS->getZExtValue();
9843 SDValue AndLHS = Op0;
9845 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9846 LHS = AndLHS.getOperand(0);
9847 RHS = AndLHS.getOperand(1);
9850 // Use BT if the immediate can't be encoded in a TEST instruction.
9851 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9853 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9857 if (LHS.getNode()) {
9858 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9859 // instruction. Since the shift amount is in-range-or-undefined, we know
9860 // that doing a bittest on the i32 value is ok. We extend to i32 because
9861 // the encoding for the i16 version is larger than the i32 version.
9862 // Also promote i16 to i32 for performance / code size reason.
9863 if (LHS.getValueType() == MVT::i8 ||
9864 LHS.getValueType() == MVT::i16)
9865 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9867 // If the operand types disagree, extend the shift amount to match. Since
9868 // BT ignores high bits (like shifts) we can use anyextend.
9869 if (LHS.getValueType() != RHS.getValueType())
9870 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9872 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9873 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9874 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9875 DAG.getConstant(Cond, MVT::i8), BT);
9881 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9883 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9888 // SSE Condition code mapping:
9897 switch (SetCCOpcode) {
9898 default: llvm_unreachable("Unexpected SETCC condition");
9900 case ISD::SETEQ: SSECC = 0; break;
9902 case ISD::SETGT: Swap = true; // Fallthrough
9904 case ISD::SETOLT: SSECC = 1; break;
9906 case ISD::SETGE: Swap = true; // Fallthrough
9908 case ISD::SETOLE: SSECC = 2; break;
9909 case ISD::SETUO: SSECC = 3; break;
9911 case ISD::SETNE: SSECC = 4; break;
9912 case ISD::SETULE: Swap = true; // Fallthrough
9913 case ISD::SETUGE: SSECC = 5; break;
9914 case ISD::SETULT: Swap = true; // Fallthrough
9915 case ISD::SETUGT: SSECC = 6; break;
9916 case ISD::SETO: SSECC = 7; break;
9918 case ISD::SETONE: SSECC = 8; break;
9921 std::swap(Op0, Op1);
9926 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9927 // ones, and then concatenate the result back.
9928 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9929 MVT VT = Op.getSimpleValueType();
9931 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9932 "Unsupported value type for operation");
9934 unsigned NumElems = VT.getVectorNumElements();
9936 SDValue CC = Op.getOperand(2);
9938 // Extract the LHS vectors
9939 SDValue LHS = Op.getOperand(0);
9940 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9941 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9943 // Extract the RHS vectors
9944 SDValue RHS = Op.getOperand(1);
9945 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9946 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9948 // Issue the operation on the smaller types and concatenate the result back
9949 MVT EltVT = VT.getVectorElementType();
9950 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9951 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9952 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9953 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9956 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9957 SDValue Op0 = Op.getOperand(0);
9958 SDValue Op1 = Op.getOperand(1);
9959 SDValue CC = Op.getOperand(2);
9960 MVT VT = Op.getSimpleValueType();
9962 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9963 Op.getValueType().getScalarType() == MVT::i1 &&
9964 "Cannot set masked compare for this operation");
9966 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9969 bool Unsigned = false;
9971 switch (SetCCOpcode) {
9972 default: llvm_unreachable("Unexpected SETCC condition");
9973 case ISD::SETNE: SSECC = 4; break;
9974 case ISD::SETEQ: SSECC = 0; break;
9975 case ISD::SETUGT: Unsigned = true;
9976 case ISD::SETGT: SSECC = 6; break; // NLE
9977 case ISD::SETULT: Unsigned = true;
9978 case ISD::SETLT: SSECC = 1; break;
9979 case ISD::SETUGE: Unsigned = true;
9980 case ISD::SETGE: SSECC = 5; break; // NLT
9981 case ISD::SETULE: Unsigned = true;
9982 case ISD::SETLE: SSECC = 2; break;
9984 unsigned Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9985 return DAG.getNode(Opc, dl, VT, Op0, Op1,
9986 DAG.getConstant(SSECC, MVT::i8));
9990 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9991 SelectionDAG &DAG) {
9992 SDValue Op0 = Op.getOperand(0);
9993 SDValue Op1 = Op.getOperand(1);
9994 SDValue CC = Op.getOperand(2);
9995 MVT VT = Op.getSimpleValueType();
9996 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9997 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10002 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10003 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10006 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10007 unsigned Opc = X86ISD::CMPP;
10008 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10009 assert(VT.getVectorNumElements() <= 16);
10010 Opc = X86ISD::CMPM;
10012 // In the two special cases we can't handle, emit two comparisons.
10015 unsigned CombineOpc;
10016 if (SetCCOpcode == ISD::SETUEQ) {
10017 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10019 assert(SetCCOpcode == ISD::SETONE);
10020 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10023 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10024 DAG.getConstant(CC0, MVT::i8));
10025 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10026 DAG.getConstant(CC1, MVT::i8));
10027 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10029 // Handle all other FP comparisons here.
10030 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10031 DAG.getConstant(SSECC, MVT::i8));
10034 // Break 256-bit integer vector compare into smaller ones.
10035 if (VT.is256BitVector() && !Subtarget->hasInt256())
10036 return Lower256IntVSETCC(Op, DAG);
10038 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10039 EVT OpVT = Op1.getValueType();
10040 if (Subtarget->hasAVX512()) {
10041 if (Op1.getValueType().is512BitVector() ||
10042 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10043 return LowerIntVSETCC_AVX512(Op, DAG);
10045 // In AVX-512 architecture setcc returns mask with i1 elements,
10046 // But there is no compare instruction for i8 and i16 elements.
10047 // We are not talking about 512-bit operands in this case, these
10048 // types are illegal.
10050 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10051 OpVT.getVectorElementType().getSizeInBits() >= 8))
10052 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10053 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10056 // We are handling one of the integer comparisons here. Since SSE only has
10057 // GT and EQ comparisons for integer, swapping operands and multiple
10058 // operations may be required for some comparisons.
10060 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10062 switch (SetCCOpcode) {
10063 default: llvm_unreachable("Unexpected SETCC condition");
10064 case ISD::SETNE: Invert = true;
10065 case ISD::SETEQ: Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
10066 case ISD::SETLT: Swap = true;
10067 case ISD::SETGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
10068 case ISD::SETGE: Swap = true;
10069 case ISD::SETLE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10070 Invert = true; break;
10071 case ISD::SETULT: Swap = true;
10072 case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10073 FlipSigns = true; break;
10074 case ISD::SETUGE: Swap = true;
10075 case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10076 FlipSigns = true; Invert = true; break;
10079 // Special case: Use min/max operations for SETULE/SETUGE
10080 MVT VET = VT.getVectorElementType();
10082 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10083 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10086 switch (SetCCOpcode) {
10088 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10089 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10092 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10096 std::swap(Op0, Op1);
10098 // Check that the operation in question is available (most are plain SSE2,
10099 // but PCMPGTQ and PCMPEQQ have different requirements).
10100 if (VT == MVT::v2i64) {
10101 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10102 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10104 // First cast everything to the right type.
10105 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10106 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10108 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10109 // bits of the inputs before performing those operations. The lower
10110 // compare is always unsigned.
10113 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10115 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10116 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10117 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10118 Sign, Zero, Sign, Zero);
10120 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10121 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10123 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10124 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10125 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10127 // Create masks for only the low parts/high parts of the 64 bit integers.
10128 static const int MaskHi[] = { 1, 1, 3, 3 };
10129 static const int MaskLo[] = { 0, 0, 2, 2 };
10130 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10131 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10132 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10134 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10135 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10138 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10140 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10143 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10144 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10145 // pcmpeqd + pshufd + pand.
10146 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10148 // First cast everything to the right type.
10149 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10150 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10153 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10155 // Make sure the lower and upper halves are both all-ones.
10156 static const int Mask[] = { 1, 0, 3, 2 };
10157 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10158 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10161 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10163 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10167 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10168 // bits of the inputs before performing those operations.
10170 EVT EltVT = VT.getVectorElementType();
10171 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10172 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10173 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10176 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10178 // If the logical-not of the result is required, perform that now.
10180 Result = DAG.getNOT(dl, Result, VT);
10183 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10188 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10190 MVT VT = Op.getSimpleValueType();
10192 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10194 assert((VT == MVT::i8 || (Subtarget->hasAVX512() && VT == MVT::i1))
10195 && "SetCC type must be 8-bit or 1-bit integer");
10196 SDValue Op0 = Op.getOperand(0);
10197 SDValue Op1 = Op.getOperand(1);
10199 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10201 // Optimize to BT if possible.
10202 // Lower (X & (1 << N)) == 0 to BT(X, N).
10203 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10204 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10205 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10206 Op1.getOpcode() == ISD::Constant &&
10207 cast<ConstantSDNode>(Op1)->isNullValue() &&
10208 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10209 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10210 if (NewSetCC.getNode())
10214 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10216 if (Op1.getOpcode() == ISD::Constant &&
10217 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10218 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10219 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10221 // If the input is a setcc, then reuse the input setcc or use a new one with
10222 // the inverted condition.
10223 if (Op0.getOpcode() == X86ISD::SETCC) {
10224 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10225 bool Invert = (CC == ISD::SETNE) ^
10226 cast<ConstantSDNode>(Op1)->isNullValue();
10227 if (!Invert) return Op0;
10229 CCode = X86::GetOppositeBranchCondition(CCode);
10230 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10231 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
10235 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10236 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10237 if (X86CC == X86::COND_INVALID)
10240 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10241 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10242 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10243 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10246 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10247 static bool isX86LogicalCmp(SDValue Op) {
10248 unsigned Opc = Op.getNode()->getOpcode();
10249 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10250 Opc == X86ISD::SAHF)
10252 if (Op.getResNo() == 1 &&
10253 (Opc == X86ISD::ADD ||
10254 Opc == X86ISD::SUB ||
10255 Opc == X86ISD::ADC ||
10256 Opc == X86ISD::SBB ||
10257 Opc == X86ISD::SMUL ||
10258 Opc == X86ISD::UMUL ||
10259 Opc == X86ISD::INC ||
10260 Opc == X86ISD::DEC ||
10261 Opc == X86ISD::OR ||
10262 Opc == X86ISD::XOR ||
10263 Opc == X86ISD::AND))
10266 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10272 static bool isZero(SDValue V) {
10273 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10274 return C && C->isNullValue();
10277 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10278 if (V.getOpcode() != ISD::TRUNCATE)
10281 SDValue VOp0 = V.getOperand(0);
10282 unsigned InBits = VOp0.getValueSizeInBits();
10283 unsigned Bits = V.getValueSizeInBits();
10284 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10287 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10288 bool addTest = true;
10289 SDValue Cond = Op.getOperand(0);
10290 SDValue Op1 = Op.getOperand(1);
10291 SDValue Op2 = Op.getOperand(2);
10293 EVT VT = Op1.getValueType();
10296 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10297 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10298 // sequence later on.
10299 if (Cond.getOpcode() == ISD::SETCC &&
10300 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10301 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10302 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10303 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10304 int SSECC = translateX86FSETCC(
10305 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10308 if (Subtarget->hasAVX512()) {
10309 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10310 DAG.getConstant(SSECC, MVT::i8));
10311 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10313 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10314 DAG.getConstant(SSECC, MVT::i8));
10315 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10316 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10317 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10321 if (Cond.getOpcode() == ISD::SETCC) {
10322 SDValue NewCond = LowerSETCC(Cond, DAG);
10323 if (NewCond.getNode())
10327 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10328 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10329 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10330 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10331 if (Cond.getOpcode() == X86ISD::SETCC &&
10332 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10333 isZero(Cond.getOperand(1).getOperand(1))) {
10334 SDValue Cmp = Cond.getOperand(1);
10336 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10338 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10339 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10340 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10342 SDValue CmpOp0 = Cmp.getOperand(0);
10343 // Apply further optimizations for special cases
10344 // (select (x != 0), -1, 0) -> neg & sbb
10345 // (select (x == 0), 0, -1) -> neg & sbb
10346 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10347 if (YC->isNullValue() &&
10348 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10349 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10350 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10351 DAG.getConstant(0, CmpOp0.getValueType()),
10353 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10354 DAG.getConstant(X86::COND_B, MVT::i8),
10355 SDValue(Neg.getNode(), 1));
10359 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10360 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10361 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10363 SDValue Res = // Res = 0 or -1.
10364 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10365 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10367 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10368 Res = DAG.getNOT(DL, Res, Res.getValueType());
10370 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10371 if (N2C == 0 || !N2C->isNullValue())
10372 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10377 // Look past (and (setcc_carry (cmp ...)), 1).
10378 if (Cond.getOpcode() == ISD::AND &&
10379 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10380 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10381 if (C && C->getAPIntValue() == 1)
10382 Cond = Cond.getOperand(0);
10385 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10386 // setting operand in place of the X86ISD::SETCC.
10387 unsigned CondOpcode = Cond.getOpcode();
10388 if (CondOpcode == X86ISD::SETCC ||
10389 CondOpcode == X86ISD::SETCC_CARRY) {
10390 CC = Cond.getOperand(0);
10392 SDValue Cmp = Cond.getOperand(1);
10393 unsigned Opc = Cmp.getOpcode();
10394 MVT VT = Op.getSimpleValueType();
10396 bool IllegalFPCMov = false;
10397 if (VT.isFloatingPoint() && !VT.isVector() &&
10398 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10399 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10401 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10402 Opc == X86ISD::BT) { // FIXME
10406 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10407 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10408 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10409 Cond.getOperand(0).getValueType() != MVT::i8)) {
10410 SDValue LHS = Cond.getOperand(0);
10411 SDValue RHS = Cond.getOperand(1);
10412 unsigned X86Opcode;
10415 switch (CondOpcode) {
10416 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10417 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10418 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10419 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10420 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10421 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10422 default: llvm_unreachable("unexpected overflowing operator");
10424 if (CondOpcode == ISD::UMULO)
10425 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10428 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10430 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10432 if (CondOpcode == ISD::UMULO)
10433 Cond = X86Op.getValue(2);
10435 Cond = X86Op.getValue(1);
10437 CC = DAG.getConstant(X86Cond, MVT::i8);
10442 // Look pass the truncate if the high bits are known zero.
10443 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10444 Cond = Cond.getOperand(0);
10446 // We know the result of AND is compared against zero. Try to match
10448 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10449 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10450 if (NewSetCC.getNode()) {
10451 CC = NewSetCC.getOperand(0);
10452 Cond = NewSetCC.getOperand(1);
10459 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10460 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10463 // a < b ? -1 : 0 -> RES = ~setcc_carry
10464 // a < b ? 0 : -1 -> RES = setcc_carry
10465 // a >= b ? -1 : 0 -> RES = setcc_carry
10466 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10467 if (Cond.getOpcode() == X86ISD::SUB) {
10468 Cond = ConvertCmpIfNecessary(Cond, DAG);
10469 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10471 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10472 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10473 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10474 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10475 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10476 return DAG.getNOT(DL, Res, Res.getValueType());
10481 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10482 // widen the cmov and push the truncate through. This avoids introducing a new
10483 // branch during isel and doesn't add any extensions.
10484 if (Op.getValueType() == MVT::i8 &&
10485 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10486 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10487 if (T1.getValueType() == T2.getValueType() &&
10488 // Blacklist CopyFromReg to avoid partial register stalls.
10489 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10490 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10491 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10492 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10496 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10497 // condition is true.
10498 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10499 SDValue Ops[] = { Op2, Op1, CC, Cond };
10500 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10503 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10504 MVT VT = Op->getSimpleValueType(0);
10505 SDValue In = Op->getOperand(0);
10506 MVT InVT = In.getSimpleValueType();
10509 unsigned int NumElts = VT.getVectorNumElements();
10510 if (NumElts != 8 && NumElts != 16)
10513 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10514 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10516 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10517 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10519 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10520 Constant *C = ConstantInt::get(*DAG.getContext(),
10521 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10523 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10524 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10525 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10526 MachinePointerInfo::getConstantPool(),
10527 false, false, false, Alignment);
10528 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10529 if (VT.is512BitVector())
10531 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10534 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10535 SelectionDAG &DAG) {
10536 MVT VT = Op->getSimpleValueType(0);
10537 SDValue In = Op->getOperand(0);
10538 MVT InVT = In.getSimpleValueType();
10541 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10542 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10544 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10545 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10546 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10549 if (Subtarget->hasInt256())
10550 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10552 // Optimize vectors in AVX mode
10553 // Sign extend v8i16 to v8i32 and
10556 // Divide input vector into two parts
10557 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10558 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10559 // concat the vectors to original VT
10561 unsigned NumElems = InVT.getVectorNumElements();
10562 SDValue Undef = DAG.getUNDEF(InVT);
10564 SmallVector<int,8> ShufMask1(NumElems, -1);
10565 for (unsigned i = 0; i != NumElems/2; ++i)
10568 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10570 SmallVector<int,8> ShufMask2(NumElems, -1);
10571 for (unsigned i = 0; i != NumElems/2; ++i)
10572 ShufMask2[i] = i + NumElems/2;
10574 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10576 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10577 VT.getVectorNumElements()/2);
10579 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10580 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10582 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10585 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10586 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10587 // from the AND / OR.
10588 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10589 Opc = Op.getOpcode();
10590 if (Opc != ISD::OR && Opc != ISD::AND)
10592 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10593 Op.getOperand(0).hasOneUse() &&
10594 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10595 Op.getOperand(1).hasOneUse());
10598 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10599 // 1 and that the SETCC node has a single use.
10600 static bool isXor1OfSetCC(SDValue Op) {
10601 if (Op.getOpcode() != ISD::XOR)
10603 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10604 if (N1C && N1C->getAPIntValue() == 1) {
10605 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10606 Op.getOperand(0).hasOneUse();
10611 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10612 bool addTest = true;
10613 SDValue Chain = Op.getOperand(0);
10614 SDValue Cond = Op.getOperand(1);
10615 SDValue Dest = Op.getOperand(2);
10618 bool Inverted = false;
10620 if (Cond.getOpcode() == ISD::SETCC) {
10621 // Check for setcc([su]{add,sub,mul}o == 0).
10622 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10623 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10624 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10625 Cond.getOperand(0).getResNo() == 1 &&
10626 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10627 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10628 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10629 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10630 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10631 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10633 Cond = Cond.getOperand(0);
10635 SDValue NewCond = LowerSETCC(Cond, DAG);
10636 if (NewCond.getNode())
10641 // FIXME: LowerXALUO doesn't handle these!!
10642 else if (Cond.getOpcode() == X86ISD::ADD ||
10643 Cond.getOpcode() == X86ISD::SUB ||
10644 Cond.getOpcode() == X86ISD::SMUL ||
10645 Cond.getOpcode() == X86ISD::UMUL)
10646 Cond = LowerXALUO(Cond, DAG);
10649 // Look pass (and (setcc_carry (cmp ...)), 1).
10650 if (Cond.getOpcode() == ISD::AND &&
10651 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10652 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10653 if (C && C->getAPIntValue() == 1)
10654 Cond = Cond.getOperand(0);
10657 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10658 // setting operand in place of the X86ISD::SETCC.
10659 unsigned CondOpcode = Cond.getOpcode();
10660 if (CondOpcode == X86ISD::SETCC ||
10661 CondOpcode == X86ISD::SETCC_CARRY) {
10662 CC = Cond.getOperand(0);
10664 SDValue Cmp = Cond.getOperand(1);
10665 unsigned Opc = Cmp.getOpcode();
10666 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10667 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10671 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10675 // These can only come from an arithmetic instruction with overflow,
10676 // e.g. SADDO, UADDO.
10677 Cond = Cond.getNode()->getOperand(1);
10683 CondOpcode = Cond.getOpcode();
10684 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10685 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10686 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10687 Cond.getOperand(0).getValueType() != MVT::i8)) {
10688 SDValue LHS = Cond.getOperand(0);
10689 SDValue RHS = Cond.getOperand(1);
10690 unsigned X86Opcode;
10693 switch (CondOpcode) {
10694 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10695 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10696 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10697 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10698 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10699 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10700 default: llvm_unreachable("unexpected overflowing operator");
10703 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10704 if (CondOpcode == ISD::UMULO)
10705 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10708 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10710 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10712 if (CondOpcode == ISD::UMULO)
10713 Cond = X86Op.getValue(2);
10715 Cond = X86Op.getValue(1);
10717 CC = DAG.getConstant(X86Cond, MVT::i8);
10721 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10722 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10723 if (CondOpc == ISD::OR) {
10724 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10725 // two branches instead of an explicit OR instruction with a
10727 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10728 isX86LogicalCmp(Cmp)) {
10729 CC = Cond.getOperand(0).getOperand(0);
10730 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10731 Chain, Dest, CC, Cmp);
10732 CC = Cond.getOperand(1).getOperand(0);
10736 } else { // ISD::AND
10737 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10738 // two branches instead of an explicit AND instruction with a
10739 // separate test. However, we only do this if this block doesn't
10740 // have a fall-through edge, because this requires an explicit
10741 // jmp when the condition is false.
10742 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10743 isX86LogicalCmp(Cmp) &&
10744 Op.getNode()->hasOneUse()) {
10745 X86::CondCode CCode =
10746 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10747 CCode = X86::GetOppositeBranchCondition(CCode);
10748 CC = DAG.getConstant(CCode, MVT::i8);
10749 SDNode *User = *Op.getNode()->use_begin();
10750 // Look for an unconditional branch following this conditional branch.
10751 // We need this because we need to reverse the successors in order
10752 // to implement FCMP_OEQ.
10753 if (User->getOpcode() == ISD::BR) {
10754 SDValue FalseBB = User->getOperand(1);
10756 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10757 assert(NewBR == User);
10761 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10762 Chain, Dest, CC, Cmp);
10763 X86::CondCode CCode =
10764 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10765 CCode = X86::GetOppositeBranchCondition(CCode);
10766 CC = DAG.getConstant(CCode, MVT::i8);
10772 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10773 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10774 // It should be transformed during dag combiner except when the condition
10775 // is set by a arithmetics with overflow node.
10776 X86::CondCode CCode =
10777 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10778 CCode = X86::GetOppositeBranchCondition(CCode);
10779 CC = DAG.getConstant(CCode, MVT::i8);
10780 Cond = Cond.getOperand(0).getOperand(1);
10782 } else if (Cond.getOpcode() == ISD::SETCC &&
10783 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10784 // For FCMP_OEQ, we can emit
10785 // two branches instead of an explicit AND instruction with a
10786 // separate test. However, we only do this if this block doesn't
10787 // have a fall-through edge, because this requires an explicit
10788 // jmp when the condition is false.
10789 if (Op.getNode()->hasOneUse()) {
10790 SDNode *User = *Op.getNode()->use_begin();
10791 // Look for an unconditional branch following this conditional branch.
10792 // We need this because we need to reverse the successors in order
10793 // to implement FCMP_OEQ.
10794 if (User->getOpcode() == ISD::BR) {
10795 SDValue FalseBB = User->getOperand(1);
10797 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10798 assert(NewBR == User);
10802 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10803 Cond.getOperand(0), Cond.getOperand(1));
10804 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10805 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10806 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10807 Chain, Dest, CC, Cmp);
10808 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10813 } else if (Cond.getOpcode() == ISD::SETCC &&
10814 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10815 // For FCMP_UNE, we can emit
10816 // two branches instead of an explicit AND instruction with a
10817 // separate test. However, we only do this if this block doesn't
10818 // have a fall-through edge, because this requires an explicit
10819 // jmp when the condition is false.
10820 if (Op.getNode()->hasOneUse()) {
10821 SDNode *User = *Op.getNode()->use_begin();
10822 // Look for an unconditional branch following this conditional branch.
10823 // We need this because we need to reverse the successors in order
10824 // to implement FCMP_UNE.
10825 if (User->getOpcode() == ISD::BR) {
10826 SDValue FalseBB = User->getOperand(1);
10828 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10829 assert(NewBR == User);
10832 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10833 Cond.getOperand(0), Cond.getOperand(1));
10834 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10835 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10836 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10837 Chain, Dest, CC, Cmp);
10838 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10848 // Look pass the truncate if the high bits are known zero.
10849 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10850 Cond = Cond.getOperand(0);
10852 // We know the result of AND is compared against zero. Try to match
10854 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10855 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10856 if (NewSetCC.getNode()) {
10857 CC = NewSetCC.getOperand(0);
10858 Cond = NewSetCC.getOperand(1);
10865 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10866 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10868 Cond = ConvertCmpIfNecessary(Cond, DAG);
10869 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10870 Chain, Dest, CC, Cond);
10873 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10874 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10875 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10876 // that the guard pages used by the OS virtual memory manager are allocated in
10877 // correct sequence.
10879 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10880 SelectionDAG &DAG) const {
10881 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10882 getTargetMachine().Options.EnableSegmentedStacks) &&
10883 "This should be used only on Windows targets or when segmented stacks "
10885 assert(!Subtarget->isTargetMacho() && "Not implemented");
10889 SDValue Chain = Op.getOperand(0);
10890 SDValue Size = Op.getOperand(1);
10891 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10892 EVT VT = Op.getNode()->getValueType(0);
10894 bool Is64Bit = Subtarget->is64Bit();
10895 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10897 if (getTargetMachine().Options.EnableSegmentedStacks) {
10898 MachineFunction &MF = DAG.getMachineFunction();
10899 MachineRegisterInfo &MRI = MF.getRegInfo();
10902 // The 64 bit implementation of segmented stacks needs to clobber both r10
10903 // r11. This makes it impossible to use it along with nested parameters.
10904 const Function *F = MF.getFunction();
10906 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10908 if (I->hasNestAttr())
10909 report_fatal_error("Cannot use segmented stacks with functions that "
10910 "have nested arguments.");
10913 const TargetRegisterClass *AddrRegClass =
10914 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10915 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10916 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10917 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10918 DAG.getRegister(Vreg, SPTy));
10919 SDValue Ops1[2] = { Value, Chain };
10920 return DAG.getMergeValues(Ops1, 2, dl);
10923 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10925 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10926 Flag = Chain.getValue(1);
10927 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10929 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10931 const X86RegisterInfo *RegInfo =
10932 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10933 unsigned SPReg = RegInfo->getStackRegister();
10934 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
10935 Chain = SP.getValue(1);
10938 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10939 DAG.getConstant(-(uint64_t)Align, VT));
10940 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
10943 SDValue Ops1[2] = { SP, Chain };
10944 return DAG.getMergeValues(Ops1, 2, dl);
10948 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10949 MachineFunction &MF = DAG.getMachineFunction();
10950 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10952 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10955 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10956 // vastart just stores the address of the VarArgsFrameIndex slot into the
10957 // memory location argument.
10958 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10960 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10961 MachinePointerInfo(SV), false, false, 0);
10965 // gp_offset (0 - 6 * 8)
10966 // fp_offset (48 - 48 + 8 * 16)
10967 // overflow_arg_area (point to parameters coming in memory).
10969 SmallVector<SDValue, 8> MemOps;
10970 SDValue FIN = Op.getOperand(1);
10972 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10973 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10975 FIN, MachinePointerInfo(SV), false, false, 0);
10976 MemOps.push_back(Store);
10979 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10980 FIN, DAG.getIntPtrConstant(4));
10981 Store = DAG.getStore(Op.getOperand(0), DL,
10982 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10984 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10985 MemOps.push_back(Store);
10987 // Store ptr to overflow_arg_area
10988 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10989 FIN, DAG.getIntPtrConstant(4));
10990 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10992 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10993 MachinePointerInfo(SV, 8),
10995 MemOps.push_back(Store);
10997 // Store ptr to reg_save_area.
10998 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10999 FIN, DAG.getIntPtrConstant(8));
11000 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11002 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11003 MachinePointerInfo(SV, 16), false, false, 0);
11004 MemOps.push_back(Store);
11005 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11006 &MemOps[0], MemOps.size());
11009 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11010 assert(Subtarget->is64Bit() &&
11011 "LowerVAARG only handles 64-bit va_arg!");
11012 assert((Subtarget->isTargetLinux() ||
11013 Subtarget->isTargetDarwin()) &&
11014 "Unhandled target in LowerVAARG");
11015 assert(Op.getNode()->getNumOperands() == 4);
11016 SDValue Chain = Op.getOperand(0);
11017 SDValue SrcPtr = Op.getOperand(1);
11018 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11019 unsigned Align = Op.getConstantOperandVal(3);
11022 EVT ArgVT = Op.getNode()->getValueType(0);
11023 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11024 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11027 // Decide which area this value should be read from.
11028 // TODO: Implement the AMD64 ABI in its entirety. This simple
11029 // selection mechanism works only for the basic types.
11030 if (ArgVT == MVT::f80) {
11031 llvm_unreachable("va_arg for f80 not yet implemented");
11032 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11033 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11034 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11035 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11037 llvm_unreachable("Unhandled argument type in LowerVAARG");
11040 if (ArgMode == 2) {
11041 // Sanity Check: Make sure using fp_offset makes sense.
11042 assert(!getTargetMachine().Options.UseSoftFloat &&
11043 !(DAG.getMachineFunction()
11044 .getFunction()->getAttributes()
11045 .hasAttribute(AttributeSet::FunctionIndex,
11046 Attribute::NoImplicitFloat)) &&
11047 Subtarget->hasSSE1());
11050 // Insert VAARG_64 node into the DAG
11051 // VAARG_64 returns two values: Variable Argument Address, Chain
11052 SmallVector<SDValue, 11> InstOps;
11053 InstOps.push_back(Chain);
11054 InstOps.push_back(SrcPtr);
11055 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11056 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11057 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11058 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11059 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11060 VTs, &InstOps[0], InstOps.size(),
11062 MachinePointerInfo(SV),
11064 /*Volatile=*/false,
11066 /*WriteMem=*/true);
11067 Chain = VAARG.getValue(1);
11069 // Load the next argument and return it
11070 return DAG.getLoad(ArgVT, dl,
11073 MachinePointerInfo(),
11074 false, false, false, 0);
11077 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11078 SelectionDAG &DAG) {
11079 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11080 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11081 SDValue Chain = Op.getOperand(0);
11082 SDValue DstPtr = Op.getOperand(1);
11083 SDValue SrcPtr = Op.getOperand(2);
11084 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11085 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11088 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11089 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11091 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11094 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11095 // amount is a constant. Takes immediate version of shift as input.
11096 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, EVT VT,
11097 SDValue SrcOp, uint64_t ShiftAmt,
11098 SelectionDAG &DAG) {
11100 // Check for ShiftAmt >= element width
11101 if (ShiftAmt >= VT.getVectorElementType().getSizeInBits()) {
11102 if (Opc == X86ISD::VSRAI)
11103 ShiftAmt = VT.getVectorElementType().getSizeInBits() - 1;
11105 return DAG.getConstant(0, VT);
11108 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11109 && "Unknown target vector shift-by-constant node");
11111 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11114 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11115 // may or may not be a constant. Takes immediate version of shift as input.
11116 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
11117 SDValue SrcOp, SDValue ShAmt,
11118 SelectionDAG &DAG) {
11119 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11121 // Catch shift-by-constant.
11122 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11123 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11124 CShAmt->getZExtValue(), DAG);
11126 // Change opcode to non-immediate version
11128 default: llvm_unreachable("Unknown target vector shift node");
11129 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11130 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11131 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11134 // Need to build a vector containing shift amount
11135 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11138 ShOps[1] = DAG.getConstant(0, MVT::i32);
11139 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11140 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11142 // The return type has to be a 128-bit type with the same element
11143 // type as the input type.
11144 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11145 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11147 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11148 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11151 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11153 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11155 default: return SDValue(); // Don't custom lower most intrinsics.
11156 // Comparison intrinsics.
11157 case Intrinsic::x86_sse_comieq_ss:
11158 case Intrinsic::x86_sse_comilt_ss:
11159 case Intrinsic::x86_sse_comile_ss:
11160 case Intrinsic::x86_sse_comigt_ss:
11161 case Intrinsic::x86_sse_comige_ss:
11162 case Intrinsic::x86_sse_comineq_ss:
11163 case Intrinsic::x86_sse_ucomieq_ss:
11164 case Intrinsic::x86_sse_ucomilt_ss:
11165 case Intrinsic::x86_sse_ucomile_ss:
11166 case Intrinsic::x86_sse_ucomigt_ss:
11167 case Intrinsic::x86_sse_ucomige_ss:
11168 case Intrinsic::x86_sse_ucomineq_ss:
11169 case Intrinsic::x86_sse2_comieq_sd:
11170 case Intrinsic::x86_sse2_comilt_sd:
11171 case Intrinsic::x86_sse2_comile_sd:
11172 case Intrinsic::x86_sse2_comigt_sd:
11173 case Intrinsic::x86_sse2_comige_sd:
11174 case Intrinsic::x86_sse2_comineq_sd:
11175 case Intrinsic::x86_sse2_ucomieq_sd:
11176 case Intrinsic::x86_sse2_ucomilt_sd:
11177 case Intrinsic::x86_sse2_ucomile_sd:
11178 case Intrinsic::x86_sse2_ucomigt_sd:
11179 case Intrinsic::x86_sse2_ucomige_sd:
11180 case Intrinsic::x86_sse2_ucomineq_sd: {
11184 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11185 case Intrinsic::x86_sse_comieq_ss:
11186 case Intrinsic::x86_sse2_comieq_sd:
11187 Opc = X86ISD::COMI;
11190 case Intrinsic::x86_sse_comilt_ss:
11191 case Intrinsic::x86_sse2_comilt_sd:
11192 Opc = X86ISD::COMI;
11195 case Intrinsic::x86_sse_comile_ss:
11196 case Intrinsic::x86_sse2_comile_sd:
11197 Opc = X86ISD::COMI;
11200 case Intrinsic::x86_sse_comigt_ss:
11201 case Intrinsic::x86_sse2_comigt_sd:
11202 Opc = X86ISD::COMI;
11205 case Intrinsic::x86_sse_comige_ss:
11206 case Intrinsic::x86_sse2_comige_sd:
11207 Opc = X86ISD::COMI;
11210 case Intrinsic::x86_sse_comineq_ss:
11211 case Intrinsic::x86_sse2_comineq_sd:
11212 Opc = X86ISD::COMI;
11215 case Intrinsic::x86_sse_ucomieq_ss:
11216 case Intrinsic::x86_sse2_ucomieq_sd:
11217 Opc = X86ISD::UCOMI;
11220 case Intrinsic::x86_sse_ucomilt_ss:
11221 case Intrinsic::x86_sse2_ucomilt_sd:
11222 Opc = X86ISD::UCOMI;
11225 case Intrinsic::x86_sse_ucomile_ss:
11226 case Intrinsic::x86_sse2_ucomile_sd:
11227 Opc = X86ISD::UCOMI;
11230 case Intrinsic::x86_sse_ucomigt_ss:
11231 case Intrinsic::x86_sse2_ucomigt_sd:
11232 Opc = X86ISD::UCOMI;
11235 case Intrinsic::x86_sse_ucomige_ss:
11236 case Intrinsic::x86_sse2_ucomige_sd:
11237 Opc = X86ISD::UCOMI;
11240 case Intrinsic::x86_sse_ucomineq_ss:
11241 case Intrinsic::x86_sse2_ucomineq_sd:
11242 Opc = X86ISD::UCOMI;
11247 SDValue LHS = Op.getOperand(1);
11248 SDValue RHS = Op.getOperand(2);
11249 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11250 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11251 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11252 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11253 DAG.getConstant(X86CC, MVT::i8), Cond);
11254 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11257 // Arithmetic intrinsics.
11258 case Intrinsic::x86_sse2_pmulu_dq:
11259 case Intrinsic::x86_avx2_pmulu_dq:
11260 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11261 Op.getOperand(1), Op.getOperand(2));
11263 // SSE2/AVX2 sub with unsigned saturation intrinsics
11264 case Intrinsic::x86_sse2_psubus_b:
11265 case Intrinsic::x86_sse2_psubus_w:
11266 case Intrinsic::x86_avx2_psubus_b:
11267 case Intrinsic::x86_avx2_psubus_w:
11268 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11269 Op.getOperand(1), Op.getOperand(2));
11271 // SSE3/AVX horizontal add/sub intrinsics
11272 case Intrinsic::x86_sse3_hadd_ps:
11273 case Intrinsic::x86_sse3_hadd_pd:
11274 case Intrinsic::x86_avx_hadd_ps_256:
11275 case Intrinsic::x86_avx_hadd_pd_256:
11276 case Intrinsic::x86_sse3_hsub_ps:
11277 case Intrinsic::x86_sse3_hsub_pd:
11278 case Intrinsic::x86_avx_hsub_ps_256:
11279 case Intrinsic::x86_avx_hsub_pd_256:
11280 case Intrinsic::x86_ssse3_phadd_w_128:
11281 case Intrinsic::x86_ssse3_phadd_d_128:
11282 case Intrinsic::x86_avx2_phadd_w:
11283 case Intrinsic::x86_avx2_phadd_d:
11284 case Intrinsic::x86_ssse3_phsub_w_128:
11285 case Intrinsic::x86_ssse3_phsub_d_128:
11286 case Intrinsic::x86_avx2_phsub_w:
11287 case Intrinsic::x86_avx2_phsub_d: {
11290 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11291 case Intrinsic::x86_sse3_hadd_ps:
11292 case Intrinsic::x86_sse3_hadd_pd:
11293 case Intrinsic::x86_avx_hadd_ps_256:
11294 case Intrinsic::x86_avx_hadd_pd_256:
11295 Opcode = X86ISD::FHADD;
11297 case Intrinsic::x86_sse3_hsub_ps:
11298 case Intrinsic::x86_sse3_hsub_pd:
11299 case Intrinsic::x86_avx_hsub_ps_256:
11300 case Intrinsic::x86_avx_hsub_pd_256:
11301 Opcode = X86ISD::FHSUB;
11303 case Intrinsic::x86_ssse3_phadd_w_128:
11304 case Intrinsic::x86_ssse3_phadd_d_128:
11305 case Intrinsic::x86_avx2_phadd_w:
11306 case Intrinsic::x86_avx2_phadd_d:
11307 Opcode = X86ISD::HADD;
11309 case Intrinsic::x86_ssse3_phsub_w_128:
11310 case Intrinsic::x86_ssse3_phsub_d_128:
11311 case Intrinsic::x86_avx2_phsub_w:
11312 case Intrinsic::x86_avx2_phsub_d:
11313 Opcode = X86ISD::HSUB;
11316 return DAG.getNode(Opcode, dl, Op.getValueType(),
11317 Op.getOperand(1), Op.getOperand(2));
11320 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11321 case Intrinsic::x86_sse2_pmaxu_b:
11322 case Intrinsic::x86_sse41_pmaxuw:
11323 case Intrinsic::x86_sse41_pmaxud:
11324 case Intrinsic::x86_avx2_pmaxu_b:
11325 case Intrinsic::x86_avx2_pmaxu_w:
11326 case Intrinsic::x86_avx2_pmaxu_d:
11327 case Intrinsic::x86_avx512_pmaxu_d:
11328 case Intrinsic::x86_avx512_pmaxu_q:
11329 case Intrinsic::x86_sse2_pminu_b:
11330 case Intrinsic::x86_sse41_pminuw:
11331 case Intrinsic::x86_sse41_pminud:
11332 case Intrinsic::x86_avx2_pminu_b:
11333 case Intrinsic::x86_avx2_pminu_w:
11334 case Intrinsic::x86_avx2_pminu_d:
11335 case Intrinsic::x86_avx512_pminu_d:
11336 case Intrinsic::x86_avx512_pminu_q:
11337 case Intrinsic::x86_sse41_pmaxsb:
11338 case Intrinsic::x86_sse2_pmaxs_w:
11339 case Intrinsic::x86_sse41_pmaxsd:
11340 case Intrinsic::x86_avx2_pmaxs_b:
11341 case Intrinsic::x86_avx2_pmaxs_w:
11342 case Intrinsic::x86_avx2_pmaxs_d:
11343 case Intrinsic::x86_avx512_pmaxs_d:
11344 case Intrinsic::x86_avx512_pmaxs_q:
11345 case Intrinsic::x86_sse41_pminsb:
11346 case Intrinsic::x86_sse2_pmins_w:
11347 case Intrinsic::x86_sse41_pminsd:
11348 case Intrinsic::x86_avx2_pmins_b:
11349 case Intrinsic::x86_avx2_pmins_w:
11350 case Intrinsic::x86_avx2_pmins_d:
11351 case Intrinsic::x86_avx512_pmins_d:
11352 case Intrinsic::x86_avx512_pmins_q: {
11355 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11356 case Intrinsic::x86_sse2_pmaxu_b:
11357 case Intrinsic::x86_sse41_pmaxuw:
11358 case Intrinsic::x86_sse41_pmaxud:
11359 case Intrinsic::x86_avx2_pmaxu_b:
11360 case Intrinsic::x86_avx2_pmaxu_w:
11361 case Intrinsic::x86_avx2_pmaxu_d:
11362 case Intrinsic::x86_avx512_pmaxu_d:
11363 case Intrinsic::x86_avx512_pmaxu_q:
11364 Opcode = X86ISD::UMAX;
11366 case Intrinsic::x86_sse2_pminu_b:
11367 case Intrinsic::x86_sse41_pminuw:
11368 case Intrinsic::x86_sse41_pminud:
11369 case Intrinsic::x86_avx2_pminu_b:
11370 case Intrinsic::x86_avx2_pminu_w:
11371 case Intrinsic::x86_avx2_pminu_d:
11372 case Intrinsic::x86_avx512_pminu_d:
11373 case Intrinsic::x86_avx512_pminu_q:
11374 Opcode = X86ISD::UMIN;
11376 case Intrinsic::x86_sse41_pmaxsb:
11377 case Intrinsic::x86_sse2_pmaxs_w:
11378 case Intrinsic::x86_sse41_pmaxsd:
11379 case Intrinsic::x86_avx2_pmaxs_b:
11380 case Intrinsic::x86_avx2_pmaxs_w:
11381 case Intrinsic::x86_avx2_pmaxs_d:
11382 case Intrinsic::x86_avx512_pmaxs_d:
11383 case Intrinsic::x86_avx512_pmaxs_q:
11384 Opcode = X86ISD::SMAX;
11386 case Intrinsic::x86_sse41_pminsb:
11387 case Intrinsic::x86_sse2_pmins_w:
11388 case Intrinsic::x86_sse41_pminsd:
11389 case Intrinsic::x86_avx2_pmins_b:
11390 case Intrinsic::x86_avx2_pmins_w:
11391 case Intrinsic::x86_avx2_pmins_d:
11392 case Intrinsic::x86_avx512_pmins_d:
11393 case Intrinsic::x86_avx512_pmins_q:
11394 Opcode = X86ISD::SMIN;
11397 return DAG.getNode(Opcode, dl, Op.getValueType(),
11398 Op.getOperand(1), Op.getOperand(2));
11401 // SSE/SSE2/AVX floating point max/min intrinsics.
11402 case Intrinsic::x86_sse_max_ps:
11403 case Intrinsic::x86_sse2_max_pd:
11404 case Intrinsic::x86_avx_max_ps_256:
11405 case Intrinsic::x86_avx_max_pd_256:
11406 case Intrinsic::x86_avx512_max_ps_512:
11407 case Intrinsic::x86_avx512_max_pd_512:
11408 case Intrinsic::x86_sse_min_ps:
11409 case Intrinsic::x86_sse2_min_pd:
11410 case Intrinsic::x86_avx_min_ps_256:
11411 case Intrinsic::x86_avx_min_pd_256:
11412 case Intrinsic::x86_avx512_min_ps_512:
11413 case Intrinsic::x86_avx512_min_pd_512: {
11416 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11417 case Intrinsic::x86_sse_max_ps:
11418 case Intrinsic::x86_sse2_max_pd:
11419 case Intrinsic::x86_avx_max_ps_256:
11420 case Intrinsic::x86_avx_max_pd_256:
11421 case Intrinsic::x86_avx512_max_ps_512:
11422 case Intrinsic::x86_avx512_max_pd_512:
11423 Opcode = X86ISD::FMAX;
11425 case Intrinsic::x86_sse_min_ps:
11426 case Intrinsic::x86_sse2_min_pd:
11427 case Intrinsic::x86_avx_min_ps_256:
11428 case Intrinsic::x86_avx_min_pd_256:
11429 case Intrinsic::x86_avx512_min_ps_512:
11430 case Intrinsic::x86_avx512_min_pd_512:
11431 Opcode = X86ISD::FMIN;
11434 return DAG.getNode(Opcode, dl, Op.getValueType(),
11435 Op.getOperand(1), Op.getOperand(2));
11438 // AVX2 variable shift intrinsics
11439 case Intrinsic::x86_avx2_psllv_d:
11440 case Intrinsic::x86_avx2_psllv_q:
11441 case Intrinsic::x86_avx2_psllv_d_256:
11442 case Intrinsic::x86_avx2_psllv_q_256:
11443 case Intrinsic::x86_avx2_psrlv_d:
11444 case Intrinsic::x86_avx2_psrlv_q:
11445 case Intrinsic::x86_avx2_psrlv_d_256:
11446 case Intrinsic::x86_avx2_psrlv_q_256:
11447 case Intrinsic::x86_avx2_psrav_d:
11448 case Intrinsic::x86_avx2_psrav_d_256: {
11451 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11452 case Intrinsic::x86_avx2_psllv_d:
11453 case Intrinsic::x86_avx2_psllv_q:
11454 case Intrinsic::x86_avx2_psllv_d_256:
11455 case Intrinsic::x86_avx2_psllv_q_256:
11458 case Intrinsic::x86_avx2_psrlv_d:
11459 case Intrinsic::x86_avx2_psrlv_q:
11460 case Intrinsic::x86_avx2_psrlv_d_256:
11461 case Intrinsic::x86_avx2_psrlv_q_256:
11464 case Intrinsic::x86_avx2_psrav_d:
11465 case Intrinsic::x86_avx2_psrav_d_256:
11469 return DAG.getNode(Opcode, dl, Op.getValueType(),
11470 Op.getOperand(1), Op.getOperand(2));
11473 case Intrinsic::x86_ssse3_pshuf_b_128:
11474 case Intrinsic::x86_avx2_pshuf_b:
11475 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11476 Op.getOperand(1), Op.getOperand(2));
11478 case Intrinsic::x86_ssse3_psign_b_128:
11479 case Intrinsic::x86_ssse3_psign_w_128:
11480 case Intrinsic::x86_ssse3_psign_d_128:
11481 case Intrinsic::x86_avx2_psign_b:
11482 case Intrinsic::x86_avx2_psign_w:
11483 case Intrinsic::x86_avx2_psign_d:
11484 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11485 Op.getOperand(1), Op.getOperand(2));
11487 case Intrinsic::x86_sse41_insertps:
11488 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11489 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11491 case Intrinsic::x86_avx_vperm2f128_ps_256:
11492 case Intrinsic::x86_avx_vperm2f128_pd_256:
11493 case Intrinsic::x86_avx_vperm2f128_si_256:
11494 case Intrinsic::x86_avx2_vperm2i128:
11495 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11496 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11498 case Intrinsic::x86_avx2_permd:
11499 case Intrinsic::x86_avx2_permps:
11500 // Operands intentionally swapped. Mask is last operand to intrinsic,
11501 // but second operand for node/instruction.
11502 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11503 Op.getOperand(2), Op.getOperand(1));
11505 case Intrinsic::x86_sse_sqrt_ps:
11506 case Intrinsic::x86_sse2_sqrt_pd:
11507 case Intrinsic::x86_avx_sqrt_ps_256:
11508 case Intrinsic::x86_avx_sqrt_pd_256:
11509 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11511 // ptest and testp intrinsics. The intrinsic these come from are designed to
11512 // return an integer value, not just an instruction so lower it to the ptest
11513 // or testp pattern and a setcc for the result.
11514 case Intrinsic::x86_sse41_ptestz:
11515 case Intrinsic::x86_sse41_ptestc:
11516 case Intrinsic::x86_sse41_ptestnzc:
11517 case Intrinsic::x86_avx_ptestz_256:
11518 case Intrinsic::x86_avx_ptestc_256:
11519 case Intrinsic::x86_avx_ptestnzc_256:
11520 case Intrinsic::x86_avx_vtestz_ps:
11521 case Intrinsic::x86_avx_vtestc_ps:
11522 case Intrinsic::x86_avx_vtestnzc_ps:
11523 case Intrinsic::x86_avx_vtestz_pd:
11524 case Intrinsic::x86_avx_vtestc_pd:
11525 case Intrinsic::x86_avx_vtestnzc_pd:
11526 case Intrinsic::x86_avx_vtestz_ps_256:
11527 case Intrinsic::x86_avx_vtestc_ps_256:
11528 case Intrinsic::x86_avx_vtestnzc_ps_256:
11529 case Intrinsic::x86_avx_vtestz_pd_256:
11530 case Intrinsic::x86_avx_vtestc_pd_256:
11531 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11532 bool IsTestPacked = false;
11535 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11536 case Intrinsic::x86_avx_vtestz_ps:
11537 case Intrinsic::x86_avx_vtestz_pd:
11538 case Intrinsic::x86_avx_vtestz_ps_256:
11539 case Intrinsic::x86_avx_vtestz_pd_256:
11540 IsTestPacked = true; // Fallthrough
11541 case Intrinsic::x86_sse41_ptestz:
11542 case Intrinsic::x86_avx_ptestz_256:
11544 X86CC = X86::COND_E;
11546 case Intrinsic::x86_avx_vtestc_ps:
11547 case Intrinsic::x86_avx_vtestc_pd:
11548 case Intrinsic::x86_avx_vtestc_ps_256:
11549 case Intrinsic::x86_avx_vtestc_pd_256:
11550 IsTestPacked = true; // Fallthrough
11551 case Intrinsic::x86_sse41_ptestc:
11552 case Intrinsic::x86_avx_ptestc_256:
11554 X86CC = X86::COND_B;
11556 case Intrinsic::x86_avx_vtestnzc_ps:
11557 case Intrinsic::x86_avx_vtestnzc_pd:
11558 case Intrinsic::x86_avx_vtestnzc_ps_256:
11559 case Intrinsic::x86_avx_vtestnzc_pd_256:
11560 IsTestPacked = true; // Fallthrough
11561 case Intrinsic::x86_sse41_ptestnzc:
11562 case Intrinsic::x86_avx_ptestnzc_256:
11564 X86CC = X86::COND_A;
11568 SDValue LHS = Op.getOperand(1);
11569 SDValue RHS = Op.getOperand(2);
11570 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11571 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11572 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11573 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11574 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11576 case Intrinsic::x86_avx512_kortestz_w:
11577 case Intrinsic::x86_avx512_kortestc_w: {
11578 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11579 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11580 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11581 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11582 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11583 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11584 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11587 // SSE/AVX shift intrinsics
11588 case Intrinsic::x86_sse2_psll_w:
11589 case Intrinsic::x86_sse2_psll_d:
11590 case Intrinsic::x86_sse2_psll_q:
11591 case Intrinsic::x86_avx2_psll_w:
11592 case Intrinsic::x86_avx2_psll_d:
11593 case Intrinsic::x86_avx2_psll_q:
11594 case Intrinsic::x86_sse2_psrl_w:
11595 case Intrinsic::x86_sse2_psrl_d:
11596 case Intrinsic::x86_sse2_psrl_q:
11597 case Intrinsic::x86_avx2_psrl_w:
11598 case Intrinsic::x86_avx2_psrl_d:
11599 case Intrinsic::x86_avx2_psrl_q:
11600 case Intrinsic::x86_sse2_psra_w:
11601 case Intrinsic::x86_sse2_psra_d:
11602 case Intrinsic::x86_avx2_psra_w:
11603 case Intrinsic::x86_avx2_psra_d: {
11606 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11607 case Intrinsic::x86_sse2_psll_w:
11608 case Intrinsic::x86_sse2_psll_d:
11609 case Intrinsic::x86_sse2_psll_q:
11610 case Intrinsic::x86_avx2_psll_w:
11611 case Intrinsic::x86_avx2_psll_d:
11612 case Intrinsic::x86_avx2_psll_q:
11613 Opcode = X86ISD::VSHL;
11615 case Intrinsic::x86_sse2_psrl_w:
11616 case Intrinsic::x86_sse2_psrl_d:
11617 case Intrinsic::x86_sse2_psrl_q:
11618 case Intrinsic::x86_avx2_psrl_w:
11619 case Intrinsic::x86_avx2_psrl_d:
11620 case Intrinsic::x86_avx2_psrl_q:
11621 Opcode = X86ISD::VSRL;
11623 case Intrinsic::x86_sse2_psra_w:
11624 case Intrinsic::x86_sse2_psra_d:
11625 case Intrinsic::x86_avx2_psra_w:
11626 case Intrinsic::x86_avx2_psra_d:
11627 Opcode = X86ISD::VSRA;
11630 return DAG.getNode(Opcode, dl, Op.getValueType(),
11631 Op.getOperand(1), Op.getOperand(2));
11634 // SSE/AVX immediate shift intrinsics
11635 case Intrinsic::x86_sse2_pslli_w:
11636 case Intrinsic::x86_sse2_pslli_d:
11637 case Intrinsic::x86_sse2_pslli_q:
11638 case Intrinsic::x86_avx2_pslli_w:
11639 case Intrinsic::x86_avx2_pslli_d:
11640 case Intrinsic::x86_avx2_pslli_q:
11641 case Intrinsic::x86_sse2_psrli_w:
11642 case Intrinsic::x86_sse2_psrli_d:
11643 case Intrinsic::x86_sse2_psrli_q:
11644 case Intrinsic::x86_avx2_psrli_w:
11645 case Intrinsic::x86_avx2_psrli_d:
11646 case Intrinsic::x86_avx2_psrli_q:
11647 case Intrinsic::x86_sse2_psrai_w:
11648 case Intrinsic::x86_sse2_psrai_d:
11649 case Intrinsic::x86_avx2_psrai_w:
11650 case Intrinsic::x86_avx2_psrai_d: {
11653 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11654 case Intrinsic::x86_sse2_pslli_w:
11655 case Intrinsic::x86_sse2_pslli_d:
11656 case Intrinsic::x86_sse2_pslli_q:
11657 case Intrinsic::x86_avx2_pslli_w:
11658 case Intrinsic::x86_avx2_pslli_d:
11659 case Intrinsic::x86_avx2_pslli_q:
11660 Opcode = X86ISD::VSHLI;
11662 case Intrinsic::x86_sse2_psrli_w:
11663 case Intrinsic::x86_sse2_psrli_d:
11664 case Intrinsic::x86_sse2_psrli_q:
11665 case Intrinsic::x86_avx2_psrli_w:
11666 case Intrinsic::x86_avx2_psrli_d:
11667 case Intrinsic::x86_avx2_psrli_q:
11668 Opcode = X86ISD::VSRLI;
11670 case Intrinsic::x86_sse2_psrai_w:
11671 case Intrinsic::x86_sse2_psrai_d:
11672 case Intrinsic::x86_avx2_psrai_w:
11673 case Intrinsic::x86_avx2_psrai_d:
11674 Opcode = X86ISD::VSRAI;
11677 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11678 Op.getOperand(1), Op.getOperand(2), DAG);
11681 case Intrinsic::x86_sse42_pcmpistria128:
11682 case Intrinsic::x86_sse42_pcmpestria128:
11683 case Intrinsic::x86_sse42_pcmpistric128:
11684 case Intrinsic::x86_sse42_pcmpestric128:
11685 case Intrinsic::x86_sse42_pcmpistrio128:
11686 case Intrinsic::x86_sse42_pcmpestrio128:
11687 case Intrinsic::x86_sse42_pcmpistris128:
11688 case Intrinsic::x86_sse42_pcmpestris128:
11689 case Intrinsic::x86_sse42_pcmpistriz128:
11690 case Intrinsic::x86_sse42_pcmpestriz128: {
11694 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11695 case Intrinsic::x86_sse42_pcmpistria128:
11696 Opcode = X86ISD::PCMPISTRI;
11697 X86CC = X86::COND_A;
11699 case Intrinsic::x86_sse42_pcmpestria128:
11700 Opcode = X86ISD::PCMPESTRI;
11701 X86CC = X86::COND_A;
11703 case Intrinsic::x86_sse42_pcmpistric128:
11704 Opcode = X86ISD::PCMPISTRI;
11705 X86CC = X86::COND_B;
11707 case Intrinsic::x86_sse42_pcmpestric128:
11708 Opcode = X86ISD::PCMPESTRI;
11709 X86CC = X86::COND_B;
11711 case Intrinsic::x86_sse42_pcmpistrio128:
11712 Opcode = X86ISD::PCMPISTRI;
11713 X86CC = X86::COND_O;
11715 case Intrinsic::x86_sse42_pcmpestrio128:
11716 Opcode = X86ISD::PCMPESTRI;
11717 X86CC = X86::COND_O;
11719 case Intrinsic::x86_sse42_pcmpistris128:
11720 Opcode = X86ISD::PCMPISTRI;
11721 X86CC = X86::COND_S;
11723 case Intrinsic::x86_sse42_pcmpestris128:
11724 Opcode = X86ISD::PCMPESTRI;
11725 X86CC = X86::COND_S;
11727 case Intrinsic::x86_sse42_pcmpistriz128:
11728 Opcode = X86ISD::PCMPISTRI;
11729 X86CC = X86::COND_E;
11731 case Intrinsic::x86_sse42_pcmpestriz128:
11732 Opcode = X86ISD::PCMPESTRI;
11733 X86CC = X86::COND_E;
11736 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11737 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11738 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11739 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11740 DAG.getConstant(X86CC, MVT::i8),
11741 SDValue(PCMP.getNode(), 1));
11742 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11745 case Intrinsic::x86_sse42_pcmpistri128:
11746 case Intrinsic::x86_sse42_pcmpestri128: {
11748 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11749 Opcode = X86ISD::PCMPISTRI;
11751 Opcode = X86ISD::PCMPESTRI;
11753 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11754 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11755 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11757 case Intrinsic::x86_fma_vfmadd_ps:
11758 case Intrinsic::x86_fma_vfmadd_pd:
11759 case Intrinsic::x86_fma_vfmsub_ps:
11760 case Intrinsic::x86_fma_vfmsub_pd:
11761 case Intrinsic::x86_fma_vfnmadd_ps:
11762 case Intrinsic::x86_fma_vfnmadd_pd:
11763 case Intrinsic::x86_fma_vfnmsub_ps:
11764 case Intrinsic::x86_fma_vfnmsub_pd:
11765 case Intrinsic::x86_fma_vfmaddsub_ps:
11766 case Intrinsic::x86_fma_vfmaddsub_pd:
11767 case Intrinsic::x86_fma_vfmsubadd_ps:
11768 case Intrinsic::x86_fma_vfmsubadd_pd:
11769 case Intrinsic::x86_fma_vfmadd_ps_256:
11770 case Intrinsic::x86_fma_vfmadd_pd_256:
11771 case Intrinsic::x86_fma_vfmsub_ps_256:
11772 case Intrinsic::x86_fma_vfmsub_pd_256:
11773 case Intrinsic::x86_fma_vfnmadd_ps_256:
11774 case Intrinsic::x86_fma_vfnmadd_pd_256:
11775 case Intrinsic::x86_fma_vfnmsub_ps_256:
11776 case Intrinsic::x86_fma_vfnmsub_pd_256:
11777 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11778 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11779 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11780 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11781 case Intrinsic::x86_fma_vfmadd_ps_512:
11782 case Intrinsic::x86_fma_vfmadd_pd_512:
11783 case Intrinsic::x86_fma_vfmsub_ps_512:
11784 case Intrinsic::x86_fma_vfmsub_pd_512:
11785 case Intrinsic::x86_fma_vfnmadd_ps_512:
11786 case Intrinsic::x86_fma_vfnmadd_pd_512:
11787 case Intrinsic::x86_fma_vfnmsub_ps_512:
11788 case Intrinsic::x86_fma_vfnmsub_pd_512:
11789 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11790 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11791 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11792 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11795 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11796 case Intrinsic::x86_fma_vfmadd_ps:
11797 case Intrinsic::x86_fma_vfmadd_pd:
11798 case Intrinsic::x86_fma_vfmadd_ps_256:
11799 case Intrinsic::x86_fma_vfmadd_pd_256:
11800 case Intrinsic::x86_fma_vfmadd_ps_512:
11801 case Intrinsic::x86_fma_vfmadd_pd_512:
11802 Opc = X86ISD::FMADD;
11804 case Intrinsic::x86_fma_vfmsub_ps:
11805 case Intrinsic::x86_fma_vfmsub_pd:
11806 case Intrinsic::x86_fma_vfmsub_ps_256:
11807 case Intrinsic::x86_fma_vfmsub_pd_256:
11808 case Intrinsic::x86_fma_vfmsub_ps_512:
11809 case Intrinsic::x86_fma_vfmsub_pd_512:
11810 Opc = X86ISD::FMSUB;
11812 case Intrinsic::x86_fma_vfnmadd_ps:
11813 case Intrinsic::x86_fma_vfnmadd_pd:
11814 case Intrinsic::x86_fma_vfnmadd_ps_256:
11815 case Intrinsic::x86_fma_vfnmadd_pd_256:
11816 case Intrinsic::x86_fma_vfnmadd_ps_512:
11817 case Intrinsic::x86_fma_vfnmadd_pd_512:
11818 Opc = X86ISD::FNMADD;
11820 case Intrinsic::x86_fma_vfnmsub_ps:
11821 case Intrinsic::x86_fma_vfnmsub_pd:
11822 case Intrinsic::x86_fma_vfnmsub_ps_256:
11823 case Intrinsic::x86_fma_vfnmsub_pd_256:
11824 case Intrinsic::x86_fma_vfnmsub_ps_512:
11825 case Intrinsic::x86_fma_vfnmsub_pd_512:
11826 Opc = X86ISD::FNMSUB;
11828 case Intrinsic::x86_fma_vfmaddsub_ps:
11829 case Intrinsic::x86_fma_vfmaddsub_pd:
11830 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11831 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11832 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11833 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11834 Opc = X86ISD::FMADDSUB;
11836 case Intrinsic::x86_fma_vfmsubadd_ps:
11837 case Intrinsic::x86_fma_vfmsubadd_pd:
11838 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11839 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11840 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11841 case Intrinsic::x86_fma_vfmsubadd_pd_512:
11842 Opc = X86ISD::FMSUBADD;
11846 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11847 Op.getOperand(2), Op.getOperand(3));
11852 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11853 SDValue Base, SDValue Index,
11854 SDValue ScaleOp, SDValue Chain,
11855 const X86Subtarget * Subtarget) {
11857 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11858 assert(C && "Invalid scale type");
11859 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11860 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11861 EVT MaskVT = MVT::getVectorVT(MVT::i1,
11862 Index.getValueType().getVectorNumElements());
11863 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11864 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11865 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11866 SDValue Segment = DAG.getRegister(0, MVT::i32);
11867 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11868 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11869 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11870 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11873 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11874 SDValue Src, SDValue Mask, SDValue Base,
11875 SDValue Index, SDValue ScaleOp, SDValue Chain,
11876 const X86Subtarget * Subtarget) {
11878 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11879 assert(C && "Invalid scale type");
11880 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11881 EVT MaskVT = MVT::getVectorVT(MVT::i1,
11882 Index.getValueType().getVectorNumElements());
11883 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11884 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11885 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11886 SDValue Segment = DAG.getRegister(0, MVT::i32);
11887 if (Src.getOpcode() == ISD::UNDEF)
11888 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11889 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11890 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11891 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11892 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11895 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11896 SDValue Src, SDValue Base, SDValue Index,
11897 SDValue ScaleOp, SDValue Chain) {
11899 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11900 assert(C && "Invalid scale type");
11901 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11902 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11903 SDValue Segment = DAG.getRegister(0, MVT::i32);
11904 EVT MaskVT = MVT::getVectorVT(MVT::i1,
11905 Index.getValueType().getVectorNumElements());
11906 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11907 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11908 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11909 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11910 return SDValue(Res, 1);
11913 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11914 SDValue Src, SDValue Mask, SDValue Base,
11915 SDValue Index, SDValue ScaleOp, SDValue Chain) {
11917 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11918 assert(C && "Invalid scale type");
11919 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11920 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11921 SDValue Segment = DAG.getRegister(0, MVT::i32);
11922 EVT MaskVT = MVT::getVectorVT(MVT::i1,
11923 Index.getValueType().getVectorNumElements());
11924 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11925 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11926 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11927 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11928 return SDValue(Res, 1);
11931 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
11932 SelectionDAG &DAG) {
11934 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11936 default: return SDValue(); // Don't custom lower most intrinsics.
11938 // RDRAND/RDSEED intrinsics.
11939 case Intrinsic::x86_rdrand_16:
11940 case Intrinsic::x86_rdrand_32:
11941 case Intrinsic::x86_rdrand_64:
11942 case Intrinsic::x86_rdseed_16:
11943 case Intrinsic::x86_rdseed_32:
11944 case Intrinsic::x86_rdseed_64: {
11945 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11946 IntNo == Intrinsic::x86_rdseed_32 ||
11947 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11949 // Emit the node with the right value type.
11950 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11951 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11953 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11954 // Otherwise return the value from Rand, which is always 0, casted to i32.
11955 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11956 DAG.getConstant(1, Op->getValueType(1)),
11957 DAG.getConstant(X86::COND_B, MVT::i32),
11958 SDValue(Result.getNode(), 1) };
11959 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11960 DAG.getVTList(Op->getValueType(1), MVT::Glue),
11961 Ops, array_lengthof(Ops));
11963 // Return { result, isValid, chain }.
11964 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11965 SDValue(Result.getNode(), 2));
11967 //int_gather(index, base, scale);
11968 case Intrinsic::x86_avx512_gather_qpd_512:
11969 case Intrinsic::x86_avx512_gather_qps_512:
11970 case Intrinsic::x86_avx512_gather_dpd_512:
11971 case Intrinsic::x86_avx512_gather_qpi_512:
11972 case Intrinsic::x86_avx512_gather_qpq_512:
11973 case Intrinsic::x86_avx512_gather_dpq_512:
11974 case Intrinsic::x86_avx512_gather_dps_512:
11975 case Intrinsic::x86_avx512_gather_dpi_512: {
11978 default: llvm_unreachable("Unexpected intrinsic!");
11979 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
11980 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
11981 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
11982 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
11983 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
11984 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
11985 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
11986 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
11988 SDValue Chain = Op.getOperand(0);
11989 SDValue Index = Op.getOperand(2);
11990 SDValue Base = Op.getOperand(3);
11991 SDValue Scale = Op.getOperand(4);
11992 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
11994 //int_gather_mask(v1, mask, index, base, scale);
11995 case Intrinsic::x86_avx512_gather_qps_mask_512:
11996 case Intrinsic::x86_avx512_gather_qpd_mask_512:
11997 case Intrinsic::x86_avx512_gather_dpd_mask_512:
11998 case Intrinsic::x86_avx512_gather_dps_mask_512:
11999 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12000 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12001 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12002 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12005 default: llvm_unreachable("Unexpected intrinsic!");
12006 case Intrinsic::x86_avx512_gather_qps_mask_512:
12007 Opc = X86::VGATHERQPSZrm; break;
12008 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12009 Opc = X86::VGATHERQPDZrm; break;
12010 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12011 Opc = X86::VGATHERDPDZrm; break;
12012 case Intrinsic::x86_avx512_gather_dps_mask_512:
12013 Opc = X86::VGATHERDPSZrm; break;
12014 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12015 Opc = X86::VPGATHERQDZrm; break;
12016 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12017 Opc = X86::VPGATHERQQZrm; break;
12018 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12019 Opc = X86::VPGATHERDDZrm; break;
12020 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12021 Opc = X86::VPGATHERDQZrm; break;
12023 SDValue Chain = Op.getOperand(0);
12024 SDValue Src = Op.getOperand(2);
12025 SDValue Mask = Op.getOperand(3);
12026 SDValue Index = Op.getOperand(4);
12027 SDValue Base = Op.getOperand(5);
12028 SDValue Scale = Op.getOperand(6);
12029 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12032 //int_scatter(base, index, v1, scale);
12033 case Intrinsic::x86_avx512_scatter_qpd_512:
12034 case Intrinsic::x86_avx512_scatter_qps_512:
12035 case Intrinsic::x86_avx512_scatter_dpd_512:
12036 case Intrinsic::x86_avx512_scatter_qpi_512:
12037 case Intrinsic::x86_avx512_scatter_qpq_512:
12038 case Intrinsic::x86_avx512_scatter_dpq_512:
12039 case Intrinsic::x86_avx512_scatter_dps_512:
12040 case Intrinsic::x86_avx512_scatter_dpi_512: {
12043 default: llvm_unreachable("Unexpected intrinsic!");
12044 case Intrinsic::x86_avx512_scatter_qpd_512:
12045 Opc = X86::VSCATTERQPDZmr; break;
12046 case Intrinsic::x86_avx512_scatter_qps_512:
12047 Opc = X86::VSCATTERQPSZmr; break;
12048 case Intrinsic::x86_avx512_scatter_dpd_512:
12049 Opc = X86::VSCATTERDPDZmr; break;
12050 case Intrinsic::x86_avx512_scatter_dps_512:
12051 Opc = X86::VSCATTERDPSZmr; break;
12052 case Intrinsic::x86_avx512_scatter_qpi_512:
12053 Opc = X86::VPSCATTERQDZmr; break;
12054 case Intrinsic::x86_avx512_scatter_qpq_512:
12055 Opc = X86::VPSCATTERQQZmr; break;
12056 case Intrinsic::x86_avx512_scatter_dpq_512:
12057 Opc = X86::VPSCATTERDQZmr; break;
12058 case Intrinsic::x86_avx512_scatter_dpi_512:
12059 Opc = X86::VPSCATTERDDZmr; break;
12061 SDValue Chain = Op.getOperand(0);
12062 SDValue Base = Op.getOperand(2);
12063 SDValue Index = Op.getOperand(3);
12064 SDValue Src = Op.getOperand(4);
12065 SDValue Scale = Op.getOperand(5);
12066 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12068 //int_scatter_mask(base, mask, index, v1, scale);
12069 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12070 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12071 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12072 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12073 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12074 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12075 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12076 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12079 default: llvm_unreachable("Unexpected intrinsic!");
12080 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12081 Opc = X86::VSCATTERQPDZmr; break;
12082 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12083 Opc = X86::VSCATTERQPSZmr; break;
12084 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12085 Opc = X86::VSCATTERDPDZmr; break;
12086 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12087 Opc = X86::VSCATTERDPSZmr; break;
12088 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12089 Opc = X86::VPSCATTERQDZmr; break;
12090 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12091 Opc = X86::VPSCATTERQQZmr; break;
12092 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12093 Opc = X86::VPSCATTERDQZmr; break;
12094 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12095 Opc = X86::VPSCATTERDDZmr; break;
12097 SDValue Chain = Op.getOperand(0);
12098 SDValue Base = Op.getOperand(2);
12099 SDValue Mask = Op.getOperand(3);
12100 SDValue Index = Op.getOperand(4);
12101 SDValue Src = Op.getOperand(5);
12102 SDValue Scale = Op.getOperand(6);
12103 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12105 // XTEST intrinsics.
12106 case Intrinsic::x86_xtest: {
12107 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12108 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12109 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12110 DAG.getConstant(X86::COND_NE, MVT::i8),
12112 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12113 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12114 Ret, SDValue(InTrans.getNode(), 1));
12119 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12120 SelectionDAG &DAG) const {
12121 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12122 MFI->setReturnAddressIsTaken(true);
12124 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12126 EVT PtrVT = getPointerTy();
12129 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12130 const X86RegisterInfo *RegInfo =
12131 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12132 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12133 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12134 DAG.getNode(ISD::ADD, dl, PtrVT,
12135 FrameAddr, Offset),
12136 MachinePointerInfo(), false, false, false, 0);
12139 // Just load the return address.
12140 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12141 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12142 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12145 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12146 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12147 MFI->setFrameAddressIsTaken(true);
12149 EVT VT = Op.getValueType();
12150 SDLoc dl(Op); // FIXME probably not meaningful
12151 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12152 const X86RegisterInfo *RegInfo =
12153 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12154 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12155 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12156 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12157 "Invalid Frame Register!");
12158 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12160 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12161 MachinePointerInfo(),
12162 false, false, false, 0);
12166 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12167 SelectionDAG &DAG) const {
12168 const X86RegisterInfo *RegInfo =
12169 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12170 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12173 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12174 SDValue Chain = Op.getOperand(0);
12175 SDValue Offset = Op.getOperand(1);
12176 SDValue Handler = Op.getOperand(2);
12179 EVT PtrVT = getPointerTy();
12180 const X86RegisterInfo *RegInfo =
12181 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12182 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12183 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12184 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12185 "Invalid Frame Register!");
12186 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12187 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12189 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12190 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12191 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12192 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12194 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12196 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12197 DAG.getRegister(StoreAddrReg, PtrVT));
12200 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12201 SelectionDAG &DAG) const {
12203 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12204 DAG.getVTList(MVT::i32, MVT::Other),
12205 Op.getOperand(0), Op.getOperand(1));
12208 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12209 SelectionDAG &DAG) const {
12211 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12212 Op.getOperand(0), Op.getOperand(1));
12215 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12216 return Op.getOperand(0);
12219 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12220 SelectionDAG &DAG) const {
12221 SDValue Root = Op.getOperand(0);
12222 SDValue Trmp = Op.getOperand(1); // trampoline
12223 SDValue FPtr = Op.getOperand(2); // nested function
12224 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12227 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12228 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12230 if (Subtarget->is64Bit()) {
12231 SDValue OutChains[6];
12233 // Large code-model.
12234 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12235 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12237 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12238 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12240 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12242 // Load the pointer to the nested function into R11.
12243 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12244 SDValue Addr = Trmp;
12245 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12246 Addr, MachinePointerInfo(TrmpAddr),
12249 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12250 DAG.getConstant(2, MVT::i64));
12251 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12252 MachinePointerInfo(TrmpAddr, 2),
12255 // Load the 'nest' parameter value into R10.
12256 // R10 is specified in X86CallingConv.td
12257 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12258 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12259 DAG.getConstant(10, MVT::i64));
12260 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12261 Addr, MachinePointerInfo(TrmpAddr, 10),
12264 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12265 DAG.getConstant(12, MVT::i64));
12266 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12267 MachinePointerInfo(TrmpAddr, 12),
12270 // Jump to the nested function.
12271 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12272 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12273 DAG.getConstant(20, MVT::i64));
12274 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12275 Addr, MachinePointerInfo(TrmpAddr, 20),
12278 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12279 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12280 DAG.getConstant(22, MVT::i64));
12281 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12282 MachinePointerInfo(TrmpAddr, 22),
12285 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12287 const Function *Func =
12288 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12289 CallingConv::ID CC = Func->getCallingConv();
12294 llvm_unreachable("Unsupported calling convention");
12295 case CallingConv::C:
12296 case CallingConv::X86_StdCall: {
12297 // Pass 'nest' parameter in ECX.
12298 // Must be kept in sync with X86CallingConv.td
12299 NestReg = X86::ECX;
12301 // Check that ECX wasn't needed by an 'inreg' parameter.
12302 FunctionType *FTy = Func->getFunctionType();
12303 const AttributeSet &Attrs = Func->getAttributes();
12305 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12306 unsigned InRegCount = 0;
12309 for (FunctionType::param_iterator I = FTy->param_begin(),
12310 E = FTy->param_end(); I != E; ++I, ++Idx)
12311 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12312 // FIXME: should only count parameters that are lowered to integers.
12313 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12315 if (InRegCount > 2) {
12316 report_fatal_error("Nest register in use - reduce number of inreg"
12322 case CallingConv::X86_FastCall:
12323 case CallingConv::X86_ThisCall:
12324 case CallingConv::Fast:
12325 // Pass 'nest' parameter in EAX.
12326 // Must be kept in sync with X86CallingConv.td
12327 NestReg = X86::EAX;
12331 SDValue OutChains[4];
12332 SDValue Addr, Disp;
12334 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12335 DAG.getConstant(10, MVT::i32));
12336 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12338 // This is storing the opcode for MOV32ri.
12339 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12340 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12341 OutChains[0] = DAG.getStore(Root, dl,
12342 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12343 Trmp, MachinePointerInfo(TrmpAddr),
12346 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12347 DAG.getConstant(1, MVT::i32));
12348 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12349 MachinePointerInfo(TrmpAddr, 1),
12352 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12353 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12354 DAG.getConstant(5, MVT::i32));
12355 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12356 MachinePointerInfo(TrmpAddr, 5),
12359 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12360 DAG.getConstant(6, MVT::i32));
12361 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12362 MachinePointerInfo(TrmpAddr, 6),
12365 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12369 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12370 SelectionDAG &DAG) const {
12372 The rounding mode is in bits 11:10 of FPSR, and has the following
12374 00 Round to nearest
12379 FLT_ROUNDS, on the other hand, expects the following:
12386 To perform the conversion, we do:
12387 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12390 MachineFunction &MF = DAG.getMachineFunction();
12391 const TargetMachine &TM = MF.getTarget();
12392 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12393 unsigned StackAlignment = TFI.getStackAlignment();
12394 EVT VT = Op.getValueType();
12397 // Save FP Control Word to stack slot
12398 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12399 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12401 MachineMemOperand *MMO =
12402 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12403 MachineMemOperand::MOStore, 2, 2);
12405 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12406 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12407 DAG.getVTList(MVT::Other),
12408 Ops, array_lengthof(Ops), MVT::i16,
12411 // Load FP Control Word from stack slot
12412 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12413 MachinePointerInfo(), false, false, false, 0);
12415 // Transform as necessary
12417 DAG.getNode(ISD::SRL, DL, MVT::i16,
12418 DAG.getNode(ISD::AND, DL, MVT::i16,
12419 CWD, DAG.getConstant(0x800, MVT::i16)),
12420 DAG.getConstant(11, MVT::i8));
12422 DAG.getNode(ISD::SRL, DL, MVT::i16,
12423 DAG.getNode(ISD::AND, DL, MVT::i16,
12424 CWD, DAG.getConstant(0x400, MVT::i16)),
12425 DAG.getConstant(9, MVT::i8));
12428 DAG.getNode(ISD::AND, DL, MVT::i16,
12429 DAG.getNode(ISD::ADD, DL, MVT::i16,
12430 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12431 DAG.getConstant(1, MVT::i16)),
12432 DAG.getConstant(3, MVT::i16));
12434 return DAG.getNode((VT.getSizeInBits() < 16 ?
12435 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12438 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12439 EVT VT = Op.getValueType();
12441 unsigned NumBits = VT.getSizeInBits();
12444 Op = Op.getOperand(0);
12445 if (VT == MVT::i8) {
12446 // Zero extend to i32 since there is not an i8 bsr.
12448 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12451 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12452 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12453 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12455 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12458 DAG.getConstant(NumBits+NumBits-1, OpVT),
12459 DAG.getConstant(X86::COND_E, MVT::i8),
12462 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12464 // Finally xor with NumBits-1.
12465 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12468 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12472 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12473 EVT VT = Op.getValueType();
12475 unsigned NumBits = VT.getSizeInBits();
12478 Op = Op.getOperand(0);
12479 if (VT == MVT::i8) {
12480 // Zero extend to i32 since there is not an i8 bsr.
12482 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12485 // Issue a bsr (scan bits in reverse).
12486 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12487 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12489 // And xor with NumBits-1.
12490 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12493 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12497 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12498 EVT VT = Op.getValueType();
12499 unsigned NumBits = VT.getSizeInBits();
12501 Op = Op.getOperand(0);
12503 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12504 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12505 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12507 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12510 DAG.getConstant(NumBits, VT),
12511 DAG.getConstant(X86::COND_E, MVT::i8),
12514 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12517 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12518 // ones, and then concatenate the result back.
12519 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12520 EVT VT = Op.getValueType();
12522 assert(VT.is256BitVector() && VT.isInteger() &&
12523 "Unsupported value type for operation");
12525 unsigned NumElems = VT.getVectorNumElements();
12528 // Extract the LHS vectors
12529 SDValue LHS = Op.getOperand(0);
12530 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12531 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12533 // Extract the RHS vectors
12534 SDValue RHS = Op.getOperand(1);
12535 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12536 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12538 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12539 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12541 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12542 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12543 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12546 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12547 assert(Op.getValueType().is256BitVector() &&
12548 Op.getValueType().isInteger() &&
12549 "Only handle AVX 256-bit vector integer operation");
12550 return Lower256IntArith(Op, DAG);
12553 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12554 assert(Op.getValueType().is256BitVector() &&
12555 Op.getValueType().isInteger() &&
12556 "Only handle AVX 256-bit vector integer operation");
12557 return Lower256IntArith(Op, DAG);
12560 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12561 SelectionDAG &DAG) {
12563 EVT VT = Op.getValueType();
12565 // Decompose 256-bit ops into smaller 128-bit ops.
12566 if (VT.is256BitVector() && !Subtarget->hasInt256())
12567 return Lower256IntArith(Op, DAG);
12569 SDValue A = Op.getOperand(0);
12570 SDValue B = Op.getOperand(1);
12572 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12573 if (VT == MVT::v4i32) {
12574 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12575 "Should not custom lower when pmuldq is available!");
12577 // Extract the odd parts.
12578 static const int UnpackMask[] = { 1, -1, 3, -1 };
12579 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12580 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12582 // Multiply the even parts.
12583 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12584 // Now multiply odd parts.
12585 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12587 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12588 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12590 // Merge the two vectors back together with a shuffle. This expands into 2
12592 static const int ShufMask[] = { 0, 4, 2, 6 };
12593 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12596 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12597 "Only know how to lower V2I64/V4I64/V8I64 multiply");
12599 // Ahi = psrlqi(a, 32);
12600 // Bhi = psrlqi(b, 32);
12602 // AloBlo = pmuludq(a, b);
12603 // AloBhi = pmuludq(a, Bhi);
12604 // AhiBlo = pmuludq(Ahi, b);
12606 // AloBhi = psllqi(AloBhi, 32);
12607 // AhiBlo = psllqi(AhiBlo, 32);
12608 // return AloBlo + AloBhi + AhiBlo;
12610 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12611 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12613 // Bit cast to 32-bit vectors for MULUDQ
12614 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12615 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12616 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12617 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12618 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12619 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12621 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12622 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12623 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12625 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12626 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12628 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12629 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12632 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12633 EVT VT = Op.getValueType();
12634 EVT EltTy = VT.getVectorElementType();
12635 unsigned NumElts = VT.getVectorNumElements();
12636 SDValue N0 = Op.getOperand(0);
12639 // Lower sdiv X, pow2-const.
12640 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12644 APInt SplatValue, SplatUndef;
12645 unsigned SplatBitSize;
12647 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12649 EltTy.getSizeInBits() < SplatBitSize)
12652 if ((SplatValue != 0) &&
12653 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12654 unsigned Lg2 = SplatValue.countTrailingZeros();
12655 // Splat the sign bit.
12656 SmallVector<SDValue, 16> Sz(NumElts,
12657 DAG.getConstant(EltTy.getSizeInBits() - 1,
12659 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12660 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12662 // Add (N0 < 0) ? abs2 - 1 : 0;
12663 SmallVector<SDValue, 16> Amt(NumElts,
12664 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12666 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12667 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12669 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12670 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12671 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12672 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12675 // If we're dividing by a positive value, we're done. Otherwise, we must
12676 // negate the result.
12677 if (SplatValue.isNonNegative())
12680 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12681 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12682 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12687 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12688 const X86Subtarget *Subtarget) {
12689 EVT VT = Op.getValueType();
12691 SDValue R = Op.getOperand(0);
12692 SDValue Amt = Op.getOperand(1);
12694 // Optimize shl/srl/sra with constant shift amount.
12695 if (isSplatVector(Amt.getNode())) {
12696 SDValue SclrAmt = Amt->getOperand(0);
12697 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12698 uint64_t ShiftAmt = C->getZExtValue();
12700 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12701 (Subtarget->hasInt256() &&
12702 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12703 (Subtarget->hasAVX512() &&
12704 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12705 if (Op.getOpcode() == ISD::SHL)
12706 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12708 if (Op.getOpcode() == ISD::SRL)
12709 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12711 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12712 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12716 if (VT == MVT::v16i8) {
12717 if (Op.getOpcode() == ISD::SHL) {
12718 // Make a large shift.
12719 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12720 MVT::v8i16, R, ShiftAmt,
12722 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12723 // Zero out the rightmost bits.
12724 SmallVector<SDValue, 16> V(16,
12725 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12727 return DAG.getNode(ISD::AND, dl, VT, SHL,
12728 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12730 if (Op.getOpcode() == ISD::SRL) {
12731 // Make a large shift.
12732 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12733 MVT::v8i16, R, ShiftAmt,
12735 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12736 // Zero out the leftmost bits.
12737 SmallVector<SDValue, 16> V(16,
12738 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12740 return DAG.getNode(ISD::AND, dl, VT, SRL,
12741 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12743 if (Op.getOpcode() == ISD::SRA) {
12744 if (ShiftAmt == 7) {
12745 // R s>> 7 === R s< 0
12746 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12747 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12750 // R s>> a === ((R u>> a) ^ m) - m
12751 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12752 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12754 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12755 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12756 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12759 llvm_unreachable("Unknown shift opcode.");
12762 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12763 if (Op.getOpcode() == ISD::SHL) {
12764 // Make a large shift.
12765 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12766 MVT::v16i16, R, ShiftAmt,
12768 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12769 // Zero out the rightmost bits.
12770 SmallVector<SDValue, 32> V(32,
12771 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12773 return DAG.getNode(ISD::AND, dl, VT, SHL,
12774 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12776 if (Op.getOpcode() == ISD::SRL) {
12777 // Make a large shift.
12778 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12779 MVT::v16i16, R, ShiftAmt,
12781 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12782 // Zero out the leftmost bits.
12783 SmallVector<SDValue, 32> V(32,
12784 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12786 return DAG.getNode(ISD::AND, dl, VT, SRL,
12787 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12789 if (Op.getOpcode() == ISD::SRA) {
12790 if (ShiftAmt == 7) {
12791 // R s>> 7 === R s< 0
12792 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12793 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12796 // R s>> a === ((R u>> a) ^ m) - m
12797 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12798 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12800 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12801 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12802 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12805 llvm_unreachable("Unknown shift opcode.");
12810 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12811 if (!Subtarget->is64Bit() &&
12812 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12813 Amt.getOpcode() == ISD::BITCAST &&
12814 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12815 Amt = Amt.getOperand(0);
12816 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12817 VT.getVectorNumElements();
12818 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12819 uint64_t ShiftAmt = 0;
12820 for (unsigned i = 0; i != Ratio; ++i) {
12821 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12825 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12827 // Check remaining shift amounts.
12828 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12829 uint64_t ShAmt = 0;
12830 for (unsigned j = 0; j != Ratio; ++j) {
12831 ConstantSDNode *C =
12832 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12836 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12838 if (ShAmt != ShiftAmt)
12841 switch (Op.getOpcode()) {
12843 llvm_unreachable("Unknown shift opcode!");
12845 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12848 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12851 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12859 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12860 const X86Subtarget* Subtarget) {
12861 EVT VT = Op.getValueType();
12863 SDValue R = Op.getOperand(0);
12864 SDValue Amt = Op.getOperand(1);
12866 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12867 VT == MVT::v4i32 || VT == MVT::v8i16 ||
12868 (Subtarget->hasInt256() &&
12869 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12870 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12871 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12873 EVT EltVT = VT.getVectorElementType();
12875 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12876 unsigned NumElts = VT.getVectorNumElements();
12878 for (i = 0; i != NumElts; ++i) {
12879 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12883 for (j = i; j != NumElts; ++j) {
12884 SDValue Arg = Amt.getOperand(j);
12885 if (Arg.getOpcode() == ISD::UNDEF) continue;
12886 if (Arg != Amt.getOperand(i))
12889 if (i != NumElts && j == NumElts)
12890 BaseShAmt = Amt.getOperand(i);
12892 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12893 Amt = Amt.getOperand(0);
12894 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12895 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12896 SDValue InVec = Amt.getOperand(0);
12897 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12898 unsigned NumElts = InVec.getValueType().getVectorNumElements();
12900 for (; i != NumElts; ++i) {
12901 SDValue Arg = InVec.getOperand(i);
12902 if (Arg.getOpcode() == ISD::UNDEF) continue;
12906 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12907 if (ConstantSDNode *C =
12908 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12909 unsigned SplatIdx =
12910 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12911 if (C->getZExtValue() == SplatIdx)
12912 BaseShAmt = InVec.getOperand(1);
12915 if (BaseShAmt.getNode() == 0)
12916 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12917 DAG.getIntPtrConstant(0));
12921 if (BaseShAmt.getNode()) {
12922 if (EltVT.bitsGT(MVT::i32))
12923 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12924 else if (EltVT.bitsLT(MVT::i32))
12925 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12927 switch (Op.getOpcode()) {
12929 llvm_unreachable("Unknown shift opcode!");
12931 switch (VT.getSimpleVT().SimpleTy) {
12932 default: return SDValue();
12941 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12944 switch (VT.getSimpleVT().SimpleTy) {
12945 default: return SDValue();
12952 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12955 switch (VT.getSimpleVT().SimpleTy) {
12956 default: return SDValue();
12965 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12971 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12972 if (!Subtarget->is64Bit() &&
12973 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
12974 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
12975 Amt.getOpcode() == ISD::BITCAST &&
12976 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12977 Amt = Amt.getOperand(0);
12978 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12979 VT.getVectorNumElements();
12980 std::vector<SDValue> Vals(Ratio);
12981 for (unsigned i = 0; i != Ratio; ++i)
12982 Vals[i] = Amt.getOperand(i);
12983 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12984 for (unsigned j = 0; j != Ratio; ++j)
12985 if (Vals[j] != Amt.getOperand(i + j))
12988 switch (Op.getOpcode()) {
12990 llvm_unreachable("Unknown shift opcode!");
12992 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12994 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12996 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13003 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13004 SelectionDAG &DAG) {
13006 EVT VT = Op.getValueType();
13008 SDValue R = Op.getOperand(0);
13009 SDValue Amt = Op.getOperand(1);
13012 if (!Subtarget->hasSSE2())
13015 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13019 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13023 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13025 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13026 if (Subtarget->hasInt256()) {
13027 if (Op.getOpcode() == ISD::SRL &&
13028 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13029 VT == MVT::v4i64 || VT == MVT::v8i32))
13031 if (Op.getOpcode() == ISD::SHL &&
13032 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13033 VT == MVT::v4i64 || VT == MVT::v8i32))
13035 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13039 // Lower SHL with variable shift amount.
13040 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13041 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13043 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13044 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13045 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13046 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13048 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13049 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13052 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13053 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13055 // Turn 'a' into a mask suitable for VSELECT
13056 SDValue VSelM = DAG.getConstant(0x80, VT);
13057 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13058 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13060 SDValue CM1 = DAG.getConstant(0x0f, VT);
13061 SDValue CM2 = DAG.getConstant(0x3f, VT);
13063 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13064 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13065 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13066 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13067 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13070 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13071 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13072 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13074 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13075 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13076 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13077 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13078 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13081 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13082 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13083 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13085 // return VSELECT(r, r+r, a);
13086 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13087 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13091 // Decompose 256-bit shifts into smaller 128-bit shifts.
13092 if (VT.is256BitVector()) {
13093 unsigned NumElems = VT.getVectorNumElements();
13094 MVT EltVT = VT.getVectorElementType().getSimpleVT();
13095 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13097 // Extract the two vectors
13098 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13099 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13101 // Recreate the shift amount vectors
13102 SDValue Amt1, Amt2;
13103 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13104 // Constant shift amount
13105 SmallVector<SDValue, 4> Amt1Csts;
13106 SmallVector<SDValue, 4> Amt2Csts;
13107 for (unsigned i = 0; i != NumElems/2; ++i)
13108 Amt1Csts.push_back(Amt->getOperand(i));
13109 for (unsigned i = NumElems/2; i != NumElems; ++i)
13110 Amt2Csts.push_back(Amt->getOperand(i));
13112 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13113 &Amt1Csts[0], NumElems/2);
13114 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13115 &Amt2Csts[0], NumElems/2);
13117 // Variable shift amount
13118 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13119 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13122 // Issue new vector shifts for the smaller types
13123 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13124 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13126 // Concatenate the result back
13127 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13133 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13134 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13135 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13136 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13137 // has only one use.
13138 SDNode *N = Op.getNode();
13139 SDValue LHS = N->getOperand(0);
13140 SDValue RHS = N->getOperand(1);
13141 unsigned BaseOp = 0;
13144 switch (Op.getOpcode()) {
13145 default: llvm_unreachable("Unknown ovf instruction!");
13147 // A subtract of one will be selected as a INC. Note that INC doesn't
13148 // set CF, so we can't do this for UADDO.
13149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13151 BaseOp = X86ISD::INC;
13152 Cond = X86::COND_O;
13155 BaseOp = X86ISD::ADD;
13156 Cond = X86::COND_O;
13159 BaseOp = X86ISD::ADD;
13160 Cond = X86::COND_B;
13163 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13164 // set CF, so we can't do this for USUBO.
13165 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13167 BaseOp = X86ISD::DEC;
13168 Cond = X86::COND_O;
13171 BaseOp = X86ISD::SUB;
13172 Cond = X86::COND_O;
13175 BaseOp = X86ISD::SUB;
13176 Cond = X86::COND_B;
13179 BaseOp = X86ISD::SMUL;
13180 Cond = X86::COND_O;
13182 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13183 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13185 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13188 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13189 DAG.getConstant(X86::COND_O, MVT::i32),
13190 SDValue(Sum.getNode(), 2));
13192 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13196 // Also sets EFLAGS.
13197 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13198 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13201 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13202 DAG.getConstant(Cond, MVT::i32),
13203 SDValue(Sum.getNode(), 1));
13205 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13208 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13209 SelectionDAG &DAG) const {
13211 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13212 EVT VT = Op.getValueType();
13214 if (!Subtarget->hasSSE2() || !VT.isVector())
13217 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13218 ExtraVT.getScalarType().getSizeInBits();
13220 switch (VT.getSimpleVT().SimpleTy) {
13221 default: return SDValue();
13224 if (!Subtarget->hasFp256())
13226 if (!Subtarget->hasInt256()) {
13227 // needs to be split
13228 unsigned NumElems = VT.getVectorNumElements();
13230 // Extract the LHS vectors
13231 SDValue LHS = Op.getOperand(0);
13232 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13233 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13235 MVT EltVT = VT.getVectorElementType().getSimpleVT();
13236 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13238 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13239 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13240 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13242 SDValue Extra = DAG.getValueType(ExtraVT);
13244 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13245 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13247 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13252 SDValue Op0 = Op.getOperand(0);
13253 SDValue Op00 = Op0.getOperand(0);
13255 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13256 if (Op0.getOpcode() == ISD::BITCAST &&
13257 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13258 // (sext (vzext x)) -> (vsext x)
13259 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13260 if (Tmp1.getNode()) {
13261 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13262 // This folding is only valid when the in-reg type is a vector of i8,
13264 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13265 ExtraEltVT == MVT::i32) {
13266 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13267 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13268 "This optimization is invalid without a VZEXT.");
13269 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13275 // If the above didn't work, then just use Shift-Left + Shift-Right.
13276 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13278 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13284 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13285 SelectionDAG &DAG) {
13287 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13288 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13289 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13290 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13292 // The only fence that needs an instruction is a sequentially-consistent
13293 // cross-thread fence.
13294 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13295 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13296 // no-sse2). There isn't any reason to disable it if the target processor
13298 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13299 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13301 SDValue Chain = Op.getOperand(0);
13302 SDValue Zero = DAG.getConstant(0, MVT::i32);
13304 DAG.getRegister(X86::ESP, MVT::i32), // Base
13305 DAG.getTargetConstant(1, MVT::i8), // Scale
13306 DAG.getRegister(0, MVT::i32), // Index
13307 DAG.getTargetConstant(0, MVT::i32), // Disp
13308 DAG.getRegister(0, MVT::i32), // Segment.
13312 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13313 return SDValue(Res, 0);
13316 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13317 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13320 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13321 SelectionDAG &DAG) {
13322 EVT T = Op.getValueType();
13326 switch(T.getSimpleVT().SimpleTy) {
13327 default: llvm_unreachable("Invalid value type!");
13328 case MVT::i8: Reg = X86::AL; size = 1; break;
13329 case MVT::i16: Reg = X86::AX; size = 2; break;
13330 case MVT::i32: Reg = X86::EAX; size = 4; break;
13332 assert(Subtarget->is64Bit() && "Node not type legal!");
13333 Reg = X86::RAX; size = 8;
13336 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13337 Op.getOperand(2), SDValue());
13338 SDValue Ops[] = { cpIn.getValue(0),
13341 DAG.getTargetConstant(size, MVT::i8),
13342 cpIn.getValue(1) };
13343 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13344 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13345 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13346 Ops, array_lengthof(Ops), T, MMO);
13348 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13352 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13353 SelectionDAG &DAG) {
13354 assert(Subtarget->is64Bit() && "Result not type legalized?");
13355 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13356 SDValue TheChain = Op.getOperand(0);
13358 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13359 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13360 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13362 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13363 DAG.getConstant(32, MVT::i8));
13365 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13368 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13371 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13372 SelectionDAG &DAG) {
13373 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13374 MVT DstVT = Op.getSimpleValueType();
13375 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13376 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13377 assert((DstVT == MVT::i64 ||
13378 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13379 "Unexpected custom BITCAST");
13380 // i64 <=> MMX conversions are Legal.
13381 if (SrcVT==MVT::i64 && DstVT.isVector())
13383 if (DstVT==MVT::i64 && SrcVT.isVector())
13385 // MMX <=> MMX conversions are Legal.
13386 if (SrcVT.isVector() && DstVT.isVector())
13388 // All other conversions need to be expanded.
13392 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13393 SDNode *Node = Op.getNode();
13395 EVT T = Node->getValueType(0);
13396 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13397 DAG.getConstant(0, T), Node->getOperand(2));
13398 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13399 cast<AtomicSDNode>(Node)->getMemoryVT(),
13400 Node->getOperand(0),
13401 Node->getOperand(1), negOp,
13402 cast<AtomicSDNode>(Node)->getSrcValue(),
13403 cast<AtomicSDNode>(Node)->getAlignment(),
13404 cast<AtomicSDNode>(Node)->getOrdering(),
13405 cast<AtomicSDNode>(Node)->getSynchScope());
13408 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13409 SDNode *Node = Op.getNode();
13411 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13413 // Convert seq_cst store -> xchg
13414 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13415 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13416 // (The only way to get a 16-byte store is cmpxchg16b)
13417 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13418 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13419 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13420 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13421 cast<AtomicSDNode>(Node)->getMemoryVT(),
13422 Node->getOperand(0),
13423 Node->getOperand(1), Node->getOperand(2),
13424 cast<AtomicSDNode>(Node)->getMemOperand(),
13425 cast<AtomicSDNode>(Node)->getOrdering(),
13426 cast<AtomicSDNode>(Node)->getSynchScope());
13427 return Swap.getValue(1);
13429 // Other atomic stores have a simple pattern.
13433 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13434 EVT VT = Op.getNode()->getValueType(0);
13436 // Let legalize expand this if it isn't a legal type yet.
13437 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13440 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13443 bool ExtraOp = false;
13444 switch (Op.getOpcode()) {
13445 default: llvm_unreachable("Invalid code");
13446 case ISD::ADDC: Opc = X86ISD::ADD; break;
13447 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13448 case ISD::SUBC: Opc = X86ISD::SUB; break;
13449 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13453 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13455 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13456 Op.getOperand(1), Op.getOperand(2));
13459 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13460 SelectionDAG &DAG) {
13461 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13463 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13464 // which returns the values as { float, float } (in XMM0) or
13465 // { double, double } (which is returned in XMM0, XMM1).
13467 SDValue Arg = Op.getOperand(0);
13468 EVT ArgVT = Arg.getValueType();
13469 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13471 TargetLowering::ArgListTy Args;
13472 TargetLowering::ArgListEntry Entry;
13476 Entry.isSExt = false;
13477 Entry.isZExt = false;
13478 Args.push_back(Entry);
13480 bool isF64 = ArgVT == MVT::f64;
13481 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13482 // the small struct {f32, f32} is returned in (eax, edx). For f64,
13483 // the results are returned via SRet in memory.
13484 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
13485 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13486 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13488 Type *RetTy = isF64
13489 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13490 : (Type*)VectorType::get(ArgTy, 4);
13492 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13493 false, false, false, false, 0,
13494 CallingConv::C, /*isTaillCall=*/false,
13495 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13496 Callee, Args, DAG, dl);
13497 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13500 // Returned in xmm0 and xmm1.
13501 return CallResult.first;
13503 // Returned in bits 0:31 and 32:64 xmm0.
13504 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13505 CallResult.first, DAG.getIntPtrConstant(0));
13506 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13507 CallResult.first, DAG.getIntPtrConstant(1));
13508 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13509 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13512 /// LowerOperation - Provide custom lowering hooks for some operations.
13514 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13515 switch (Op.getOpcode()) {
13516 default: llvm_unreachable("Should not custom lower this!");
13517 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
13518 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13519 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
13520 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
13521 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
13522 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13523 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
13524 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13525 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13526 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13527 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13528 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13529 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13530 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13531 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13532 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13533 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
13534 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13535 case ISD::SHL_PARTS:
13536 case ISD::SRA_PARTS:
13537 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
13538 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
13539 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
13540 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13541 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
13542 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13543 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
13544 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
13545 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
13546 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
13547 case ISD::FABS: return LowerFABS(Op, DAG);
13548 case ISD::FNEG: return LowerFNEG(Op, DAG);
13549 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
13550 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
13551 case ISD::SETCC: return LowerSETCC(Op, DAG);
13552 case ISD::SELECT: return LowerSELECT(Op, DAG);
13553 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
13554 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
13555 case ISD::VASTART: return LowerVASTART(Op, DAG);
13556 case ISD::VAARG: return LowerVAARG(Op, DAG);
13557 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
13558 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13559 case ISD::INTRINSIC_VOID:
13560 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13561 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
13562 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
13563 case ISD::FRAME_TO_ARGS_OFFSET:
13564 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13565 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13566 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
13567 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
13568 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
13569 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
13570 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
13571 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
13572 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
13573 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13574 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
13575 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
13578 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
13584 case ISD::UMULO: return LowerXALUO(Op, DAG);
13585 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13586 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
13590 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13591 case ISD::ADD: return LowerADD(Op, DAG);
13592 case ISD::SUB: return LowerSUB(Op, DAG);
13593 case ISD::SDIV: return LowerSDIV(Op, DAG);
13594 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
13598 static void ReplaceATOMIC_LOAD(SDNode *Node,
13599 SmallVectorImpl<SDValue> &Results,
13600 SelectionDAG &DAG) {
13602 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13604 // Convert wide load -> cmpxchg8b/cmpxchg16b
13605 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13606 // (The only way to get a 16-byte load is cmpxchg16b)
13607 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13608 SDValue Zero = DAG.getConstant(0, VT);
13609 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13610 Node->getOperand(0),
13611 Node->getOperand(1), Zero, Zero,
13612 cast<AtomicSDNode>(Node)->getMemOperand(),
13613 cast<AtomicSDNode>(Node)->getOrdering(),
13614 cast<AtomicSDNode>(Node)->getSynchScope());
13615 Results.push_back(Swap.getValue(0));
13616 Results.push_back(Swap.getValue(1));
13620 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13621 SelectionDAG &DAG, unsigned NewOp) {
13623 assert (Node->getValueType(0) == MVT::i64 &&
13624 "Only know how to expand i64 atomics");
13626 SDValue Chain = Node->getOperand(0);
13627 SDValue In1 = Node->getOperand(1);
13628 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13629 Node->getOperand(2), DAG.getIntPtrConstant(0));
13630 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13631 Node->getOperand(2), DAG.getIntPtrConstant(1));
13632 SDValue Ops[] = { Chain, In1, In2L, In2H };
13633 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13635 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13636 cast<MemSDNode>(Node)->getMemOperand());
13637 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13638 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13639 Results.push_back(Result.getValue(2));
13642 /// ReplaceNodeResults - Replace a node with an illegal result type
13643 /// with a new node built out of custom code.
13644 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13645 SmallVectorImpl<SDValue>&Results,
13646 SelectionDAG &DAG) const {
13648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13649 switch (N->getOpcode()) {
13651 llvm_unreachable("Do not know how to custom type legalize this operation!");
13652 case ISD::SIGN_EXTEND_INREG:
13657 // We don't want to expand or promote these.
13659 case ISD::FP_TO_SINT:
13660 case ISD::FP_TO_UINT: {
13661 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13663 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13666 std::pair<SDValue,SDValue> Vals =
13667 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13668 SDValue FIST = Vals.first, StackSlot = Vals.second;
13669 if (FIST.getNode() != 0) {
13670 EVT VT = N->getValueType(0);
13671 // Return a load from the stack slot.
13672 if (StackSlot.getNode() != 0)
13673 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13674 MachinePointerInfo(),
13675 false, false, false, 0));
13677 Results.push_back(FIST);
13681 case ISD::UINT_TO_FP: {
13682 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13683 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13684 N->getValueType(0) != MVT::v2f32)
13686 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13688 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13690 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13691 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13692 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13693 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13694 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13695 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13698 case ISD::FP_ROUND: {
13699 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13701 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13702 Results.push_back(V);
13705 case ISD::READCYCLECOUNTER: {
13706 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13707 SDValue TheChain = N->getOperand(0);
13708 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13709 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13711 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13713 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13714 SDValue Ops[] = { eax, edx };
13715 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13716 array_lengthof(Ops)));
13717 Results.push_back(edx.getValue(1));
13720 case ISD::ATOMIC_CMP_SWAP: {
13721 EVT T = N->getValueType(0);
13722 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13723 bool Regs64bit = T == MVT::i128;
13724 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13725 SDValue cpInL, cpInH;
13726 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13727 DAG.getConstant(0, HalfT));
13728 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13729 DAG.getConstant(1, HalfT));
13730 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13731 Regs64bit ? X86::RAX : X86::EAX,
13733 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13734 Regs64bit ? X86::RDX : X86::EDX,
13735 cpInH, cpInL.getValue(1));
13736 SDValue swapInL, swapInH;
13737 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13738 DAG.getConstant(0, HalfT));
13739 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13740 DAG.getConstant(1, HalfT));
13741 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13742 Regs64bit ? X86::RBX : X86::EBX,
13743 swapInL, cpInH.getValue(1));
13744 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13745 Regs64bit ? X86::RCX : X86::ECX,
13746 swapInH, swapInL.getValue(1));
13747 SDValue Ops[] = { swapInH.getValue(0),
13749 swapInH.getValue(1) };
13750 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13751 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13752 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13753 X86ISD::LCMPXCHG8_DAG;
13754 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13755 Ops, array_lengthof(Ops), T, MMO);
13756 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13757 Regs64bit ? X86::RAX : X86::EAX,
13758 HalfT, Result.getValue(1));
13759 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13760 Regs64bit ? X86::RDX : X86::EDX,
13761 HalfT, cpOutL.getValue(2));
13762 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13763 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13764 Results.push_back(cpOutH.getValue(1));
13767 case ISD::ATOMIC_LOAD_ADD:
13768 case ISD::ATOMIC_LOAD_AND:
13769 case ISD::ATOMIC_LOAD_NAND:
13770 case ISD::ATOMIC_LOAD_OR:
13771 case ISD::ATOMIC_LOAD_SUB:
13772 case ISD::ATOMIC_LOAD_XOR:
13773 case ISD::ATOMIC_LOAD_MAX:
13774 case ISD::ATOMIC_LOAD_MIN:
13775 case ISD::ATOMIC_LOAD_UMAX:
13776 case ISD::ATOMIC_LOAD_UMIN:
13777 case ISD::ATOMIC_SWAP: {
13779 switch (N->getOpcode()) {
13780 default: llvm_unreachable("Unexpected opcode");
13781 case ISD::ATOMIC_LOAD_ADD:
13782 Opc = X86ISD::ATOMADD64_DAG;
13784 case ISD::ATOMIC_LOAD_AND:
13785 Opc = X86ISD::ATOMAND64_DAG;
13787 case ISD::ATOMIC_LOAD_NAND:
13788 Opc = X86ISD::ATOMNAND64_DAG;
13790 case ISD::ATOMIC_LOAD_OR:
13791 Opc = X86ISD::ATOMOR64_DAG;
13793 case ISD::ATOMIC_LOAD_SUB:
13794 Opc = X86ISD::ATOMSUB64_DAG;
13796 case ISD::ATOMIC_LOAD_XOR:
13797 Opc = X86ISD::ATOMXOR64_DAG;
13799 case ISD::ATOMIC_LOAD_MAX:
13800 Opc = X86ISD::ATOMMAX64_DAG;
13802 case ISD::ATOMIC_LOAD_MIN:
13803 Opc = X86ISD::ATOMMIN64_DAG;
13805 case ISD::ATOMIC_LOAD_UMAX:
13806 Opc = X86ISD::ATOMUMAX64_DAG;
13808 case ISD::ATOMIC_LOAD_UMIN:
13809 Opc = X86ISD::ATOMUMIN64_DAG;
13811 case ISD::ATOMIC_SWAP:
13812 Opc = X86ISD::ATOMSWAP64_DAG;
13815 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13818 case ISD::ATOMIC_LOAD:
13819 ReplaceATOMIC_LOAD(N, Results, DAG);
13823 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13825 default: return NULL;
13826 case X86ISD::BSF: return "X86ISD::BSF";
13827 case X86ISD::BSR: return "X86ISD::BSR";
13828 case X86ISD::SHLD: return "X86ISD::SHLD";
13829 case X86ISD::SHRD: return "X86ISD::SHRD";
13830 case X86ISD::FAND: return "X86ISD::FAND";
13831 case X86ISD::FANDN: return "X86ISD::FANDN";
13832 case X86ISD::FOR: return "X86ISD::FOR";
13833 case X86ISD::FXOR: return "X86ISD::FXOR";
13834 case X86ISD::FSRL: return "X86ISD::FSRL";
13835 case X86ISD::FILD: return "X86ISD::FILD";
13836 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
13837 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13838 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13839 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13840 case X86ISD::FLD: return "X86ISD::FLD";
13841 case X86ISD::FST: return "X86ISD::FST";
13842 case X86ISD::CALL: return "X86ISD::CALL";
13843 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
13844 case X86ISD::BT: return "X86ISD::BT";
13845 case X86ISD::CMP: return "X86ISD::CMP";
13846 case X86ISD::COMI: return "X86ISD::COMI";
13847 case X86ISD::UCOMI: return "X86ISD::UCOMI";
13848 case X86ISD::CMPM: return "X86ISD::CMPM";
13849 case X86ISD::CMPMU: return "X86ISD::CMPMU";
13850 case X86ISD::SETCC: return "X86ISD::SETCC";
13851 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
13852 case X86ISD::FSETCC: return "X86ISD::FSETCC";
13853 case X86ISD::CMOV: return "X86ISD::CMOV";
13854 case X86ISD::BRCOND: return "X86ISD::BRCOND";
13855 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
13856 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
13857 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
13858 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
13859 case X86ISD::Wrapper: return "X86ISD::Wrapper";
13860 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
13861 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
13862 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
13863 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
13864 case X86ISD::PINSRB: return "X86ISD::PINSRB";
13865 case X86ISD::PINSRW: return "X86ISD::PINSRW";
13866 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
13867 case X86ISD::ANDNP: return "X86ISD::ANDNP";
13868 case X86ISD::PSIGN: return "X86ISD::PSIGN";
13869 case X86ISD::BLENDV: return "X86ISD::BLENDV";
13870 case X86ISD::BLENDI: return "X86ISD::BLENDI";
13871 case X86ISD::SUBUS: return "X86ISD::SUBUS";
13872 case X86ISD::HADD: return "X86ISD::HADD";
13873 case X86ISD::HSUB: return "X86ISD::HSUB";
13874 case X86ISD::FHADD: return "X86ISD::FHADD";
13875 case X86ISD::FHSUB: return "X86ISD::FHSUB";
13876 case X86ISD::UMAX: return "X86ISD::UMAX";
13877 case X86ISD::UMIN: return "X86ISD::UMIN";
13878 case X86ISD::SMAX: return "X86ISD::SMAX";
13879 case X86ISD::SMIN: return "X86ISD::SMIN";
13880 case X86ISD::FMAX: return "X86ISD::FMAX";
13881 case X86ISD::FMIN: return "X86ISD::FMIN";
13882 case X86ISD::FMAXC: return "X86ISD::FMAXC";
13883 case X86ISD::FMINC: return "X86ISD::FMINC";
13884 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
13885 case X86ISD::FRCP: return "X86ISD::FRCP";
13886 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
13887 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
13888 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
13889 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
13890 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
13891 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
13892 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
13893 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
13894 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
13895 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
13896 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
13897 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
13898 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
13899 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
13900 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
13901 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
13902 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
13903 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
13904 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
13905 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
13906 case X86ISD::VZEXT: return "X86ISD::VZEXT";
13907 case X86ISD::VSEXT: return "X86ISD::VSEXT";
13908 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
13909 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
13910 case X86ISD::VINSERT: return "X86ISD::VINSERT";
13911 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
13912 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
13913 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
13914 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
13915 case X86ISD::VSHL: return "X86ISD::VSHL";
13916 case X86ISD::VSRL: return "X86ISD::VSRL";
13917 case X86ISD::VSRA: return "X86ISD::VSRA";
13918 case X86ISD::VSHLI: return "X86ISD::VSHLI";
13919 case X86ISD::VSRLI: return "X86ISD::VSRLI";
13920 case X86ISD::VSRAI: return "X86ISD::VSRAI";
13921 case X86ISD::CMPP: return "X86ISD::CMPP";
13922 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
13923 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
13924 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
13925 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
13926 case X86ISD::ADD: return "X86ISD::ADD";
13927 case X86ISD::SUB: return "X86ISD::SUB";
13928 case X86ISD::ADC: return "X86ISD::ADC";
13929 case X86ISD::SBB: return "X86ISD::SBB";
13930 case X86ISD::SMUL: return "X86ISD::SMUL";
13931 case X86ISD::UMUL: return "X86ISD::UMUL";
13932 case X86ISD::INC: return "X86ISD::INC";
13933 case X86ISD::DEC: return "X86ISD::DEC";
13934 case X86ISD::OR: return "X86ISD::OR";
13935 case X86ISD::XOR: return "X86ISD::XOR";
13936 case X86ISD::AND: return "X86ISD::AND";
13937 case X86ISD::BLSI: return "X86ISD::BLSI";
13938 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
13939 case X86ISD::BLSR: return "X86ISD::BLSR";
13940 case X86ISD::BZHI: return "X86ISD::BZHI";
13941 case X86ISD::BEXTR: return "X86ISD::BEXTR";
13942 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
13943 case X86ISD::PTEST: return "X86ISD::PTEST";
13944 case X86ISD::TESTP: return "X86ISD::TESTP";
13945 case X86ISD::TESTM: return "X86ISD::TESTM";
13946 case X86ISD::KORTEST: return "X86ISD::KORTEST";
13947 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
13948 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
13949 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
13950 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
13951 case X86ISD::SHUFP: return "X86ISD::SHUFP";
13952 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
13953 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
13954 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
13955 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
13956 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
13957 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
13958 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
13959 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
13960 case X86ISD::MOVSD: return "X86ISD::MOVSD";
13961 case X86ISD::MOVSS: return "X86ISD::MOVSS";
13962 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
13963 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
13964 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
13965 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
13966 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
13967 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
13968 case X86ISD::VPERMV: return "X86ISD::VPERMV";
13969 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
13970 case X86ISD::VPERMI: return "X86ISD::VPERMI";
13971 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
13972 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13973 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
13974 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
13975 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
13976 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
13977 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
13978 case X86ISD::SAHF: return "X86ISD::SAHF";
13979 case X86ISD::RDRAND: return "X86ISD::RDRAND";
13980 case X86ISD::RDSEED: return "X86ISD::RDSEED";
13981 case X86ISD::FMADD: return "X86ISD::FMADD";
13982 case X86ISD::FMSUB: return "X86ISD::FMSUB";
13983 case X86ISD::FNMADD: return "X86ISD::FNMADD";
13984 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
13985 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
13986 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
13987 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
13988 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
13989 case X86ISD::XTEST: return "X86ISD::XTEST";
13993 // isLegalAddressingMode - Return true if the addressing mode represented
13994 // by AM is legal for this target, for a load/store of the specified type.
13995 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13997 // X86 supports extremely general addressing modes.
13998 CodeModel::Model M = getTargetMachine().getCodeModel();
13999 Reloc::Model R = getTargetMachine().getRelocationModel();
14001 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14002 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14007 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14009 // If a reference to this global requires an extra load, we can't fold it.
14010 if (isGlobalStubReference(GVFlags))
14013 // If BaseGV requires a register for the PIC base, we cannot also have a
14014 // BaseReg specified.
14015 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14018 // If lower 4G is not available, then we must use rip-relative addressing.
14019 if ((M != CodeModel::Small || R != Reloc::Static) &&
14020 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14024 switch (AM.Scale) {
14030 // These scales always work.
14035 // These scales are formed with basereg+scalereg. Only accept if there is
14040 default: // Other stuff never works.
14047 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14048 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14050 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14051 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14052 return NumBits1 > NumBits2;
14055 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14056 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14059 if (!isTypeLegal(EVT::getEVT(Ty1)))
14062 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14064 // Assuming the caller doesn't have a zeroext or signext return parameter,
14065 // truncation all the way down to i1 is valid.
14069 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14070 return isInt<32>(Imm);
14073 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14074 // Can also use sub to handle negated immediates.
14075 return isInt<32>(Imm);
14078 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14079 if (!VT1.isInteger() || !VT2.isInteger())
14081 unsigned NumBits1 = VT1.getSizeInBits();
14082 unsigned NumBits2 = VT2.getSizeInBits();
14083 return NumBits1 > NumBits2;
14086 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14087 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14088 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14091 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14092 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14093 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14096 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14097 EVT VT1 = Val.getValueType();
14098 if (isZExtFree(VT1, VT2))
14101 if (Val.getOpcode() != ISD::LOAD)
14104 if (!VT1.isSimple() || !VT1.isInteger() ||
14105 !VT2.isSimple() || !VT2.isInteger())
14108 switch (VT1.getSimpleVT().SimpleTy) {
14113 // X86 has 8, 16, and 32-bit zero-extending loads.
14121 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14122 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14125 VT = VT.getScalarType();
14127 if (!VT.isSimple())
14130 switch (VT.getSimpleVT().SimpleTy) {
14141 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14142 // i16 instructions are longer (0x66 prefix) and potentially slower.
14143 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14146 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14147 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14148 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14149 /// are assumed to be legal.
14151 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14153 if (!VT.isSimple())
14156 MVT SVT = VT.getSimpleVT();
14158 // Very little shuffling can be done for 64-bit vectors right now.
14159 if (VT.getSizeInBits() == 64)
14162 // FIXME: pshufb, blends, shifts.
14163 return (SVT.getVectorNumElements() == 2 ||
14164 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14165 isMOVLMask(M, SVT) ||
14166 isSHUFPMask(M, SVT) ||
14167 isPSHUFDMask(M, SVT) ||
14168 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14169 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14170 isPALIGNRMask(M, SVT, Subtarget) ||
14171 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14172 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14173 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14174 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14178 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14180 if (!VT.isSimple())
14183 MVT SVT = VT.getSimpleVT();
14184 unsigned NumElts = SVT.getVectorNumElements();
14185 // FIXME: This collection of masks seems suspect.
14188 if (NumElts == 4 && SVT.is128BitVector()) {
14189 return (isMOVLMask(Mask, SVT) ||
14190 isCommutedMOVLMask(Mask, SVT, true) ||
14191 isSHUFPMask(Mask, SVT) ||
14192 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14197 //===----------------------------------------------------------------------===//
14198 // X86 Scheduler Hooks
14199 //===----------------------------------------------------------------------===//
14201 /// Utility function to emit xbegin specifying the start of an RTM region.
14202 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14203 const TargetInstrInfo *TII) {
14204 DebugLoc DL = MI->getDebugLoc();
14206 const BasicBlock *BB = MBB->getBasicBlock();
14207 MachineFunction::iterator I = MBB;
14210 // For the v = xbegin(), we generate
14221 MachineBasicBlock *thisMBB = MBB;
14222 MachineFunction *MF = MBB->getParent();
14223 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14224 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14225 MF->insert(I, mainMBB);
14226 MF->insert(I, sinkMBB);
14228 // Transfer the remainder of BB and its successor edges to sinkMBB.
14229 sinkMBB->splice(sinkMBB->begin(), MBB,
14230 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14231 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14235 // # fallthrough to mainMBB
14236 // # abortion to sinkMBB
14237 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14238 thisMBB->addSuccessor(mainMBB);
14239 thisMBB->addSuccessor(sinkMBB);
14243 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14244 mainMBB->addSuccessor(sinkMBB);
14247 // EAX is live into the sinkMBB
14248 sinkMBB->addLiveIn(X86::EAX);
14249 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14250 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14253 MI->eraseFromParent();
14257 // Get CMPXCHG opcode for the specified data type.
14258 static unsigned getCmpXChgOpcode(EVT VT) {
14259 switch (VT.getSimpleVT().SimpleTy) {
14260 case MVT::i8: return X86::LCMPXCHG8;
14261 case MVT::i16: return X86::LCMPXCHG16;
14262 case MVT::i32: return X86::LCMPXCHG32;
14263 case MVT::i64: return X86::LCMPXCHG64;
14267 llvm_unreachable("Invalid operand size!");
14270 // Get LOAD opcode for the specified data type.
14271 static unsigned getLoadOpcode(EVT VT) {
14272 switch (VT.getSimpleVT().SimpleTy) {
14273 case MVT::i8: return X86::MOV8rm;
14274 case MVT::i16: return X86::MOV16rm;
14275 case MVT::i32: return X86::MOV32rm;
14276 case MVT::i64: return X86::MOV64rm;
14280 llvm_unreachable("Invalid operand size!");
14283 // Get opcode of the non-atomic one from the specified atomic instruction.
14284 static unsigned getNonAtomicOpcode(unsigned Opc) {
14286 case X86::ATOMAND8: return X86::AND8rr;
14287 case X86::ATOMAND16: return X86::AND16rr;
14288 case X86::ATOMAND32: return X86::AND32rr;
14289 case X86::ATOMAND64: return X86::AND64rr;
14290 case X86::ATOMOR8: return X86::OR8rr;
14291 case X86::ATOMOR16: return X86::OR16rr;
14292 case X86::ATOMOR32: return X86::OR32rr;
14293 case X86::ATOMOR64: return X86::OR64rr;
14294 case X86::ATOMXOR8: return X86::XOR8rr;
14295 case X86::ATOMXOR16: return X86::XOR16rr;
14296 case X86::ATOMXOR32: return X86::XOR32rr;
14297 case X86::ATOMXOR64: return X86::XOR64rr;
14299 llvm_unreachable("Unhandled atomic-load-op opcode!");
14302 // Get opcode of the non-atomic one from the specified atomic instruction with
14304 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14305 unsigned &ExtraOpc) {
14307 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14308 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14309 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14310 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14311 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14312 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14313 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14314 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14315 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14316 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14317 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14318 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14319 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14320 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14321 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14322 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14323 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14324 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14325 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14326 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14328 llvm_unreachable("Unhandled atomic-load-op opcode!");
14331 // Get opcode of the non-atomic one from the specified atomic instruction for
14332 // 64-bit data type on 32-bit target.
14333 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14335 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14336 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14337 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14338 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14339 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14340 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14341 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14342 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14343 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14344 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14346 llvm_unreachable("Unhandled atomic-load-op opcode!");
14349 // Get opcode of the non-atomic one from the specified atomic instruction for
14350 // 64-bit data type on 32-bit target with extra opcode.
14351 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14353 unsigned &ExtraOpc) {
14355 case X86::ATOMNAND6432:
14356 ExtraOpc = X86::NOT32r;
14357 HiOpc = X86::AND32rr;
14358 return X86::AND32rr;
14360 llvm_unreachable("Unhandled atomic-load-op opcode!");
14363 // Get pseudo CMOV opcode from the specified data type.
14364 static unsigned getPseudoCMOVOpc(EVT VT) {
14365 switch (VT.getSimpleVT().SimpleTy) {
14366 case MVT::i8: return X86::CMOV_GR8;
14367 case MVT::i16: return X86::CMOV_GR16;
14368 case MVT::i32: return X86::CMOV_GR32;
14372 llvm_unreachable("Unknown CMOV opcode!");
14375 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14376 // They will be translated into a spin-loop or compare-exchange loop from
14379 // dst = atomic-fetch-op MI.addr, MI.val
14385 // t1 = LOAD MI.addr
14387 // t4 = phi(t1, t3 / loop)
14388 // t2 = OP MI.val, t4
14390 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14396 MachineBasicBlock *
14397 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14398 MachineBasicBlock *MBB) const {
14399 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14400 DebugLoc DL = MI->getDebugLoc();
14402 MachineFunction *MF = MBB->getParent();
14403 MachineRegisterInfo &MRI = MF->getRegInfo();
14405 const BasicBlock *BB = MBB->getBasicBlock();
14406 MachineFunction::iterator I = MBB;
14409 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14410 "Unexpected number of operands");
14412 assert(MI->hasOneMemOperand() &&
14413 "Expected atomic-load-op to have one memoperand");
14415 // Memory Reference
14416 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14417 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14419 unsigned DstReg, SrcReg;
14420 unsigned MemOpndSlot;
14422 unsigned CurOp = 0;
14424 DstReg = MI->getOperand(CurOp++).getReg();
14425 MemOpndSlot = CurOp;
14426 CurOp += X86::AddrNumOperands;
14427 SrcReg = MI->getOperand(CurOp++).getReg();
14429 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14430 MVT::SimpleValueType VT = *RC->vt_begin();
14431 unsigned t1 = MRI.createVirtualRegister(RC);
14432 unsigned t2 = MRI.createVirtualRegister(RC);
14433 unsigned t3 = MRI.createVirtualRegister(RC);
14434 unsigned t4 = MRI.createVirtualRegister(RC);
14435 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14437 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14438 unsigned LOADOpc = getLoadOpcode(VT);
14440 // For the atomic load-arith operator, we generate
14443 // t1 = LOAD [MI.addr]
14445 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14446 // t1 = OP MI.val, EAX
14448 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14454 MachineBasicBlock *thisMBB = MBB;
14455 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14456 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14457 MF->insert(I, mainMBB);
14458 MF->insert(I, sinkMBB);
14460 MachineInstrBuilder MIB;
14462 // Transfer the remainder of BB and its successor edges to sinkMBB.
14463 sinkMBB->splice(sinkMBB->begin(), MBB,
14464 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14465 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14468 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14469 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14470 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14472 NewMO.setIsKill(false);
14473 MIB.addOperand(NewMO);
14475 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14476 unsigned flags = (*MMOI)->getFlags();
14477 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14478 MachineMemOperand *MMO =
14479 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14480 (*MMOI)->getSize(),
14481 (*MMOI)->getBaseAlignment(),
14482 (*MMOI)->getTBAAInfo(),
14483 (*MMOI)->getRanges());
14484 MIB.addMemOperand(MMO);
14487 thisMBB->addSuccessor(mainMBB);
14490 MachineBasicBlock *origMainMBB = mainMBB;
14493 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14494 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14496 unsigned Opc = MI->getOpcode();
14499 llvm_unreachable("Unhandled atomic-load-op opcode!");
14500 case X86::ATOMAND8:
14501 case X86::ATOMAND16:
14502 case X86::ATOMAND32:
14503 case X86::ATOMAND64:
14505 case X86::ATOMOR16:
14506 case X86::ATOMOR32:
14507 case X86::ATOMOR64:
14508 case X86::ATOMXOR8:
14509 case X86::ATOMXOR16:
14510 case X86::ATOMXOR32:
14511 case X86::ATOMXOR64: {
14512 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14513 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14517 case X86::ATOMNAND8:
14518 case X86::ATOMNAND16:
14519 case X86::ATOMNAND32:
14520 case X86::ATOMNAND64: {
14521 unsigned Tmp = MRI.createVirtualRegister(RC);
14523 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14524 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14526 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14529 case X86::ATOMMAX8:
14530 case X86::ATOMMAX16:
14531 case X86::ATOMMAX32:
14532 case X86::ATOMMAX64:
14533 case X86::ATOMMIN8:
14534 case X86::ATOMMIN16:
14535 case X86::ATOMMIN32:
14536 case X86::ATOMMIN64:
14537 case X86::ATOMUMAX8:
14538 case X86::ATOMUMAX16:
14539 case X86::ATOMUMAX32:
14540 case X86::ATOMUMAX64:
14541 case X86::ATOMUMIN8:
14542 case X86::ATOMUMIN16:
14543 case X86::ATOMUMIN32:
14544 case X86::ATOMUMIN64: {
14546 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14548 BuildMI(mainMBB, DL, TII->get(CMPOpc))
14552 if (Subtarget->hasCMov()) {
14553 if (VT != MVT::i8) {
14555 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14559 // Promote i8 to i32 to use CMOV32
14560 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14561 const TargetRegisterClass *RC32 =
14562 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14563 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14564 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14565 unsigned Tmp = MRI.createVirtualRegister(RC32);
14567 unsigned Undef = MRI.createVirtualRegister(RC32);
14568 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14570 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14573 .addImm(X86::sub_8bit);
14574 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14577 .addImm(X86::sub_8bit);
14579 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14583 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14584 .addReg(Tmp, 0, X86::sub_8bit);
14587 // Use pseudo select and lower them.
14588 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14589 "Invalid atomic-load-op transformation!");
14590 unsigned SelOpc = getPseudoCMOVOpc(VT);
14591 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14592 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14593 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14594 .addReg(SrcReg).addReg(t4)
14596 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14597 // Replace the original PHI node as mainMBB is changed after CMOV
14599 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14600 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14601 Phi->eraseFromParent();
14607 // Copy PhyReg back from virtual register.
14608 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14611 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14612 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14613 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14615 NewMO.setIsKill(false);
14616 MIB.addOperand(NewMO);
14619 MIB.setMemRefs(MMOBegin, MMOEnd);
14621 // Copy PhyReg back to virtual register.
14622 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14625 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14627 mainMBB->addSuccessor(origMainMBB);
14628 mainMBB->addSuccessor(sinkMBB);
14631 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14632 TII->get(TargetOpcode::COPY), DstReg)
14635 MI->eraseFromParent();
14639 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14640 // instructions. They will be translated into a spin-loop or compare-exchange
14644 // dst = atomic-fetch-op MI.addr, MI.val
14650 // t1L = LOAD [MI.addr + 0]
14651 // t1H = LOAD [MI.addr + 4]
14653 // t4L = phi(t1L, t3L / loop)
14654 // t4H = phi(t1H, t3H / loop)
14655 // t2L = OP MI.val.lo, t4L
14656 // t2H = OP MI.val.hi, t4H
14661 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14669 MachineBasicBlock *
14670 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14671 MachineBasicBlock *MBB) const {
14672 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14673 DebugLoc DL = MI->getDebugLoc();
14675 MachineFunction *MF = MBB->getParent();
14676 MachineRegisterInfo &MRI = MF->getRegInfo();
14678 const BasicBlock *BB = MBB->getBasicBlock();
14679 MachineFunction::iterator I = MBB;
14682 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14683 "Unexpected number of operands");
14685 assert(MI->hasOneMemOperand() &&
14686 "Expected atomic-load-op32 to have one memoperand");
14688 // Memory Reference
14689 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14690 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14692 unsigned DstLoReg, DstHiReg;
14693 unsigned SrcLoReg, SrcHiReg;
14694 unsigned MemOpndSlot;
14696 unsigned CurOp = 0;
14698 DstLoReg = MI->getOperand(CurOp++).getReg();
14699 DstHiReg = MI->getOperand(CurOp++).getReg();
14700 MemOpndSlot = CurOp;
14701 CurOp += X86::AddrNumOperands;
14702 SrcLoReg = MI->getOperand(CurOp++).getReg();
14703 SrcHiReg = MI->getOperand(CurOp++).getReg();
14705 const TargetRegisterClass *RC = &X86::GR32RegClass;
14706 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14708 unsigned t1L = MRI.createVirtualRegister(RC);
14709 unsigned t1H = MRI.createVirtualRegister(RC);
14710 unsigned t2L = MRI.createVirtualRegister(RC);
14711 unsigned t2H = MRI.createVirtualRegister(RC);
14712 unsigned t3L = MRI.createVirtualRegister(RC);
14713 unsigned t3H = MRI.createVirtualRegister(RC);
14714 unsigned t4L = MRI.createVirtualRegister(RC);
14715 unsigned t4H = MRI.createVirtualRegister(RC);
14717 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14718 unsigned LOADOpc = X86::MOV32rm;
14720 // For the atomic load-arith operator, we generate
14723 // t1L = LOAD [MI.addr + 0]
14724 // t1H = LOAD [MI.addr + 4]
14726 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14727 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14728 // t2L = OP MI.val.lo, t4L
14729 // t2H = OP MI.val.hi, t4H
14732 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14740 MachineBasicBlock *thisMBB = MBB;
14741 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14742 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14743 MF->insert(I, mainMBB);
14744 MF->insert(I, sinkMBB);
14746 MachineInstrBuilder MIB;
14748 // Transfer the remainder of BB and its successor edges to sinkMBB.
14749 sinkMBB->splice(sinkMBB->begin(), MBB,
14750 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14751 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14755 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14756 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14757 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14759 NewMO.setIsKill(false);
14760 MIB.addOperand(NewMO);
14762 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14763 unsigned flags = (*MMOI)->getFlags();
14764 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14765 MachineMemOperand *MMO =
14766 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14767 (*MMOI)->getSize(),
14768 (*MMOI)->getBaseAlignment(),
14769 (*MMOI)->getTBAAInfo(),
14770 (*MMOI)->getRanges());
14771 MIB.addMemOperand(MMO);
14773 MachineInstr *LowMI = MIB;
14776 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14777 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14778 if (i == X86::AddrDisp) {
14779 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14781 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14783 NewMO.setIsKill(false);
14784 MIB.addOperand(NewMO);
14787 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14789 thisMBB->addSuccessor(mainMBB);
14792 MachineBasicBlock *origMainMBB = mainMBB;
14795 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14796 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14797 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14798 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14800 unsigned Opc = MI->getOpcode();
14803 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14804 case X86::ATOMAND6432:
14805 case X86::ATOMOR6432:
14806 case X86::ATOMXOR6432:
14807 case X86::ATOMADD6432:
14808 case X86::ATOMSUB6432: {
14810 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14811 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14813 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14817 case X86::ATOMNAND6432: {
14818 unsigned HiOpc, NOTOpc;
14819 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14820 unsigned TmpL = MRI.createVirtualRegister(RC);
14821 unsigned TmpH = MRI.createVirtualRegister(RC);
14822 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14824 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14826 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14827 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14830 case X86::ATOMMAX6432:
14831 case X86::ATOMMIN6432:
14832 case X86::ATOMUMAX6432:
14833 case X86::ATOMUMIN6432: {
14835 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14836 unsigned cL = MRI.createVirtualRegister(RC8);
14837 unsigned cH = MRI.createVirtualRegister(RC8);
14838 unsigned cL32 = MRI.createVirtualRegister(RC);
14839 unsigned cH32 = MRI.createVirtualRegister(RC);
14840 unsigned cc = MRI.createVirtualRegister(RC);
14841 // cl := cmp src_lo, lo
14842 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14843 .addReg(SrcLoReg).addReg(t4L);
14844 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14845 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14846 // ch := cmp src_hi, hi
14847 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14848 .addReg(SrcHiReg).addReg(t4H);
14849 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14850 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14851 // cc := if (src_hi == hi) ? cl : ch;
14852 if (Subtarget->hasCMov()) {
14853 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14854 .addReg(cH32).addReg(cL32);
14856 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14857 .addReg(cH32).addReg(cL32)
14858 .addImm(X86::COND_E);
14859 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14861 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14862 if (Subtarget->hasCMov()) {
14863 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14864 .addReg(SrcLoReg).addReg(t4L);
14865 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14866 .addReg(SrcHiReg).addReg(t4H);
14868 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14869 .addReg(SrcLoReg).addReg(t4L)
14870 .addImm(X86::COND_NE);
14871 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14872 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14873 // 2nd CMOV lowering.
14874 mainMBB->addLiveIn(X86::EFLAGS);
14875 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14876 .addReg(SrcHiReg).addReg(t4H)
14877 .addImm(X86::COND_NE);
14878 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14879 // Replace the original PHI node as mainMBB is changed after CMOV
14881 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14882 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14883 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14884 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14885 PhiL->eraseFromParent();
14886 PhiH->eraseFromParent();
14890 case X86::ATOMSWAP6432: {
14892 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14893 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14894 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14899 // Copy EDX:EAX back from HiReg:LoReg
14900 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14901 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14902 // Copy ECX:EBX from t1H:t1L
14903 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14904 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14906 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14907 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14908 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14910 NewMO.setIsKill(false);
14911 MIB.addOperand(NewMO);
14913 MIB.setMemRefs(MMOBegin, MMOEnd);
14915 // Copy EDX:EAX back to t3H:t3L
14916 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14917 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14919 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14921 mainMBB->addSuccessor(origMainMBB);
14922 mainMBB->addSuccessor(sinkMBB);
14925 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14926 TII->get(TargetOpcode::COPY), DstLoReg)
14928 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14929 TII->get(TargetOpcode::COPY), DstHiReg)
14932 MI->eraseFromParent();
14936 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14937 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14938 // in the .td file.
14939 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14940 const TargetInstrInfo *TII) {
14942 switch (MI->getOpcode()) {
14943 default: llvm_unreachable("illegal opcode!");
14944 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
14945 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14946 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
14947 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14948 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
14949 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14950 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
14951 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14954 DebugLoc dl = MI->getDebugLoc();
14955 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14957 unsigned NumArgs = MI->getNumOperands();
14958 for (unsigned i = 1; i < NumArgs; ++i) {
14959 MachineOperand &Op = MI->getOperand(i);
14960 if (!(Op.isReg() && Op.isImplicit()))
14961 MIB.addOperand(Op);
14963 if (MI->hasOneMemOperand())
14964 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14966 BuildMI(*BB, MI, dl,
14967 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14968 .addReg(X86::XMM0);
14970 MI->eraseFromParent();
14974 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14975 // defs in an instruction pattern
14976 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14977 const TargetInstrInfo *TII) {
14979 switch (MI->getOpcode()) {
14980 default: llvm_unreachable("illegal opcode!");
14981 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
14982 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14983 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
14984 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14985 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
14986 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14987 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
14988 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14991 DebugLoc dl = MI->getDebugLoc();
14992 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14994 unsigned NumArgs = MI->getNumOperands(); // remove the results
14995 for (unsigned i = 1; i < NumArgs; ++i) {
14996 MachineOperand &Op = MI->getOperand(i);
14997 if (!(Op.isReg() && Op.isImplicit()))
14998 MIB.addOperand(Op);
15000 if (MI->hasOneMemOperand())
15001 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15003 BuildMI(*BB, MI, dl,
15004 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15007 MI->eraseFromParent();
15011 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15012 const TargetInstrInfo *TII,
15013 const X86Subtarget* Subtarget) {
15014 DebugLoc dl = MI->getDebugLoc();
15016 // Address into RAX/EAX, other two args into ECX, EDX.
15017 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15018 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15019 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15020 for (int i = 0; i < X86::AddrNumOperands; ++i)
15021 MIB.addOperand(MI->getOperand(i));
15023 unsigned ValOps = X86::AddrNumOperands;
15024 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15025 .addReg(MI->getOperand(ValOps).getReg());
15026 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15027 .addReg(MI->getOperand(ValOps+1).getReg());
15029 // The instruction doesn't actually take any operands though.
15030 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15032 MI->eraseFromParent(); // The pseudo is gone now.
15036 MachineBasicBlock *
15037 X86TargetLowering::EmitVAARG64WithCustomInserter(
15039 MachineBasicBlock *MBB) const {
15040 // Emit va_arg instruction on X86-64.
15042 // Operands to this pseudo-instruction:
15043 // 0 ) Output : destination address (reg)
15044 // 1-5) Input : va_list address (addr, i64mem)
15045 // 6 ) ArgSize : Size (in bytes) of vararg type
15046 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15047 // 8 ) Align : Alignment of type
15048 // 9 ) EFLAGS (implicit-def)
15050 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15051 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15053 unsigned DestReg = MI->getOperand(0).getReg();
15054 MachineOperand &Base = MI->getOperand(1);
15055 MachineOperand &Scale = MI->getOperand(2);
15056 MachineOperand &Index = MI->getOperand(3);
15057 MachineOperand &Disp = MI->getOperand(4);
15058 MachineOperand &Segment = MI->getOperand(5);
15059 unsigned ArgSize = MI->getOperand(6).getImm();
15060 unsigned ArgMode = MI->getOperand(7).getImm();
15061 unsigned Align = MI->getOperand(8).getImm();
15063 // Memory Reference
15064 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15065 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15066 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15068 // Machine Information
15069 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15070 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15071 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15072 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15073 DebugLoc DL = MI->getDebugLoc();
15075 // struct va_list {
15078 // i64 overflow_area (address)
15079 // i64 reg_save_area (address)
15081 // sizeof(va_list) = 24
15082 // alignment(va_list) = 8
15084 unsigned TotalNumIntRegs = 6;
15085 unsigned TotalNumXMMRegs = 8;
15086 bool UseGPOffset = (ArgMode == 1);
15087 bool UseFPOffset = (ArgMode == 2);
15088 unsigned MaxOffset = TotalNumIntRegs * 8 +
15089 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15091 /* Align ArgSize to a multiple of 8 */
15092 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15093 bool NeedsAlign = (Align > 8);
15095 MachineBasicBlock *thisMBB = MBB;
15096 MachineBasicBlock *overflowMBB;
15097 MachineBasicBlock *offsetMBB;
15098 MachineBasicBlock *endMBB;
15100 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15101 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15102 unsigned OffsetReg = 0;
15104 if (!UseGPOffset && !UseFPOffset) {
15105 // If we only pull from the overflow region, we don't create a branch.
15106 // We don't need to alter control flow.
15107 OffsetDestReg = 0; // unused
15108 OverflowDestReg = DestReg;
15111 overflowMBB = thisMBB;
15114 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15115 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15116 // If not, pull from overflow_area. (branch to overflowMBB)
15121 // offsetMBB overflowMBB
15126 // Registers for the PHI in endMBB
15127 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15128 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15130 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15131 MachineFunction *MF = MBB->getParent();
15132 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15133 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15134 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15136 MachineFunction::iterator MBBIter = MBB;
15139 // Insert the new basic blocks
15140 MF->insert(MBBIter, offsetMBB);
15141 MF->insert(MBBIter, overflowMBB);
15142 MF->insert(MBBIter, endMBB);
15144 // Transfer the remainder of MBB and its successor edges to endMBB.
15145 endMBB->splice(endMBB->begin(), thisMBB,
15146 llvm::next(MachineBasicBlock::iterator(MI)),
15148 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15150 // Make offsetMBB and overflowMBB successors of thisMBB
15151 thisMBB->addSuccessor(offsetMBB);
15152 thisMBB->addSuccessor(overflowMBB);
15154 // endMBB is a successor of both offsetMBB and overflowMBB
15155 offsetMBB->addSuccessor(endMBB);
15156 overflowMBB->addSuccessor(endMBB);
15158 // Load the offset value into a register
15159 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15160 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15164 .addDisp(Disp, UseFPOffset ? 4 : 0)
15165 .addOperand(Segment)
15166 .setMemRefs(MMOBegin, MMOEnd);
15168 // Check if there is enough room left to pull this argument.
15169 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15171 .addImm(MaxOffset + 8 - ArgSizeA8);
15173 // Branch to "overflowMBB" if offset >= max
15174 // Fall through to "offsetMBB" otherwise
15175 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15176 .addMBB(overflowMBB);
15179 // In offsetMBB, emit code to use the reg_save_area.
15181 assert(OffsetReg != 0);
15183 // Read the reg_save_area address.
15184 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15185 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15190 .addOperand(Segment)
15191 .setMemRefs(MMOBegin, MMOEnd);
15193 // Zero-extend the offset
15194 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15195 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15198 .addImm(X86::sub_32bit);
15200 // Add the offset to the reg_save_area to get the final address.
15201 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15202 .addReg(OffsetReg64)
15203 .addReg(RegSaveReg);
15205 // Compute the offset for the next argument
15206 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15207 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15209 .addImm(UseFPOffset ? 16 : 8);
15211 // Store it back into the va_list.
15212 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15216 .addDisp(Disp, UseFPOffset ? 4 : 0)
15217 .addOperand(Segment)
15218 .addReg(NextOffsetReg)
15219 .setMemRefs(MMOBegin, MMOEnd);
15222 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15227 // Emit code to use overflow area
15230 // Load the overflow_area address into a register.
15231 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15232 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15237 .addOperand(Segment)
15238 .setMemRefs(MMOBegin, MMOEnd);
15240 // If we need to align it, do so. Otherwise, just copy the address
15241 // to OverflowDestReg.
15243 // Align the overflow address
15244 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15245 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15247 // aligned_addr = (addr + (align-1)) & ~(align-1)
15248 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15249 .addReg(OverflowAddrReg)
15252 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15254 .addImm(~(uint64_t)(Align-1));
15256 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15257 .addReg(OverflowAddrReg);
15260 // Compute the next overflow address after this argument.
15261 // (the overflow address should be kept 8-byte aligned)
15262 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15263 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15264 .addReg(OverflowDestReg)
15265 .addImm(ArgSizeA8);
15267 // Store the new overflow address.
15268 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15273 .addOperand(Segment)
15274 .addReg(NextAddrReg)
15275 .setMemRefs(MMOBegin, MMOEnd);
15277 // If we branched, emit the PHI to the front of endMBB.
15279 BuildMI(*endMBB, endMBB->begin(), DL,
15280 TII->get(X86::PHI), DestReg)
15281 .addReg(OffsetDestReg).addMBB(offsetMBB)
15282 .addReg(OverflowDestReg).addMBB(overflowMBB);
15285 // Erase the pseudo instruction
15286 MI->eraseFromParent();
15291 MachineBasicBlock *
15292 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15294 MachineBasicBlock *MBB) const {
15295 // Emit code to save XMM registers to the stack. The ABI says that the
15296 // number of registers to save is given in %al, so it's theoretically
15297 // possible to do an indirect jump trick to avoid saving all of them,
15298 // however this code takes a simpler approach and just executes all
15299 // of the stores if %al is non-zero. It's less code, and it's probably
15300 // easier on the hardware branch predictor, and stores aren't all that
15301 // expensive anyway.
15303 // Create the new basic blocks. One block contains all the XMM stores,
15304 // and one block is the final destination regardless of whether any
15305 // stores were performed.
15306 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15307 MachineFunction *F = MBB->getParent();
15308 MachineFunction::iterator MBBIter = MBB;
15310 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15311 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15312 F->insert(MBBIter, XMMSaveMBB);
15313 F->insert(MBBIter, EndMBB);
15315 // Transfer the remainder of MBB and its successor edges to EndMBB.
15316 EndMBB->splice(EndMBB->begin(), MBB,
15317 llvm::next(MachineBasicBlock::iterator(MI)),
15319 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15321 // The original block will now fall through to the XMM save block.
15322 MBB->addSuccessor(XMMSaveMBB);
15323 // The XMMSaveMBB will fall through to the end block.
15324 XMMSaveMBB->addSuccessor(EndMBB);
15326 // Now add the instructions.
15327 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15328 DebugLoc DL = MI->getDebugLoc();
15330 unsigned CountReg = MI->getOperand(0).getReg();
15331 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15332 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15334 if (!Subtarget->isTargetWin64()) {
15335 // If %al is 0, branch around the XMM save block.
15336 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15337 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15338 MBB->addSuccessor(EndMBB);
15341 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15342 // In the XMM save block, save all the XMM argument registers.
15343 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
15344 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15345 MachineMemOperand *MMO =
15346 F->getMachineMemOperand(
15347 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15348 MachineMemOperand::MOStore,
15349 /*Size=*/16, /*Align=*/16);
15350 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15351 .addFrameIndex(RegSaveFrameIndex)
15352 .addImm(/*Scale=*/1)
15353 .addReg(/*IndexReg=*/0)
15354 .addImm(/*Disp=*/Offset)
15355 .addReg(/*Segment=*/0)
15356 .addReg(MI->getOperand(i).getReg())
15357 .addMemOperand(MMO);
15360 MI->eraseFromParent(); // The pseudo instruction is gone now.
15365 // The EFLAGS operand of SelectItr might be missing a kill marker
15366 // because there were multiple uses of EFLAGS, and ISel didn't know
15367 // which to mark. Figure out whether SelectItr should have had a
15368 // kill marker, and set it if it should. Returns the correct kill
15370 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15371 MachineBasicBlock* BB,
15372 const TargetRegisterInfo* TRI) {
15373 // Scan forward through BB for a use/def of EFLAGS.
15374 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15375 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15376 const MachineInstr& mi = *miI;
15377 if (mi.readsRegister(X86::EFLAGS))
15379 if (mi.definesRegister(X86::EFLAGS))
15380 break; // Should have kill-flag - update below.
15383 // If we hit the end of the block, check whether EFLAGS is live into a
15385 if (miI == BB->end()) {
15386 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15387 sEnd = BB->succ_end();
15388 sItr != sEnd; ++sItr) {
15389 MachineBasicBlock* succ = *sItr;
15390 if (succ->isLiveIn(X86::EFLAGS))
15395 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15396 // out. SelectMI should have a kill flag on EFLAGS.
15397 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15401 MachineBasicBlock *
15402 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15403 MachineBasicBlock *BB) const {
15404 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15405 DebugLoc DL = MI->getDebugLoc();
15407 // To "insert" a SELECT_CC instruction, we actually have to insert the
15408 // diamond control-flow pattern. The incoming instruction knows the
15409 // destination vreg to set, the condition code register to branch on, the
15410 // true/false values to select between, and a branch opcode to use.
15411 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15412 MachineFunction::iterator It = BB;
15418 // cmpTY ccX, r1, r2
15420 // fallthrough --> copy0MBB
15421 MachineBasicBlock *thisMBB = BB;
15422 MachineFunction *F = BB->getParent();
15423 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15424 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15425 F->insert(It, copy0MBB);
15426 F->insert(It, sinkMBB);
15428 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15429 // live into the sink and copy blocks.
15430 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15431 if (!MI->killsRegister(X86::EFLAGS) &&
15432 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15433 copy0MBB->addLiveIn(X86::EFLAGS);
15434 sinkMBB->addLiveIn(X86::EFLAGS);
15437 // Transfer the remainder of BB and its successor edges to sinkMBB.
15438 sinkMBB->splice(sinkMBB->begin(), BB,
15439 llvm::next(MachineBasicBlock::iterator(MI)),
15441 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15443 // Add the true and fallthrough blocks as its successors.
15444 BB->addSuccessor(copy0MBB);
15445 BB->addSuccessor(sinkMBB);
15447 // Create the conditional branch instruction.
15449 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15450 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15453 // %FalseValue = ...
15454 // # fallthrough to sinkMBB
15455 copy0MBB->addSuccessor(sinkMBB);
15458 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15460 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15461 TII->get(X86::PHI), MI->getOperand(0).getReg())
15462 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15463 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15465 MI->eraseFromParent(); // The pseudo instruction is gone now.
15469 MachineBasicBlock *
15470 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15471 bool Is64Bit) const {
15472 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15473 DebugLoc DL = MI->getDebugLoc();
15474 MachineFunction *MF = BB->getParent();
15475 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15477 assert(getTargetMachine().Options.EnableSegmentedStacks);
15479 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15480 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15483 // ... [Till the alloca]
15484 // If stacklet is not large enough, jump to mallocMBB
15487 // Allocate by subtracting from RSP
15488 // Jump to continueMBB
15491 // Allocate by call to runtime
15495 // [rest of original BB]
15498 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15499 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15500 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15502 MachineRegisterInfo &MRI = MF->getRegInfo();
15503 const TargetRegisterClass *AddrRegClass =
15504 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15506 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15507 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15508 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15509 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15510 sizeVReg = MI->getOperand(1).getReg(),
15511 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15513 MachineFunction::iterator MBBIter = BB;
15516 MF->insert(MBBIter, bumpMBB);
15517 MF->insert(MBBIter, mallocMBB);
15518 MF->insert(MBBIter, continueMBB);
15520 continueMBB->splice(continueMBB->begin(), BB, llvm::next
15521 (MachineBasicBlock::iterator(MI)), BB->end());
15522 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15524 // Add code to the main basic block to check if the stack limit has been hit,
15525 // and if so, jump to mallocMBB otherwise to bumpMBB.
15526 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15527 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15528 .addReg(tmpSPVReg).addReg(sizeVReg);
15529 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15530 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15531 .addReg(SPLimitVReg);
15532 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15534 // bumpMBB simply decreases the stack pointer, since we know the current
15535 // stacklet has enough space.
15536 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15537 .addReg(SPLimitVReg);
15538 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15539 .addReg(SPLimitVReg);
15540 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15542 // Calls into a routine in libgcc to allocate more space from the heap.
15543 const uint32_t *RegMask =
15544 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15546 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15548 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15549 .addExternalSymbol("__morestack_allocate_stack_space")
15550 .addRegMask(RegMask)
15551 .addReg(X86::RDI, RegState::Implicit)
15552 .addReg(X86::RAX, RegState::ImplicitDefine);
15554 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15556 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15557 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15558 .addExternalSymbol("__morestack_allocate_stack_space")
15559 .addRegMask(RegMask)
15560 .addReg(X86::EAX, RegState::ImplicitDefine);
15564 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15567 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15568 .addReg(Is64Bit ? X86::RAX : X86::EAX);
15569 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15571 // Set up the CFG correctly.
15572 BB->addSuccessor(bumpMBB);
15573 BB->addSuccessor(mallocMBB);
15574 mallocMBB->addSuccessor(continueMBB);
15575 bumpMBB->addSuccessor(continueMBB);
15577 // Take care of the PHI nodes.
15578 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15579 MI->getOperand(0).getReg())
15580 .addReg(mallocPtrVReg).addMBB(mallocMBB)
15581 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15583 // Delete the original pseudo instruction.
15584 MI->eraseFromParent();
15587 return continueMBB;
15590 MachineBasicBlock *
15591 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15592 MachineBasicBlock *BB) const {
15593 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15594 DebugLoc DL = MI->getDebugLoc();
15596 assert(!Subtarget->isTargetMacho());
15598 // The lowering is pretty easy: we're just emitting the call to _alloca. The
15599 // non-trivial part is impdef of ESP.
15601 if (Subtarget->isTargetWin64()) {
15602 if (Subtarget->isTargetCygMing()) {
15603 // ___chkstk(Mingw64):
15604 // Clobbers R10, R11, RAX and EFLAGS.
15606 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15607 .addExternalSymbol("___chkstk")
15608 .addReg(X86::RAX, RegState::Implicit)
15609 .addReg(X86::RSP, RegState::Implicit)
15610 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15611 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15612 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15614 // __chkstk(MSVCRT): does not update stack pointer.
15615 // Clobbers R10, R11 and EFLAGS.
15616 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15617 .addExternalSymbol("__chkstk")
15618 .addReg(X86::RAX, RegState::Implicit)
15619 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15620 // RAX has the offset to be subtracted from RSP.
15621 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15626 const char *StackProbeSymbol =
15627 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15629 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15630 .addExternalSymbol(StackProbeSymbol)
15631 .addReg(X86::EAX, RegState::Implicit)
15632 .addReg(X86::ESP, RegState::Implicit)
15633 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15634 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15635 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15638 MI->eraseFromParent(); // The pseudo instruction is gone now.
15642 MachineBasicBlock *
15643 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15644 MachineBasicBlock *BB) const {
15645 // This is pretty easy. We're taking the value that we received from
15646 // our load from the relocation, sticking it in either RDI (x86-64)
15647 // or EAX and doing an indirect call. The return value will then
15648 // be in the normal return register.
15649 const X86InstrInfo *TII
15650 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15651 DebugLoc DL = MI->getDebugLoc();
15652 MachineFunction *F = BB->getParent();
15654 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15655 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15657 // Get a register mask for the lowered call.
15658 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15659 // proper register mask.
15660 const uint32_t *RegMask =
15661 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15662 if (Subtarget->is64Bit()) {
15663 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15664 TII->get(X86::MOV64rm), X86::RDI)
15666 .addImm(0).addReg(0)
15667 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15668 MI->getOperand(3).getTargetFlags())
15670 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15671 addDirectMem(MIB, X86::RDI);
15672 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15673 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15674 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15675 TII->get(X86::MOV32rm), X86::EAX)
15677 .addImm(0).addReg(0)
15678 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15679 MI->getOperand(3).getTargetFlags())
15681 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15682 addDirectMem(MIB, X86::EAX);
15683 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15685 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15686 TII->get(X86::MOV32rm), X86::EAX)
15687 .addReg(TII->getGlobalBaseReg(F))
15688 .addImm(0).addReg(0)
15689 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15690 MI->getOperand(3).getTargetFlags())
15692 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15693 addDirectMem(MIB, X86::EAX);
15694 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15697 MI->eraseFromParent(); // The pseudo instruction is gone now.
15701 MachineBasicBlock *
15702 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15703 MachineBasicBlock *MBB) const {
15704 DebugLoc DL = MI->getDebugLoc();
15705 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15707 MachineFunction *MF = MBB->getParent();
15708 MachineRegisterInfo &MRI = MF->getRegInfo();
15710 const BasicBlock *BB = MBB->getBasicBlock();
15711 MachineFunction::iterator I = MBB;
15714 // Memory Reference
15715 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15716 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15719 unsigned MemOpndSlot = 0;
15721 unsigned CurOp = 0;
15723 DstReg = MI->getOperand(CurOp++).getReg();
15724 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15725 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15726 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15727 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15729 MemOpndSlot = CurOp;
15731 MVT PVT = getPointerTy();
15732 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15733 "Invalid Pointer Size!");
15735 // For v = setjmp(buf), we generate
15738 // buf[LabelOffset] = restoreMBB
15739 // SjLjSetup restoreMBB
15745 // v = phi(main, restore)
15750 MachineBasicBlock *thisMBB = MBB;
15751 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15752 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15753 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15754 MF->insert(I, mainMBB);
15755 MF->insert(I, sinkMBB);
15756 MF->push_back(restoreMBB);
15758 MachineInstrBuilder MIB;
15760 // Transfer the remainder of BB and its successor edges to sinkMBB.
15761 sinkMBB->splice(sinkMBB->begin(), MBB,
15762 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15763 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15766 unsigned PtrStoreOpc = 0;
15767 unsigned LabelReg = 0;
15768 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15769 Reloc::Model RM = getTargetMachine().getRelocationModel();
15770 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15771 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15773 // Prepare IP either in reg or imm.
15774 if (!UseImmLabel) {
15775 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15776 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15777 LabelReg = MRI.createVirtualRegister(PtrRC);
15778 if (Subtarget->is64Bit()) {
15779 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15783 .addMBB(restoreMBB)
15786 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15787 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15788 .addReg(XII->getGlobalBaseReg(MF))
15791 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15795 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15797 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15798 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15799 if (i == X86::AddrDisp)
15800 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15802 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15805 MIB.addReg(LabelReg);
15807 MIB.addMBB(restoreMBB);
15808 MIB.setMemRefs(MMOBegin, MMOEnd);
15810 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15811 .addMBB(restoreMBB);
15813 const X86RegisterInfo *RegInfo =
15814 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15815 MIB.addRegMask(RegInfo->getNoPreservedMask());
15816 thisMBB->addSuccessor(mainMBB);
15817 thisMBB->addSuccessor(restoreMBB);
15821 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15822 mainMBB->addSuccessor(sinkMBB);
15825 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15826 TII->get(X86::PHI), DstReg)
15827 .addReg(mainDstReg).addMBB(mainMBB)
15828 .addReg(restoreDstReg).addMBB(restoreMBB);
15831 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15832 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15833 restoreMBB->addSuccessor(sinkMBB);
15835 MI->eraseFromParent();
15839 MachineBasicBlock *
15840 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15841 MachineBasicBlock *MBB) const {
15842 DebugLoc DL = MI->getDebugLoc();
15843 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15845 MachineFunction *MF = MBB->getParent();
15846 MachineRegisterInfo &MRI = MF->getRegInfo();
15848 // Memory Reference
15849 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15850 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15852 MVT PVT = getPointerTy();
15853 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15854 "Invalid Pointer Size!");
15856 const TargetRegisterClass *RC =
15857 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15858 unsigned Tmp = MRI.createVirtualRegister(RC);
15859 // Since FP is only updated here but NOT referenced, it's treated as GPR.
15860 const X86RegisterInfo *RegInfo =
15861 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15862 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15863 unsigned SP = RegInfo->getStackRegister();
15865 MachineInstrBuilder MIB;
15867 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15868 const int64_t SPOffset = 2 * PVT.getStoreSize();
15870 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15871 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15874 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15875 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15876 MIB.addOperand(MI->getOperand(i));
15877 MIB.setMemRefs(MMOBegin, MMOEnd);
15879 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15880 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15881 if (i == X86::AddrDisp)
15882 MIB.addDisp(MI->getOperand(i), LabelOffset);
15884 MIB.addOperand(MI->getOperand(i));
15886 MIB.setMemRefs(MMOBegin, MMOEnd);
15888 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15889 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15890 if (i == X86::AddrDisp)
15891 MIB.addDisp(MI->getOperand(i), SPOffset);
15893 MIB.addOperand(MI->getOperand(i));
15895 MIB.setMemRefs(MMOBegin, MMOEnd);
15897 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15899 MI->eraseFromParent();
15903 MachineBasicBlock *
15904 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15905 MachineBasicBlock *BB) const {
15906 switch (MI->getOpcode()) {
15907 default: llvm_unreachable("Unexpected instr type to insert");
15908 case X86::TAILJMPd64:
15909 case X86::TAILJMPr64:
15910 case X86::TAILJMPm64:
15911 llvm_unreachable("TAILJMP64 would not be touched here.");
15912 case X86::TCRETURNdi64:
15913 case X86::TCRETURNri64:
15914 case X86::TCRETURNmi64:
15916 case X86::WIN_ALLOCA:
15917 return EmitLoweredWinAlloca(MI, BB);
15918 case X86::SEG_ALLOCA_32:
15919 return EmitLoweredSegAlloca(MI, BB, false);
15920 case X86::SEG_ALLOCA_64:
15921 return EmitLoweredSegAlloca(MI, BB, true);
15922 case X86::TLSCall_32:
15923 case X86::TLSCall_64:
15924 return EmitLoweredTLSCall(MI, BB);
15925 case X86::CMOV_GR8:
15926 case X86::CMOV_FR32:
15927 case X86::CMOV_FR64:
15928 case X86::CMOV_V4F32:
15929 case X86::CMOV_V2F64:
15930 case X86::CMOV_V2I64:
15931 case X86::CMOV_V8F32:
15932 case X86::CMOV_V4F64:
15933 case X86::CMOV_V4I64:
15934 case X86::CMOV_V16F32:
15935 case X86::CMOV_V8F64:
15936 case X86::CMOV_V8I64:
15937 case X86::CMOV_GR16:
15938 case X86::CMOV_GR32:
15939 case X86::CMOV_RFP32:
15940 case X86::CMOV_RFP64:
15941 case X86::CMOV_RFP80:
15942 return EmitLoweredSelect(MI, BB);
15944 case X86::FP32_TO_INT16_IN_MEM:
15945 case X86::FP32_TO_INT32_IN_MEM:
15946 case X86::FP32_TO_INT64_IN_MEM:
15947 case X86::FP64_TO_INT16_IN_MEM:
15948 case X86::FP64_TO_INT32_IN_MEM:
15949 case X86::FP64_TO_INT64_IN_MEM:
15950 case X86::FP80_TO_INT16_IN_MEM:
15951 case X86::FP80_TO_INT32_IN_MEM:
15952 case X86::FP80_TO_INT64_IN_MEM: {
15953 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15954 DebugLoc DL = MI->getDebugLoc();
15956 // Change the floating point control register to use "round towards zero"
15957 // mode when truncating to an integer value.
15958 MachineFunction *F = BB->getParent();
15959 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15960 addFrameReference(BuildMI(*BB, MI, DL,
15961 TII->get(X86::FNSTCW16m)), CWFrameIdx);
15963 // Load the old value of the high byte of the control word...
15965 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15966 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15969 // Set the high part to be round to zero...
15970 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15973 // Reload the modified control word now...
15974 addFrameReference(BuildMI(*BB, MI, DL,
15975 TII->get(X86::FLDCW16m)), CWFrameIdx);
15977 // Restore the memory image of control word to original value
15978 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15981 // Get the X86 opcode to use.
15983 switch (MI->getOpcode()) {
15984 default: llvm_unreachable("illegal opcode!");
15985 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15986 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15987 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15988 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15989 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15990 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15991 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15992 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15993 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15997 MachineOperand &Op = MI->getOperand(0);
15999 AM.BaseType = X86AddressMode::RegBase;
16000 AM.Base.Reg = Op.getReg();
16002 AM.BaseType = X86AddressMode::FrameIndexBase;
16003 AM.Base.FrameIndex = Op.getIndex();
16005 Op = MI->getOperand(1);
16007 AM.Scale = Op.getImm();
16008 Op = MI->getOperand(2);
16010 AM.IndexReg = Op.getImm();
16011 Op = MI->getOperand(3);
16012 if (Op.isGlobal()) {
16013 AM.GV = Op.getGlobal();
16015 AM.Disp = Op.getImm();
16017 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16018 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16020 // Reload the original control word now.
16021 addFrameReference(BuildMI(*BB, MI, DL,
16022 TII->get(X86::FLDCW16m)), CWFrameIdx);
16024 MI->eraseFromParent(); // The pseudo instruction is gone now.
16027 // String/text processing lowering.
16028 case X86::PCMPISTRM128REG:
16029 case X86::VPCMPISTRM128REG:
16030 case X86::PCMPISTRM128MEM:
16031 case X86::VPCMPISTRM128MEM:
16032 case X86::PCMPESTRM128REG:
16033 case X86::VPCMPESTRM128REG:
16034 case X86::PCMPESTRM128MEM:
16035 case X86::VPCMPESTRM128MEM:
16036 assert(Subtarget->hasSSE42() &&
16037 "Target must have SSE4.2 or AVX features enabled");
16038 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16040 // String/text processing lowering.
16041 case X86::PCMPISTRIREG:
16042 case X86::VPCMPISTRIREG:
16043 case X86::PCMPISTRIMEM:
16044 case X86::VPCMPISTRIMEM:
16045 case X86::PCMPESTRIREG:
16046 case X86::VPCMPESTRIREG:
16047 case X86::PCMPESTRIMEM:
16048 case X86::VPCMPESTRIMEM:
16049 assert(Subtarget->hasSSE42() &&
16050 "Target must have SSE4.2 or AVX features enabled");
16051 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16053 // Thread synchronization.
16055 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16059 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16061 // Atomic Lowering.
16062 case X86::ATOMAND8:
16063 case X86::ATOMAND16:
16064 case X86::ATOMAND32:
16065 case X86::ATOMAND64:
16068 case X86::ATOMOR16:
16069 case X86::ATOMOR32:
16070 case X86::ATOMOR64:
16072 case X86::ATOMXOR16:
16073 case X86::ATOMXOR8:
16074 case X86::ATOMXOR32:
16075 case X86::ATOMXOR64:
16077 case X86::ATOMNAND8:
16078 case X86::ATOMNAND16:
16079 case X86::ATOMNAND32:
16080 case X86::ATOMNAND64:
16082 case X86::ATOMMAX8:
16083 case X86::ATOMMAX16:
16084 case X86::ATOMMAX32:
16085 case X86::ATOMMAX64:
16087 case X86::ATOMMIN8:
16088 case X86::ATOMMIN16:
16089 case X86::ATOMMIN32:
16090 case X86::ATOMMIN64:
16092 case X86::ATOMUMAX8:
16093 case X86::ATOMUMAX16:
16094 case X86::ATOMUMAX32:
16095 case X86::ATOMUMAX64:
16097 case X86::ATOMUMIN8:
16098 case X86::ATOMUMIN16:
16099 case X86::ATOMUMIN32:
16100 case X86::ATOMUMIN64:
16101 return EmitAtomicLoadArith(MI, BB);
16103 // This group does 64-bit operations on a 32-bit host.
16104 case X86::ATOMAND6432:
16105 case X86::ATOMOR6432:
16106 case X86::ATOMXOR6432:
16107 case X86::ATOMNAND6432:
16108 case X86::ATOMADD6432:
16109 case X86::ATOMSUB6432:
16110 case X86::ATOMMAX6432:
16111 case X86::ATOMMIN6432:
16112 case X86::ATOMUMAX6432:
16113 case X86::ATOMUMIN6432:
16114 case X86::ATOMSWAP6432:
16115 return EmitAtomicLoadArith6432(MI, BB);
16117 case X86::VASTART_SAVE_XMM_REGS:
16118 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16120 case X86::VAARG_64:
16121 return EmitVAARG64WithCustomInserter(MI, BB);
16123 case X86::EH_SjLj_SetJmp32:
16124 case X86::EH_SjLj_SetJmp64:
16125 return emitEHSjLjSetJmp(MI, BB);
16127 case X86::EH_SjLj_LongJmp32:
16128 case X86::EH_SjLj_LongJmp64:
16129 return emitEHSjLjLongJmp(MI, BB);
16131 case TargetOpcode::STACKMAP:
16132 case TargetOpcode::PATCHPOINT:
16133 return emitPatchPoint(MI, BB);
16137 //===----------------------------------------------------------------------===//
16138 // X86 Optimization Hooks
16139 //===----------------------------------------------------------------------===//
16141 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16144 const SelectionDAG &DAG,
16145 unsigned Depth) const {
16146 unsigned BitWidth = KnownZero.getBitWidth();
16147 unsigned Opc = Op.getOpcode();
16148 assert((Opc >= ISD::BUILTIN_OP_END ||
16149 Opc == ISD::INTRINSIC_WO_CHAIN ||
16150 Opc == ISD::INTRINSIC_W_CHAIN ||
16151 Opc == ISD::INTRINSIC_VOID) &&
16152 "Should use MaskedValueIsZero if you don't know whether Op"
16153 " is a target node!");
16155 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16169 // These nodes' second result is a boolean.
16170 if (Op.getResNo() == 0)
16173 case X86ISD::SETCC:
16174 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16176 case ISD::INTRINSIC_WO_CHAIN: {
16177 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16178 unsigned NumLoBits = 0;
16181 case Intrinsic::x86_sse_movmsk_ps:
16182 case Intrinsic::x86_avx_movmsk_ps_256:
16183 case Intrinsic::x86_sse2_movmsk_pd:
16184 case Intrinsic::x86_avx_movmsk_pd_256:
16185 case Intrinsic::x86_mmx_pmovmskb:
16186 case Intrinsic::x86_sse2_pmovmskb_128:
16187 case Intrinsic::x86_avx2_pmovmskb: {
16188 // High bits of movmskp{s|d}, pmovmskb are known zero.
16190 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16191 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16192 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16193 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16194 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16195 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16196 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16197 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16199 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16208 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16209 unsigned Depth) const {
16210 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16211 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16212 return Op.getValueType().getScalarType().getSizeInBits();
16218 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16219 /// node is a GlobalAddress + offset.
16220 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16221 const GlobalValue* &GA,
16222 int64_t &Offset) const {
16223 if (N->getOpcode() == X86ISD::Wrapper) {
16224 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16225 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16226 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16230 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16233 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16234 /// same as extracting the high 128-bit part of 256-bit vector and then
16235 /// inserting the result into the low part of a new 256-bit vector
16236 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16237 EVT VT = SVOp->getValueType(0);
16238 unsigned NumElems = VT.getVectorNumElements();
16240 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16241 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16242 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16243 SVOp->getMaskElt(j) >= 0)
16249 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16250 /// same as extracting the low 128-bit part of 256-bit vector and then
16251 /// inserting the result into the high part of a new 256-bit vector
16252 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16253 EVT VT = SVOp->getValueType(0);
16254 unsigned NumElems = VT.getVectorNumElements();
16256 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16257 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16258 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16259 SVOp->getMaskElt(j) >= 0)
16265 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16266 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16267 TargetLowering::DAGCombinerInfo &DCI,
16268 const X86Subtarget* Subtarget) {
16270 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16271 SDValue V1 = SVOp->getOperand(0);
16272 SDValue V2 = SVOp->getOperand(1);
16273 EVT VT = SVOp->getValueType(0);
16274 unsigned NumElems = VT.getVectorNumElements();
16276 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16277 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16281 // V UNDEF BUILD_VECTOR UNDEF
16283 // CONCAT_VECTOR CONCAT_VECTOR
16286 // RESULT: V + zero extended
16288 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16289 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16290 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16293 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16296 // To match the shuffle mask, the first half of the mask should
16297 // be exactly the first vector, and all the rest a splat with the
16298 // first element of the second one.
16299 for (unsigned i = 0; i != NumElems/2; ++i)
16300 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16301 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16304 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16305 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16306 if (Ld->hasNUsesOfValue(1, 0)) {
16307 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16308 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16310 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16311 array_lengthof(Ops),
16313 Ld->getPointerInfo(),
16314 Ld->getAlignment(),
16315 false/*isVolatile*/, true/*ReadMem*/,
16316 false/*WriteMem*/);
16318 // Make sure the newly-created LOAD is in the same position as Ld in
16319 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16320 // and update uses of Ld's output chain to use the TokenFactor.
16321 if (Ld->hasAnyUseOfValue(1)) {
16322 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16323 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16324 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16325 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16326 SDValue(ResNode.getNode(), 1));
16329 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16333 // Emit a zeroed vector and insert the desired subvector on its
16335 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16336 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16337 return DCI.CombineTo(N, InsV);
16340 //===--------------------------------------------------------------------===//
16341 // Combine some shuffles into subvector extracts and inserts:
16344 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16345 if (isShuffleHigh128VectorInsertLow(SVOp)) {
16346 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16347 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16348 return DCI.CombineTo(N, InsV);
16351 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16352 if (isShuffleLow128VectorInsertHigh(SVOp)) {
16353 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16354 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16355 return DCI.CombineTo(N, InsV);
16361 /// PerformShuffleCombine - Performs several different shuffle combines.
16362 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16363 TargetLowering::DAGCombinerInfo &DCI,
16364 const X86Subtarget *Subtarget) {
16366 EVT VT = N->getValueType(0);
16368 // Don't create instructions with illegal types after legalize types has run.
16369 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16370 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16373 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16374 if (Subtarget->hasFp256() && VT.is256BitVector() &&
16375 N->getOpcode() == ISD::VECTOR_SHUFFLE)
16376 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16378 // Only handle 128 wide vector from here on.
16379 if (!VT.is128BitVector())
16382 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16383 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16384 // consecutive, non-overlapping, and in the right order.
16385 SmallVector<SDValue, 16> Elts;
16386 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16387 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16389 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16392 /// PerformTruncateCombine - Converts truncate operation to
16393 /// a sequence of vector shuffle operations.
16394 /// It is possible when we truncate 256-bit vector to 128-bit vector
16395 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16396 TargetLowering::DAGCombinerInfo &DCI,
16397 const X86Subtarget *Subtarget) {
16401 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16402 /// specific shuffle of a load can be folded into a single element load.
16403 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16404 /// shuffles have been customed lowered so we need to handle those here.
16405 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16406 TargetLowering::DAGCombinerInfo &DCI) {
16407 if (DCI.isBeforeLegalizeOps())
16410 SDValue InVec = N->getOperand(0);
16411 SDValue EltNo = N->getOperand(1);
16413 if (!isa<ConstantSDNode>(EltNo))
16416 EVT VT = InVec.getValueType();
16418 bool HasShuffleIntoBitcast = false;
16419 if (InVec.getOpcode() == ISD::BITCAST) {
16420 // Don't duplicate a load with other uses.
16421 if (!InVec.hasOneUse())
16423 EVT BCVT = InVec.getOperand(0).getValueType();
16424 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16426 InVec = InVec.getOperand(0);
16427 HasShuffleIntoBitcast = true;
16430 if (!isTargetShuffle(InVec.getOpcode()))
16433 // Don't duplicate a load with other uses.
16434 if (!InVec.hasOneUse())
16437 SmallVector<int, 16> ShuffleMask;
16439 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16443 // Select the input vector, guarding against out of range extract vector.
16444 unsigned NumElems = VT.getVectorNumElements();
16445 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16446 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16447 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16448 : InVec.getOperand(1);
16450 // If inputs to shuffle are the same for both ops, then allow 2 uses
16451 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16453 if (LdNode.getOpcode() == ISD::BITCAST) {
16454 // Don't duplicate a load with other uses.
16455 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16458 AllowedUses = 1; // only allow 1 load use if we have a bitcast
16459 LdNode = LdNode.getOperand(0);
16462 if (!ISD::isNormalLoad(LdNode.getNode()))
16465 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16467 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16470 if (HasShuffleIntoBitcast) {
16471 // If there's a bitcast before the shuffle, check if the load type and
16472 // alignment is valid.
16473 unsigned Align = LN0->getAlignment();
16474 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16475 unsigned NewAlign = TLI.getDataLayout()->
16476 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16478 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16482 // All checks match so transform back to vector_shuffle so that DAG combiner
16483 // can finish the job
16486 // Create shuffle node taking into account the case that its a unary shuffle
16487 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16488 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16489 InVec.getOperand(0), Shuffle,
16491 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16492 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16496 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16497 /// generation and convert it from being a bunch of shuffles and extracts
16498 /// to a simple store and scalar loads to extract the elements.
16499 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16500 TargetLowering::DAGCombinerInfo &DCI) {
16501 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16502 if (NewOp.getNode())
16505 SDValue InputVector = N->getOperand(0);
16507 // Detect whether we are trying to convert from mmx to i32 and the bitcast
16508 // from mmx to v2i32 has a single usage.
16509 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16510 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16511 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16512 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16513 N->getValueType(0),
16514 InputVector.getNode()->getOperand(0));
16516 // Only operate on vectors of 4 elements, where the alternative shuffling
16517 // gets to be more expensive.
16518 if (InputVector.getValueType() != MVT::v4i32)
16521 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16522 // single use which is a sign-extend or zero-extend, and all elements are
16524 SmallVector<SDNode *, 4> Uses;
16525 unsigned ExtractedElements = 0;
16526 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16527 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16528 if (UI.getUse().getResNo() != InputVector.getResNo())
16531 SDNode *Extract = *UI;
16532 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16535 if (Extract->getValueType(0) != MVT::i32)
16537 if (!Extract->hasOneUse())
16539 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16540 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16542 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16545 // Record which element was extracted.
16546 ExtractedElements |=
16547 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16549 Uses.push_back(Extract);
16552 // If not all the elements were used, this may not be worthwhile.
16553 if (ExtractedElements != 15)
16556 // Ok, we've now decided to do the transformation.
16557 SDLoc dl(InputVector);
16559 // Store the value to a temporary stack slot.
16560 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16561 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16562 MachinePointerInfo(), false, false, 0);
16564 // Replace each use (extract) with a load of the appropriate element.
16565 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16566 UE = Uses.end(); UI != UE; ++UI) {
16567 SDNode *Extract = *UI;
16569 // cOMpute the element's address.
16570 SDValue Idx = Extract->getOperand(1);
16572 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16573 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16574 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16575 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16577 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16578 StackPtr, OffsetVal);
16580 // Load the scalar.
16581 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16582 ScalarAddr, MachinePointerInfo(),
16583 false, false, false, 0);
16585 // Replace the exact with the load.
16586 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16589 // The replacement was made in place; don't return anything.
16593 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16594 static std::pair<unsigned, bool>
16595 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16596 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16597 if (!VT.isVector())
16598 return std::make_pair(0, false);
16600 bool NeedSplit = false;
16601 switch (VT.getSimpleVT().SimpleTy) {
16602 default: return std::make_pair(0, false);
16606 if (!Subtarget->hasAVX2())
16608 if (!Subtarget->hasAVX())
16609 return std::make_pair(0, false);
16614 if (!Subtarget->hasSSE2())
16615 return std::make_pair(0, false);
16618 // SSE2 has only a small subset of the operations.
16619 bool hasUnsigned = Subtarget->hasSSE41() ||
16620 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16621 bool hasSigned = Subtarget->hasSSE41() ||
16622 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16624 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16627 // Check for x CC y ? x : y.
16628 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16629 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16634 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16637 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16640 Opc = hasSigned ? X86ISD::SMIN : 0; break;
16643 Opc = hasSigned ? X86ISD::SMAX : 0; break;
16645 // Check for x CC y ? y : x -- a min/max with reversed arms.
16646 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16647 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16652 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16655 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16658 Opc = hasSigned ? X86ISD::SMAX : 0; break;
16661 Opc = hasSigned ? X86ISD::SMIN : 0; break;
16665 return std::make_pair(Opc, NeedSplit);
16668 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16670 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16671 TargetLowering::DAGCombinerInfo &DCI,
16672 const X86Subtarget *Subtarget) {
16674 SDValue Cond = N->getOperand(0);
16675 // Get the LHS/RHS of the select.
16676 SDValue LHS = N->getOperand(1);
16677 SDValue RHS = N->getOperand(2);
16678 EVT VT = LHS.getValueType();
16679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16681 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16682 // instructions match the semantics of the common C idiom x<y?x:y but not
16683 // x<=y?x:y, because of how they handle negative zero (which can be
16684 // ignored in unsafe-math mode).
16685 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16686 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16687 (Subtarget->hasSSE2() ||
16688 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16689 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16691 unsigned Opcode = 0;
16692 // Check for x CC y ? x : y.
16693 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16694 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16698 // Converting this to a min would handle NaNs incorrectly, and swapping
16699 // the operands would cause it to handle comparisons between positive
16700 // and negative zero incorrectly.
16701 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16702 if (!DAG.getTarget().Options.UnsafeFPMath &&
16703 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16705 std::swap(LHS, RHS);
16707 Opcode = X86ISD::FMIN;
16710 // Converting this to a min would handle comparisons between positive
16711 // and negative zero incorrectly.
16712 if (!DAG.getTarget().Options.UnsafeFPMath &&
16713 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16715 Opcode = X86ISD::FMIN;
16718 // Converting this to a min would handle both negative zeros and NaNs
16719 // incorrectly, but we can swap the operands to fix both.
16720 std::swap(LHS, RHS);
16724 Opcode = X86ISD::FMIN;
16728 // Converting this to a max would handle comparisons between positive
16729 // and negative zero incorrectly.
16730 if (!DAG.getTarget().Options.UnsafeFPMath &&
16731 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16733 Opcode = X86ISD::FMAX;
16736 // Converting this to a max would handle NaNs incorrectly, and swapping
16737 // the operands would cause it to handle comparisons between positive
16738 // and negative zero incorrectly.
16739 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16740 if (!DAG.getTarget().Options.UnsafeFPMath &&
16741 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16743 std::swap(LHS, RHS);
16745 Opcode = X86ISD::FMAX;
16748 // Converting this to a max would handle both negative zeros and NaNs
16749 // incorrectly, but we can swap the operands to fix both.
16750 std::swap(LHS, RHS);
16754 Opcode = X86ISD::FMAX;
16757 // Check for x CC y ? y : x -- a min/max with reversed arms.
16758 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16759 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16763 // Converting this to a min would handle comparisons between positive
16764 // and negative zero incorrectly, and swapping the operands would
16765 // cause it to handle NaNs incorrectly.
16766 if (!DAG.getTarget().Options.UnsafeFPMath &&
16767 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16768 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16770 std::swap(LHS, RHS);
16772 Opcode = X86ISD::FMIN;
16775 // Converting this to a min would handle NaNs incorrectly.
16776 if (!DAG.getTarget().Options.UnsafeFPMath &&
16777 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16779 Opcode = X86ISD::FMIN;
16782 // Converting this to a min would handle both negative zeros and NaNs
16783 // incorrectly, but we can swap the operands to fix both.
16784 std::swap(LHS, RHS);
16788 Opcode = X86ISD::FMIN;
16792 // Converting this to a max would handle NaNs incorrectly.
16793 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16795 Opcode = X86ISD::FMAX;
16798 // Converting this to a max would handle comparisons between positive
16799 // and negative zero incorrectly, and swapping the operands would
16800 // cause it to handle NaNs incorrectly.
16801 if (!DAG.getTarget().Options.UnsafeFPMath &&
16802 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16803 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16805 std::swap(LHS, RHS);
16807 Opcode = X86ISD::FMAX;
16810 // Converting this to a max would handle both negative zeros and NaNs
16811 // incorrectly, but we can swap the operands to fix both.
16812 std::swap(LHS, RHS);
16816 Opcode = X86ISD::FMAX;
16822 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16825 EVT CondVT = Cond.getValueType();
16826 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
16827 CondVT.getVectorElementType() == MVT::i1) {
16828 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
16829 // lowering on AVX-512. In this case we convert it to
16830 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
16831 // The same situation for all 128 and 256-bit vectors of i8 and i16
16832 EVT OpVT = LHS.getValueType();
16833 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
16834 (OpVT.getVectorElementType() == MVT::i8 ||
16835 OpVT.getVectorElementType() == MVT::i16)) {
16836 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
16837 DCI.AddToWorklist(Cond.getNode());
16838 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
16841 // If this is a select between two integer constants, try to do some
16843 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16844 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16845 // Don't do this for crazy integer types.
16846 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16847 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16848 // so that TrueC (the true value) is larger than FalseC.
16849 bool NeedsCondInvert = false;
16851 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16852 // Efficiently invertible.
16853 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
16854 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
16855 isa<ConstantSDNode>(Cond.getOperand(1))))) {
16856 NeedsCondInvert = true;
16857 std::swap(TrueC, FalseC);
16860 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
16861 if (FalseC->getAPIntValue() == 0 &&
16862 TrueC->getAPIntValue().isPowerOf2()) {
16863 if (NeedsCondInvert) // Invert the condition if needed.
16864 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16865 DAG.getConstant(1, Cond.getValueType()));
16867 // Zero extend the condition if needed.
16868 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16870 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16871 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16872 DAG.getConstant(ShAmt, MVT::i8));
16875 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16876 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16877 if (NeedsCondInvert) // Invert the condition if needed.
16878 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16879 DAG.getConstant(1, Cond.getValueType()));
16881 // Zero extend the condition if needed.
16882 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16883 FalseC->getValueType(0), Cond);
16884 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16885 SDValue(FalseC, 0));
16888 // Optimize cases that will turn into an LEA instruction. This requires
16889 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16890 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16891 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16892 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16894 bool isFastMultiplier = false;
16896 switch ((unsigned char)Diff) {
16898 case 1: // result = add base, cond
16899 case 2: // result = lea base( , cond*2)
16900 case 3: // result = lea base(cond, cond*2)
16901 case 4: // result = lea base( , cond*4)
16902 case 5: // result = lea base(cond, cond*4)
16903 case 8: // result = lea base( , cond*8)
16904 case 9: // result = lea base(cond, cond*8)
16905 isFastMultiplier = true;
16910 if (isFastMultiplier) {
16911 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16912 if (NeedsCondInvert) // Invert the condition if needed.
16913 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16914 DAG.getConstant(1, Cond.getValueType()));
16916 // Zero extend the condition if needed.
16917 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16919 // Scale the condition by the difference.
16921 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16922 DAG.getConstant(Diff, Cond.getValueType()));
16924 // Add the base if non-zero.
16925 if (FalseC->getAPIntValue() != 0)
16926 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16927 SDValue(FalseC, 0));
16934 // Canonicalize max and min:
16935 // (x > y) ? x : y -> (x >= y) ? x : y
16936 // (x < y) ? x : y -> (x <= y) ? x : y
16937 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16938 // the need for an extra compare
16939 // against zero. e.g.
16940 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16942 // testl %edi, %edi
16944 // cmovgl %edi, %eax
16948 // cmovsl %eax, %edi
16949 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16950 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16951 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16952 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16957 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16958 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16959 Cond.getOperand(0), Cond.getOperand(1), NewCC);
16960 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16965 // Early exit check
16966 if (!TLI.isTypeLegal(VT))
16969 // Match VSELECTs into subs with unsigned saturation.
16970 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16971 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16972 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16973 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16974 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16976 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16977 // left side invert the predicate to simplify logic below.
16979 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16981 CC = ISD::getSetCCInverse(CC, true);
16982 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16986 if (Other.getNode() && Other->getNumOperands() == 2 &&
16987 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16988 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16989 SDValue CondRHS = Cond->getOperand(1);
16991 // Look for a general sub with unsigned saturation first.
16992 // x >= y ? x-y : 0 --> subus x, y
16993 // x > y ? x-y : 0 --> subus x, y
16994 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16995 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16996 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16998 // If the RHS is a constant we have to reverse the const canonicalization.
16999 // x > C-1 ? x+-C : 0 --> subus x, C
17000 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17001 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17002 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17003 if (CondRHS.getConstantOperandVal(0) == -A-1)
17004 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17005 DAG.getConstant(-A, VT));
17008 // Another special case: If C was a sign bit, the sub has been
17009 // canonicalized into a xor.
17010 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17011 // it's safe to decanonicalize the xor?
17012 // x s< 0 ? x^C : 0 --> subus x, C
17013 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17014 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17015 isSplatVector(OpRHS.getNode())) {
17016 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17018 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17023 // Try to match a min/max vector operation.
17024 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17025 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17026 unsigned Opc = ret.first;
17027 bool NeedSplit = ret.second;
17029 if (Opc && NeedSplit) {
17030 unsigned NumElems = VT.getVectorNumElements();
17031 // Extract the LHS vectors
17032 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17033 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17035 // Extract the RHS vectors
17036 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17037 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17039 // Create min/max for each subvector
17040 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17041 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17043 // Merge the result
17044 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17046 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17049 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17050 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17051 // Check if SETCC has already been promoted
17052 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17053 // Check that condition value type matches vselect operand type
17056 assert(Cond.getValueType().isVector() &&
17057 "vector select expects a vector selector!");
17059 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17060 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17062 if (!TValIsAllOnes && !FValIsAllZeros) {
17063 // Try invert the condition if true value is not all 1s and false value
17065 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17066 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17068 if (TValIsAllZeros || FValIsAllOnes) {
17069 SDValue CC = Cond.getOperand(2);
17070 ISD::CondCode NewCC =
17071 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17072 Cond.getOperand(0).getValueType().isInteger());
17073 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17074 std::swap(LHS, RHS);
17075 TValIsAllOnes = FValIsAllOnes;
17076 FValIsAllZeros = TValIsAllZeros;
17080 if (TValIsAllOnes || FValIsAllZeros) {
17083 if (TValIsAllOnes && FValIsAllZeros)
17085 else if (TValIsAllOnes)
17086 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17087 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17088 else if (FValIsAllZeros)
17089 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17090 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17092 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17096 // If we know that this node is legal then we know that it is going to be
17097 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17098 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17099 // to simplify previous instructions.
17100 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17101 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17102 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17104 // Don't optimize vector selects that map to mask-registers.
17108 // Check all uses of that condition operand to check whether it will be
17109 // consumed by non-BLEND instructions, which may depend on all bits are set
17111 for (SDNode::use_iterator I = Cond->use_begin(),
17112 E = Cond->use_end(); I != E; ++I)
17113 if (I->getOpcode() != ISD::VSELECT)
17114 // TODO: Add other opcodes eventually lowered into BLEND.
17117 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17118 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17120 APInt KnownZero, KnownOne;
17121 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17122 DCI.isBeforeLegalizeOps());
17123 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17124 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17125 DCI.CommitTargetLoweringOpt(TLO);
17131 // Check whether a boolean test is testing a boolean value generated by
17132 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17135 // Simplify the following patterns:
17136 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17137 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17138 // to (Op EFLAGS Cond)
17140 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17141 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17142 // to (Op EFLAGS !Cond)
17144 // where Op could be BRCOND or CMOV.
17146 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17147 // Quit if not CMP and SUB with its value result used.
17148 if (Cmp.getOpcode() != X86ISD::CMP &&
17149 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17152 // Quit if not used as a boolean value.
17153 if (CC != X86::COND_E && CC != X86::COND_NE)
17156 // Check CMP operands. One of them should be 0 or 1 and the other should be
17157 // an SetCC or extended from it.
17158 SDValue Op1 = Cmp.getOperand(0);
17159 SDValue Op2 = Cmp.getOperand(1);
17162 const ConstantSDNode* C = 0;
17163 bool needOppositeCond = (CC == X86::COND_E);
17164 bool checkAgainstTrue = false; // Is it a comparison against 1?
17166 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17168 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17170 else // Quit if all operands are not constants.
17173 if (C->getZExtValue() == 1) {
17174 needOppositeCond = !needOppositeCond;
17175 checkAgainstTrue = true;
17176 } else if (C->getZExtValue() != 0)
17177 // Quit if the constant is neither 0 or 1.
17180 bool truncatedToBoolWithAnd = false;
17181 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17182 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17183 SetCC.getOpcode() == ISD::TRUNCATE ||
17184 SetCC.getOpcode() == ISD::AND) {
17185 if (SetCC.getOpcode() == ISD::AND) {
17187 ConstantSDNode *CS;
17188 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17189 CS->getZExtValue() == 1)
17191 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17192 CS->getZExtValue() == 1)
17196 SetCC = SetCC.getOperand(OpIdx);
17197 truncatedToBoolWithAnd = true;
17199 SetCC = SetCC.getOperand(0);
17202 switch (SetCC.getOpcode()) {
17203 case X86ISD::SETCC_CARRY:
17204 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17205 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17206 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17207 // truncated to i1 using 'and'.
17208 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17210 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17211 "Invalid use of SETCC_CARRY!");
17213 case X86ISD::SETCC:
17214 // Set the condition code or opposite one if necessary.
17215 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17216 if (needOppositeCond)
17217 CC = X86::GetOppositeBranchCondition(CC);
17218 return SetCC.getOperand(1);
17219 case X86ISD::CMOV: {
17220 // Check whether false/true value has canonical one, i.e. 0 or 1.
17221 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17222 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17223 // Quit if true value is not a constant.
17226 // Quit if false value is not a constant.
17228 SDValue Op = SetCC.getOperand(0);
17229 // Skip 'zext' or 'trunc' node.
17230 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17231 Op.getOpcode() == ISD::TRUNCATE)
17232 Op = Op.getOperand(0);
17233 // A special case for rdrand/rdseed, where 0 is set if false cond is
17235 if ((Op.getOpcode() != X86ISD::RDRAND &&
17236 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17239 // Quit if false value is not the constant 0 or 1.
17240 bool FValIsFalse = true;
17241 if (FVal && FVal->getZExtValue() != 0) {
17242 if (FVal->getZExtValue() != 1)
17244 // If FVal is 1, opposite cond is needed.
17245 needOppositeCond = !needOppositeCond;
17246 FValIsFalse = false;
17248 // Quit if TVal is not the constant opposite of FVal.
17249 if (FValIsFalse && TVal->getZExtValue() != 1)
17251 if (!FValIsFalse && TVal->getZExtValue() != 0)
17253 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17254 if (needOppositeCond)
17255 CC = X86::GetOppositeBranchCondition(CC);
17256 return SetCC.getOperand(3);
17263 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17264 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17265 TargetLowering::DAGCombinerInfo &DCI,
17266 const X86Subtarget *Subtarget) {
17269 // If the flag operand isn't dead, don't touch this CMOV.
17270 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17273 SDValue FalseOp = N->getOperand(0);
17274 SDValue TrueOp = N->getOperand(1);
17275 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17276 SDValue Cond = N->getOperand(3);
17278 if (CC == X86::COND_E || CC == X86::COND_NE) {
17279 switch (Cond.getOpcode()) {
17283 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17284 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17285 return (CC == X86::COND_E) ? FalseOp : TrueOp;
17291 Flags = checkBoolTestSetCCCombine(Cond, CC);
17292 if (Flags.getNode() &&
17293 // Extra check as FCMOV only supports a subset of X86 cond.
17294 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17295 SDValue Ops[] = { FalseOp, TrueOp,
17296 DAG.getConstant(CC, MVT::i8), Flags };
17297 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17298 Ops, array_lengthof(Ops));
17301 // If this is a select between two integer constants, try to do some
17302 // optimizations. Note that the operands are ordered the opposite of SELECT
17304 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17305 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17306 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17307 // larger than FalseC (the false value).
17308 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17309 CC = X86::GetOppositeBranchCondition(CC);
17310 std::swap(TrueC, FalseC);
17311 std::swap(TrueOp, FalseOp);
17314 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
17315 // This is efficient for any integer data type (including i8/i16) and
17317 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17318 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17319 DAG.getConstant(CC, MVT::i8), Cond);
17321 // Zero extend the condition if needed.
17322 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17324 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17325 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17326 DAG.getConstant(ShAmt, MVT::i8));
17327 if (N->getNumValues() == 2) // Dead flag value?
17328 return DCI.CombineTo(N, Cond, SDValue());
17332 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
17333 // for any integer data type, including i8/i16.
17334 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17335 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17336 DAG.getConstant(CC, MVT::i8), Cond);
17338 // Zero extend the condition if needed.
17339 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17340 FalseC->getValueType(0), Cond);
17341 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17342 SDValue(FalseC, 0));
17344 if (N->getNumValues() == 2) // Dead flag value?
17345 return DCI.CombineTo(N, Cond, SDValue());
17349 // Optimize cases that will turn into an LEA instruction. This requires
17350 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17351 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17352 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17353 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17355 bool isFastMultiplier = false;
17357 switch ((unsigned char)Diff) {
17359 case 1: // result = add base, cond
17360 case 2: // result = lea base( , cond*2)
17361 case 3: // result = lea base(cond, cond*2)
17362 case 4: // result = lea base( , cond*4)
17363 case 5: // result = lea base(cond, cond*4)
17364 case 8: // result = lea base( , cond*8)
17365 case 9: // result = lea base(cond, cond*8)
17366 isFastMultiplier = true;
17371 if (isFastMultiplier) {
17372 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17373 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17374 DAG.getConstant(CC, MVT::i8), Cond);
17375 // Zero extend the condition if needed.
17376 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17378 // Scale the condition by the difference.
17380 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17381 DAG.getConstant(Diff, Cond.getValueType()));
17383 // Add the base if non-zero.
17384 if (FalseC->getAPIntValue() != 0)
17385 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17386 SDValue(FalseC, 0));
17387 if (N->getNumValues() == 2) // Dead flag value?
17388 return DCI.CombineTo(N, Cond, SDValue());
17395 // Handle these cases:
17396 // (select (x != c), e, c) -> select (x != c), e, x),
17397 // (select (x == c), c, e) -> select (x == c), x, e)
17398 // where the c is an integer constant, and the "select" is the combination
17399 // of CMOV and CMP.
17401 // The rationale for this change is that the conditional-move from a constant
17402 // needs two instructions, however, conditional-move from a register needs
17403 // only one instruction.
17405 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17406 // some instruction-combining opportunities. This opt needs to be
17407 // postponed as late as possible.
17409 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17410 // the DCI.xxxx conditions are provided to postpone the optimization as
17411 // late as possible.
17413 ConstantSDNode *CmpAgainst = 0;
17414 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17415 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17416 !isa<ConstantSDNode>(Cond.getOperand(0))) {
17418 if (CC == X86::COND_NE &&
17419 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17420 CC = X86::GetOppositeBranchCondition(CC);
17421 std::swap(TrueOp, FalseOp);
17424 if (CC == X86::COND_E &&
17425 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17426 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17427 DAG.getConstant(CC, MVT::i8), Cond };
17428 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17429 array_lengthof(Ops));
17437 /// PerformMulCombine - Optimize a single multiply with constant into two
17438 /// in order to implement it with two cheaper instructions, e.g.
17439 /// LEA + SHL, LEA + LEA.
17440 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17441 TargetLowering::DAGCombinerInfo &DCI) {
17442 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17445 EVT VT = N->getValueType(0);
17446 if (VT != MVT::i64)
17449 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17452 uint64_t MulAmt = C->getZExtValue();
17453 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17456 uint64_t MulAmt1 = 0;
17457 uint64_t MulAmt2 = 0;
17458 if ((MulAmt % 9) == 0) {
17460 MulAmt2 = MulAmt / 9;
17461 } else if ((MulAmt % 5) == 0) {
17463 MulAmt2 = MulAmt / 5;
17464 } else if ((MulAmt % 3) == 0) {
17466 MulAmt2 = MulAmt / 3;
17469 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17472 if (isPowerOf2_64(MulAmt2) &&
17473 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17474 // If second multiplifer is pow2, issue it first. We want the multiply by
17475 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17477 std::swap(MulAmt1, MulAmt2);
17480 if (isPowerOf2_64(MulAmt1))
17481 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17482 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17484 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17485 DAG.getConstant(MulAmt1, VT));
17487 if (isPowerOf2_64(MulAmt2))
17488 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17489 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17491 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17492 DAG.getConstant(MulAmt2, VT));
17494 // Do not add new nodes to DAG combiner worklist.
17495 DCI.CombineTo(N, NewMul, false);
17500 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17501 SDValue N0 = N->getOperand(0);
17502 SDValue N1 = N->getOperand(1);
17503 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17504 EVT VT = N0.getValueType();
17506 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17507 // since the result of setcc_c is all zero's or all ones.
17508 if (VT.isInteger() && !VT.isVector() &&
17509 N1C && N0.getOpcode() == ISD::AND &&
17510 N0.getOperand(1).getOpcode() == ISD::Constant) {
17511 SDValue N00 = N0.getOperand(0);
17512 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17513 ((N00.getOpcode() == ISD::ANY_EXTEND ||
17514 N00.getOpcode() == ISD::ZERO_EXTEND) &&
17515 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17516 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17517 APInt ShAmt = N1C->getAPIntValue();
17518 Mask = Mask.shl(ShAmt);
17520 return DAG.getNode(ISD::AND, SDLoc(N), VT,
17521 N00, DAG.getConstant(Mask, VT));
17525 // Hardware support for vector shifts is sparse which makes us scalarize the
17526 // vector operations in many cases. Also, on sandybridge ADD is faster than
17528 // (shl V, 1) -> add V,V
17529 if (isSplatVector(N1.getNode())) {
17530 assert(N0.getValueType().isVector() && "Invalid vector shift type");
17531 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17532 // We shift all of the values by one. In many cases we do not have
17533 // hardware support for this operation. This is better expressed as an ADD
17535 if (N1C && (1 == N1C->getZExtValue())) {
17536 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17543 /// \brief Returns a vector of 0s if the node in input is a vector logical
17544 /// shift by a constant amount which is known to be bigger than or equal
17545 /// to the vector element size in bits.
17546 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17547 const X86Subtarget *Subtarget) {
17548 EVT VT = N->getValueType(0);
17550 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17551 (!Subtarget->hasInt256() ||
17552 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17555 SDValue Amt = N->getOperand(1);
17557 if (isSplatVector(Amt.getNode())) {
17558 SDValue SclrAmt = Amt->getOperand(0);
17559 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17560 APInt ShiftAmt = C->getAPIntValue();
17561 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17563 // SSE2/AVX2 logical shifts always return a vector of 0s
17564 // if the shift amount is bigger than or equal to
17565 // the element size. The constant shift amount will be
17566 // encoded as a 8-bit immediate.
17567 if (ShiftAmt.trunc(8).uge(MaxAmount))
17568 return getZeroVector(VT, Subtarget, DAG, DL);
17575 /// PerformShiftCombine - Combine shifts.
17576 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17577 TargetLowering::DAGCombinerInfo &DCI,
17578 const X86Subtarget *Subtarget) {
17579 if (N->getOpcode() == ISD::SHL) {
17580 SDValue V = PerformSHLCombine(N, DAG);
17581 if (V.getNode()) return V;
17584 if (N->getOpcode() != ISD::SRA) {
17585 // Try to fold this logical shift into a zero vector.
17586 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17587 if (V.getNode()) return V;
17593 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
17594 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17595 // and friends. Likewise for OR -> CMPNEQSS.
17596 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17597 TargetLowering::DAGCombinerInfo &DCI,
17598 const X86Subtarget *Subtarget) {
17601 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17602 // we're requiring SSE2 for both.
17603 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17604 SDValue N0 = N->getOperand(0);
17605 SDValue N1 = N->getOperand(1);
17606 SDValue CMP0 = N0->getOperand(1);
17607 SDValue CMP1 = N1->getOperand(1);
17610 // The SETCCs should both refer to the same CMP.
17611 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17614 SDValue CMP00 = CMP0->getOperand(0);
17615 SDValue CMP01 = CMP0->getOperand(1);
17616 EVT VT = CMP00.getValueType();
17618 if (VT == MVT::f32 || VT == MVT::f64) {
17619 bool ExpectingFlags = false;
17620 // Check for any users that want flags:
17621 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17622 !ExpectingFlags && UI != UE; ++UI)
17623 switch (UI->getOpcode()) {
17628 ExpectingFlags = true;
17630 case ISD::CopyToReg:
17631 case ISD::SIGN_EXTEND:
17632 case ISD::ZERO_EXTEND:
17633 case ISD::ANY_EXTEND:
17637 if (!ExpectingFlags) {
17638 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17639 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17641 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17642 X86::CondCode tmp = cc0;
17647 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
17648 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17649 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17650 // FIXME: need symbolic constants for these magic numbers.
17651 // See X86ATTInstPrinter.cpp:printSSECC().
17652 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17653 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00, CMP01,
17654 DAG.getConstant(x86cc, MVT::i8));
17655 MVT IntVT = (is64BitFP ? MVT::i64 : MVT::i32);
17656 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
17658 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
17659 DAG.getConstant(1, IntVT));
17660 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17661 return OneBitOfTruth;
17669 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17670 /// so it can be folded inside ANDNP.
17671 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17672 EVT VT = N->getValueType(0);
17674 // Match direct AllOnes for 128 and 256-bit vectors
17675 if (ISD::isBuildVectorAllOnes(N))
17678 // Look through a bit convert.
17679 if (N->getOpcode() == ISD::BITCAST)
17680 N = N->getOperand(0).getNode();
17682 // Sometimes the operand may come from a insert_subvector building a 256-bit
17684 if (VT.is256BitVector() &&
17685 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17686 SDValue V1 = N->getOperand(0);
17687 SDValue V2 = N->getOperand(1);
17689 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17690 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17691 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17692 ISD::isBuildVectorAllOnes(V2.getNode()))
17699 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17700 // register. In most cases we actually compare or select YMM-sized registers
17701 // and mixing the two types creates horrible code. This method optimizes
17702 // some of the transition sequences.
17703 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17704 TargetLowering::DAGCombinerInfo &DCI,
17705 const X86Subtarget *Subtarget) {
17706 EVT VT = N->getValueType(0);
17707 if (!VT.is256BitVector())
17710 assert((N->getOpcode() == ISD::ANY_EXTEND ||
17711 N->getOpcode() == ISD::ZERO_EXTEND ||
17712 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17714 SDValue Narrow = N->getOperand(0);
17715 EVT NarrowVT = Narrow->getValueType(0);
17716 if (!NarrowVT.is128BitVector())
17719 if (Narrow->getOpcode() != ISD::XOR &&
17720 Narrow->getOpcode() != ISD::AND &&
17721 Narrow->getOpcode() != ISD::OR)
17724 SDValue N0 = Narrow->getOperand(0);
17725 SDValue N1 = Narrow->getOperand(1);
17728 // The Left side has to be a trunc.
17729 if (N0.getOpcode() != ISD::TRUNCATE)
17732 // The type of the truncated inputs.
17733 EVT WideVT = N0->getOperand(0)->getValueType(0);
17737 // The right side has to be a 'trunc' or a constant vector.
17738 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17739 bool RHSConst = (isSplatVector(N1.getNode()) &&
17740 isa<ConstantSDNode>(N1->getOperand(0)));
17741 if (!RHSTrunc && !RHSConst)
17744 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17746 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17749 // Set N0 and N1 to hold the inputs to the new wide operation.
17750 N0 = N0->getOperand(0);
17752 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17753 N1->getOperand(0));
17754 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17755 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17756 } else if (RHSTrunc) {
17757 N1 = N1->getOperand(0);
17760 // Generate the wide operation.
17761 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17762 unsigned Opcode = N->getOpcode();
17764 case ISD::ANY_EXTEND:
17766 case ISD::ZERO_EXTEND: {
17767 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17768 APInt Mask = APInt::getAllOnesValue(InBits);
17769 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17770 return DAG.getNode(ISD::AND, DL, VT,
17771 Op, DAG.getConstant(Mask, VT));
17773 case ISD::SIGN_EXTEND:
17774 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17775 Op, DAG.getValueType(NarrowVT));
17777 llvm_unreachable("Unexpected opcode");
17781 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17782 TargetLowering::DAGCombinerInfo &DCI,
17783 const X86Subtarget *Subtarget) {
17784 EVT VT = N->getValueType(0);
17785 if (DCI.isBeforeLegalizeOps())
17788 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17792 // Create BLSI, BLSR, and BZHI instructions
17793 // BLSI is X & (-X)
17794 // BLSR is X & (X-1)
17795 // BZHI is X & ((1 << Y) - 1)
17796 // BEXTR is ((X >> imm) & (2**size-1))
17797 if (VT == MVT::i32 || VT == MVT::i64) {
17798 SDValue N0 = N->getOperand(0);
17799 SDValue N1 = N->getOperand(1);
17802 if (Subtarget->hasBMI()) {
17803 // Check LHS for neg
17804 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17805 isZero(N0.getOperand(0)))
17806 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17808 // Check RHS for neg
17809 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17810 isZero(N1.getOperand(0)))
17811 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17813 // Check LHS for X-1
17814 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17815 isAllOnes(N0.getOperand(1)))
17816 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17818 // Check RHS for X-1
17819 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17820 isAllOnes(N1.getOperand(1)))
17821 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17824 if (Subtarget->hasBMI2()) {
17825 // Check for (and (add (shl 1, Y), -1), X)
17826 if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
17827 SDValue N00 = N0.getOperand(0);
17828 if (N00.getOpcode() == ISD::SHL) {
17829 SDValue N001 = N00.getOperand(1);
17830 assert(N001.getValueType() == MVT::i8 && "unexpected type");
17831 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
17832 if (C && C->getZExtValue() == 1)
17833 return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
17837 // Check for (and X, (add (shl 1, Y), -1))
17838 if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
17839 SDValue N10 = N1.getOperand(0);
17840 if (N10.getOpcode() == ISD::SHL) {
17841 SDValue N101 = N10.getOperand(1);
17842 assert(N101.getValueType() == MVT::i8 && "unexpected type");
17843 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
17844 if (C && C->getZExtValue() == 1)
17845 return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
17850 // Check for BEXTR.
17851 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
17852 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
17853 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
17854 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17855 if (MaskNode && ShiftNode) {
17856 uint64_t Mask = MaskNode->getZExtValue();
17857 uint64_t Shift = ShiftNode->getZExtValue();
17858 if (isMask_64(Mask)) {
17859 uint64_t MaskSize = CountPopulation_64(Mask);
17860 if (Shift + MaskSize <= VT.getSizeInBits())
17861 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
17862 DAG.getConstant(Shift | (MaskSize << 8), VT));
17870 // Want to form ANDNP nodes:
17871 // 1) In the hopes of then easily combining them with OR and AND nodes
17872 // to form PBLEND/PSIGN.
17873 // 2) To match ANDN packed intrinsics
17874 if (VT != MVT::v2i64 && VT != MVT::v4i64)
17877 SDValue N0 = N->getOperand(0);
17878 SDValue N1 = N->getOperand(1);
17881 // Check LHS for vnot
17882 if (N0.getOpcode() == ISD::XOR &&
17883 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17884 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17885 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17887 // Check RHS for vnot
17888 if (N1.getOpcode() == ISD::XOR &&
17889 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17890 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17891 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17896 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17897 TargetLowering::DAGCombinerInfo &DCI,
17898 const X86Subtarget *Subtarget) {
17899 EVT VT = N->getValueType(0);
17900 if (DCI.isBeforeLegalizeOps())
17903 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17907 SDValue N0 = N->getOperand(0);
17908 SDValue N1 = N->getOperand(1);
17910 // look for psign/blend
17911 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17912 if (!Subtarget->hasSSSE3() ||
17913 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17916 // Canonicalize pandn to RHS
17917 if (N0.getOpcode() == X86ISD::ANDNP)
17919 // or (and (m, y), (pandn m, x))
17920 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17921 SDValue Mask = N1.getOperand(0);
17922 SDValue X = N1.getOperand(1);
17924 if (N0.getOperand(0) == Mask)
17925 Y = N0.getOperand(1);
17926 if (N0.getOperand(1) == Mask)
17927 Y = N0.getOperand(0);
17929 // Check to see if the mask appeared in both the AND and ANDNP and
17933 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17934 // Look through mask bitcast.
17935 if (Mask.getOpcode() == ISD::BITCAST)
17936 Mask = Mask.getOperand(0);
17937 if (X.getOpcode() == ISD::BITCAST)
17938 X = X.getOperand(0);
17939 if (Y.getOpcode() == ISD::BITCAST)
17940 Y = Y.getOperand(0);
17942 EVT MaskVT = Mask.getValueType();
17944 // Validate that the Mask operand is a vector sra node.
17945 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17946 // there is no psrai.b
17947 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17948 unsigned SraAmt = ~0;
17949 if (Mask.getOpcode() == ISD::SRA) {
17950 SDValue Amt = Mask.getOperand(1);
17951 if (isSplatVector(Amt.getNode())) {
17952 SDValue SclrAmt = Amt->getOperand(0);
17953 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17954 SraAmt = C->getZExtValue();
17956 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17957 SDValue SraC = Mask.getOperand(1);
17958 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
17960 if ((SraAmt + 1) != EltBits)
17965 // Now we know we at least have a plendvb with the mask val. See if
17966 // we can form a psignb/w/d.
17967 // psign = x.type == y.type == mask.type && y = sub(0, x);
17968 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17969 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17970 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17971 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17972 "Unsupported VT for PSIGN");
17973 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17974 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17976 // PBLENDVB only available on SSE 4.1
17977 if (!Subtarget->hasSSE41())
17980 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17982 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17983 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17984 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17985 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17986 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17990 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17993 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17994 MachineFunction &MF = DAG.getMachineFunction();
17995 bool OptForSize = MF.getFunction()->getAttributes().
17996 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
17998 // SHLD/SHRD instructions have lower register pressure, but on some
17999 // platforms they have higher latency than the equivalent
18000 // series of shifts/or that would otherwise be generated.
18001 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18002 // have higher latencies and we are not optimizing for size.
18003 if (!OptForSize && Subtarget->isSHLDSlow())
18006 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18008 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18010 if (!N0.hasOneUse() || !N1.hasOneUse())
18013 SDValue ShAmt0 = N0.getOperand(1);
18014 if (ShAmt0.getValueType() != MVT::i8)
18016 SDValue ShAmt1 = N1.getOperand(1);
18017 if (ShAmt1.getValueType() != MVT::i8)
18019 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18020 ShAmt0 = ShAmt0.getOperand(0);
18021 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18022 ShAmt1 = ShAmt1.getOperand(0);
18025 unsigned Opc = X86ISD::SHLD;
18026 SDValue Op0 = N0.getOperand(0);
18027 SDValue Op1 = N1.getOperand(0);
18028 if (ShAmt0.getOpcode() == ISD::SUB) {
18029 Opc = X86ISD::SHRD;
18030 std::swap(Op0, Op1);
18031 std::swap(ShAmt0, ShAmt1);
18034 unsigned Bits = VT.getSizeInBits();
18035 if (ShAmt1.getOpcode() == ISD::SUB) {
18036 SDValue Sum = ShAmt1.getOperand(0);
18037 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18038 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18039 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18040 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18041 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18042 return DAG.getNode(Opc, DL, VT,
18044 DAG.getNode(ISD::TRUNCATE, DL,
18047 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18048 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18050 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18051 return DAG.getNode(Opc, DL, VT,
18052 N0.getOperand(0), N1.getOperand(0),
18053 DAG.getNode(ISD::TRUNCATE, DL,
18060 // Generate NEG and CMOV for integer abs.
18061 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18062 EVT VT = N->getValueType(0);
18064 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18065 // 8-bit integer abs to NEG and CMOV.
18066 if (VT.isInteger() && VT.getSizeInBits() == 8)
18069 SDValue N0 = N->getOperand(0);
18070 SDValue N1 = N->getOperand(1);
18073 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18074 // and change it to SUB and CMOV.
18075 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18076 N0.getOpcode() == ISD::ADD &&
18077 N0.getOperand(1) == N1 &&
18078 N1.getOpcode() == ISD::SRA &&
18079 N1.getOperand(0) == N0.getOperand(0))
18080 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18081 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18082 // Generate SUB & CMOV.
18083 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18084 DAG.getConstant(0, VT), N0.getOperand(0));
18086 SDValue Ops[] = { N0.getOperand(0), Neg,
18087 DAG.getConstant(X86::COND_GE, MVT::i8),
18088 SDValue(Neg.getNode(), 1) };
18089 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18090 Ops, array_lengthof(Ops));
18095 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18096 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18097 TargetLowering::DAGCombinerInfo &DCI,
18098 const X86Subtarget *Subtarget) {
18099 EVT VT = N->getValueType(0);
18100 if (DCI.isBeforeLegalizeOps())
18103 if (Subtarget->hasCMov()) {
18104 SDValue RV = performIntegerAbsCombine(N, DAG);
18109 // Try forming BMI if it is available.
18110 if (!Subtarget->hasBMI())
18113 if (VT != MVT::i32 && VT != MVT::i64)
18116 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
18118 // Create BLSMSK instructions by finding X ^ (X-1)
18119 SDValue N0 = N->getOperand(0);
18120 SDValue N1 = N->getOperand(1);
18123 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18124 isAllOnes(N0.getOperand(1)))
18125 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
18127 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18128 isAllOnes(N1.getOperand(1)))
18129 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
18134 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18135 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18136 TargetLowering::DAGCombinerInfo &DCI,
18137 const X86Subtarget *Subtarget) {
18138 LoadSDNode *Ld = cast<LoadSDNode>(N);
18139 EVT RegVT = Ld->getValueType(0);
18140 EVT MemVT = Ld->getMemoryVT();
18142 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18143 unsigned RegSz = RegVT.getSizeInBits();
18145 // On Sandybridge unaligned 256bit loads are inefficient.
18146 ISD::LoadExtType Ext = Ld->getExtensionType();
18147 unsigned Alignment = Ld->getAlignment();
18148 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18149 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18150 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18151 unsigned NumElems = RegVT.getVectorNumElements();
18155 SDValue Ptr = Ld->getBasePtr();
18156 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18158 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18160 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18161 Ld->getPointerInfo(), Ld->isVolatile(),
18162 Ld->isNonTemporal(), Ld->isInvariant(),
18164 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18165 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18166 Ld->getPointerInfo(), Ld->isVolatile(),
18167 Ld->isNonTemporal(), Ld->isInvariant(),
18168 std::min(16U, Alignment));
18169 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18171 Load2.getValue(1));
18173 SDValue NewVec = DAG.getUNDEF(RegVT);
18174 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18175 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18176 return DCI.CombineTo(N, NewVec, TF, true);
18179 // If this is a vector EXT Load then attempt to optimize it using a
18180 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18181 // expansion is still better than scalar code.
18182 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18183 // emit a shuffle and a arithmetic shift.
18184 // TODO: It is possible to support ZExt by zeroing the undef values
18185 // during the shuffle phase or after the shuffle.
18186 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18187 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18188 assert(MemVT != RegVT && "Cannot extend to the same type");
18189 assert(MemVT.isVector() && "Must load a vector from memory");
18191 unsigned NumElems = RegVT.getVectorNumElements();
18192 unsigned MemSz = MemVT.getSizeInBits();
18193 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18195 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18198 // All sizes must be a power of two.
18199 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18202 // Attempt to load the original value using scalar loads.
18203 // Find the largest scalar type that divides the total loaded size.
18204 MVT SclrLoadTy = MVT::i8;
18205 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18206 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18207 MVT Tp = (MVT::SimpleValueType)tp;
18208 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18213 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18214 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18216 SclrLoadTy = MVT::f64;
18218 // Calculate the number of scalar loads that we need to perform
18219 // in order to load our vector from memory.
18220 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18221 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18224 unsigned loadRegZize = RegSz;
18225 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18228 // Represent our vector as a sequence of elements which are the
18229 // largest scalar that we can load.
18230 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18231 loadRegZize/SclrLoadTy.getSizeInBits());
18233 // Represent the data using the same element type that is stored in
18234 // memory. In practice, we ''widen'' MemVT.
18236 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18237 loadRegZize/MemVT.getScalarType().getSizeInBits());
18239 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18240 "Invalid vector type");
18242 // We can't shuffle using an illegal type.
18243 if (!TLI.isTypeLegal(WideVecVT))
18246 SmallVector<SDValue, 8> Chains;
18247 SDValue Ptr = Ld->getBasePtr();
18248 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18249 TLI.getPointerTy());
18250 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18252 for (unsigned i = 0; i < NumLoads; ++i) {
18253 // Perform a single load.
18254 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18255 Ptr, Ld->getPointerInfo(),
18256 Ld->isVolatile(), Ld->isNonTemporal(),
18257 Ld->isInvariant(), Ld->getAlignment());
18258 Chains.push_back(ScalarLoad.getValue(1));
18259 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18260 // another round of DAGCombining.
18262 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18264 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18265 ScalarLoad, DAG.getIntPtrConstant(i));
18267 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18270 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18273 // Bitcast the loaded value to a vector of the original element type, in
18274 // the size of the target vector type.
18275 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18276 unsigned SizeRatio = RegSz/MemSz;
18278 if (Ext == ISD::SEXTLOAD) {
18279 // If we have SSE4.1 we can directly emit a VSEXT node.
18280 if (Subtarget->hasSSE41()) {
18281 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18282 return DCI.CombineTo(N, Sext, TF, true);
18285 // Otherwise we'll shuffle the small elements in the high bits of the
18286 // larger type and perform an arithmetic shift. If the shift is not legal
18287 // it's better to scalarize.
18288 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18291 // Redistribute the loaded elements into the different locations.
18292 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18293 for (unsigned i = 0; i != NumElems; ++i)
18294 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18296 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18297 DAG.getUNDEF(WideVecVT),
18300 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18302 // Build the arithmetic shift.
18303 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18304 MemVT.getVectorElementType().getSizeInBits();
18305 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18306 DAG.getConstant(Amt, RegVT));
18308 return DCI.CombineTo(N, Shuff, TF, true);
18311 // Redistribute the loaded elements into the different locations.
18312 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18313 for (unsigned i = 0; i != NumElems; ++i)
18314 ShuffleVec[i*SizeRatio] = i;
18316 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18317 DAG.getUNDEF(WideVecVT),
18320 // Bitcast to the requested type.
18321 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18322 // Replace the original load with the new sequence
18323 // and return the new chain.
18324 return DCI.CombineTo(N, Shuff, TF, true);
18330 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18331 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18332 const X86Subtarget *Subtarget) {
18333 StoreSDNode *St = cast<StoreSDNode>(N);
18334 EVT VT = St->getValue().getValueType();
18335 EVT StVT = St->getMemoryVT();
18337 SDValue StoredVal = St->getOperand(1);
18338 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18340 // If we are saving a concatenation of two XMM registers, perform two stores.
18341 // On Sandy Bridge, 256-bit memory operations are executed by two
18342 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18343 // memory operation.
18344 unsigned Alignment = St->getAlignment();
18345 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18346 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18347 StVT == VT && !IsAligned) {
18348 unsigned NumElems = VT.getVectorNumElements();
18352 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18353 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18355 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18356 SDValue Ptr0 = St->getBasePtr();
18357 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18359 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18360 St->getPointerInfo(), St->isVolatile(),
18361 St->isNonTemporal(), Alignment);
18362 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18363 St->getPointerInfo(), St->isVolatile(),
18364 St->isNonTemporal(),
18365 std::min(16U, Alignment));
18366 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18369 // Optimize trunc store (of multiple scalars) to shuffle and store.
18370 // First, pack all of the elements in one place. Next, store to memory
18371 // in fewer chunks.
18372 if (St->isTruncatingStore() && VT.isVector()) {
18373 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18374 unsigned NumElems = VT.getVectorNumElements();
18375 assert(StVT != VT && "Cannot truncate to the same type");
18376 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18377 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18379 // From, To sizes and ElemCount must be pow of two
18380 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18381 // We are going to use the original vector elt for storing.
18382 // Accumulated smaller vector elements must be a multiple of the store size.
18383 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18385 unsigned SizeRatio = FromSz / ToSz;
18387 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18389 // Create a type on which we perform the shuffle
18390 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18391 StVT.getScalarType(), NumElems*SizeRatio);
18393 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18395 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18396 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18397 for (unsigned i = 0; i != NumElems; ++i)
18398 ShuffleVec[i] = i * SizeRatio;
18400 // Can't shuffle using an illegal type.
18401 if (!TLI.isTypeLegal(WideVecVT))
18404 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18405 DAG.getUNDEF(WideVecVT),
18407 // At this point all of the data is stored at the bottom of the
18408 // register. We now need to save it to mem.
18410 // Find the largest store unit
18411 MVT StoreType = MVT::i8;
18412 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18413 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18414 MVT Tp = (MVT::SimpleValueType)tp;
18415 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18419 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18420 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18421 (64 <= NumElems * ToSz))
18422 StoreType = MVT::f64;
18424 // Bitcast the original vector into a vector of store-size units
18425 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18426 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18427 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18428 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18429 SmallVector<SDValue, 8> Chains;
18430 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18431 TLI.getPointerTy());
18432 SDValue Ptr = St->getBasePtr();
18434 // Perform one or more big stores into memory.
18435 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18436 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18437 StoreType, ShuffWide,
18438 DAG.getIntPtrConstant(i));
18439 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18440 St->getPointerInfo(), St->isVolatile(),
18441 St->isNonTemporal(), St->getAlignment());
18442 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18443 Chains.push_back(Ch);
18446 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18450 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
18451 // the FP state in cases where an emms may be missing.
18452 // A preferable solution to the general problem is to figure out the right
18453 // places to insert EMMS. This qualifies as a quick hack.
18455 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18456 if (VT.getSizeInBits() != 64)
18459 const Function *F = DAG.getMachineFunction().getFunction();
18460 bool NoImplicitFloatOps = F->getAttributes().
18461 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18462 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18463 && Subtarget->hasSSE2();
18464 if ((VT.isVector() ||
18465 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18466 isa<LoadSDNode>(St->getValue()) &&
18467 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18468 St->getChain().hasOneUse() && !St->isVolatile()) {
18469 SDNode* LdVal = St->getValue().getNode();
18470 LoadSDNode *Ld = 0;
18471 int TokenFactorIndex = -1;
18472 SmallVector<SDValue, 8> Ops;
18473 SDNode* ChainVal = St->getChain().getNode();
18474 // Must be a store of a load. We currently handle two cases: the load
18475 // is a direct child, and it's under an intervening TokenFactor. It is
18476 // possible to dig deeper under nested TokenFactors.
18477 if (ChainVal == LdVal)
18478 Ld = cast<LoadSDNode>(St->getChain());
18479 else if (St->getValue().hasOneUse() &&
18480 ChainVal->getOpcode() == ISD::TokenFactor) {
18481 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18482 if (ChainVal->getOperand(i).getNode() == LdVal) {
18483 TokenFactorIndex = i;
18484 Ld = cast<LoadSDNode>(St->getValue());
18486 Ops.push_back(ChainVal->getOperand(i));
18490 if (!Ld || !ISD::isNormalLoad(Ld))
18493 // If this is not the MMX case, i.e. we are just turning i64 load/store
18494 // into f64 load/store, avoid the transformation if there are multiple
18495 // uses of the loaded value.
18496 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18501 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18502 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18504 if (Subtarget->is64Bit() || F64IsLegal) {
18505 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18506 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18507 Ld->getPointerInfo(), Ld->isVolatile(),
18508 Ld->isNonTemporal(), Ld->isInvariant(),
18509 Ld->getAlignment());
18510 SDValue NewChain = NewLd.getValue(1);
18511 if (TokenFactorIndex != -1) {
18512 Ops.push_back(NewChain);
18513 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18516 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18517 St->getPointerInfo(),
18518 St->isVolatile(), St->isNonTemporal(),
18519 St->getAlignment());
18522 // Otherwise, lower to two pairs of 32-bit loads / stores.
18523 SDValue LoAddr = Ld->getBasePtr();
18524 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18525 DAG.getConstant(4, MVT::i32));
18527 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18528 Ld->getPointerInfo(),
18529 Ld->isVolatile(), Ld->isNonTemporal(),
18530 Ld->isInvariant(), Ld->getAlignment());
18531 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18532 Ld->getPointerInfo().getWithOffset(4),
18533 Ld->isVolatile(), Ld->isNonTemporal(),
18535 MinAlign(Ld->getAlignment(), 4));
18537 SDValue NewChain = LoLd.getValue(1);
18538 if (TokenFactorIndex != -1) {
18539 Ops.push_back(LoLd);
18540 Ops.push_back(HiLd);
18541 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18545 LoAddr = St->getBasePtr();
18546 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18547 DAG.getConstant(4, MVT::i32));
18549 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18550 St->getPointerInfo(),
18551 St->isVolatile(), St->isNonTemporal(),
18552 St->getAlignment());
18553 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18554 St->getPointerInfo().getWithOffset(4),
18556 St->isNonTemporal(),
18557 MinAlign(St->getAlignment(), 4));
18558 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18563 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18564 /// and return the operands for the horizontal operation in LHS and RHS. A
18565 /// horizontal operation performs the binary operation on successive elements
18566 /// of its first operand, then on successive elements of its second operand,
18567 /// returning the resulting values in a vector. For example, if
18568 /// A = < float a0, float a1, float a2, float a3 >
18570 /// B = < float b0, float b1, float b2, float b3 >
18571 /// then the result of doing a horizontal operation on A and B is
18572 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18573 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18574 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18575 /// set to A, RHS to B, and the routine returns 'true'.
18576 /// Note that the binary operation should have the property that if one of the
18577 /// operands is UNDEF then the result is UNDEF.
18578 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18579 // Look for the following pattern: if
18580 // A = < float a0, float a1, float a2, float a3 >
18581 // B = < float b0, float b1, float b2, float b3 >
18583 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18584 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18585 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18586 // which is A horizontal-op B.
18588 // At least one of the operands should be a vector shuffle.
18589 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18590 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18593 MVT VT = LHS.getSimpleValueType();
18595 assert((VT.is128BitVector() || VT.is256BitVector()) &&
18596 "Unsupported vector type for horizontal add/sub");
18598 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18599 // operate independently on 128-bit lanes.
18600 unsigned NumElts = VT.getVectorNumElements();
18601 unsigned NumLanes = VT.getSizeInBits()/128;
18602 unsigned NumLaneElts = NumElts / NumLanes;
18603 assert((NumLaneElts % 2 == 0) &&
18604 "Vector type should have an even number of elements in each lane");
18605 unsigned HalfLaneElts = NumLaneElts/2;
18607 // View LHS in the form
18608 // LHS = VECTOR_SHUFFLE A, B, LMask
18609 // If LHS is not a shuffle then pretend it is the shuffle
18610 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18611 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18614 SmallVector<int, 16> LMask(NumElts);
18615 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18616 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18617 A = LHS.getOperand(0);
18618 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18619 B = LHS.getOperand(1);
18620 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18621 std::copy(Mask.begin(), Mask.end(), LMask.begin());
18623 if (LHS.getOpcode() != ISD::UNDEF)
18625 for (unsigned i = 0; i != NumElts; ++i)
18629 // Likewise, view RHS in the form
18630 // RHS = VECTOR_SHUFFLE C, D, RMask
18632 SmallVector<int, 16> RMask(NumElts);
18633 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18634 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18635 C = RHS.getOperand(0);
18636 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18637 D = RHS.getOperand(1);
18638 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18639 std::copy(Mask.begin(), Mask.end(), RMask.begin());
18641 if (RHS.getOpcode() != ISD::UNDEF)
18643 for (unsigned i = 0; i != NumElts; ++i)
18647 // Check that the shuffles are both shuffling the same vectors.
18648 if (!(A == C && B == D) && !(A == D && B == C))
18651 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18652 if (!A.getNode() && !B.getNode())
18655 // If A and B occur in reverse order in RHS, then "swap" them (which means
18656 // rewriting the mask).
18658 CommuteVectorShuffleMask(RMask, NumElts);
18660 // At this point LHS and RHS are equivalent to
18661 // LHS = VECTOR_SHUFFLE A, B, LMask
18662 // RHS = VECTOR_SHUFFLE A, B, RMask
18663 // Check that the masks correspond to performing a horizontal operation.
18664 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18665 for (unsigned i = 0; i != NumLaneElts; ++i) {
18666 int LIdx = LMask[i+l], RIdx = RMask[i+l];
18668 // Ignore any UNDEF components.
18669 if (LIdx < 0 || RIdx < 0 ||
18670 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18671 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18674 // Check that successive elements are being operated on. If not, this is
18675 // not a horizontal operation.
18676 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18677 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18678 if (!(LIdx == Index && RIdx == Index + 1) &&
18679 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18684 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18685 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18689 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18690 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18691 const X86Subtarget *Subtarget) {
18692 EVT VT = N->getValueType(0);
18693 SDValue LHS = N->getOperand(0);
18694 SDValue RHS = N->getOperand(1);
18696 // Try to synthesize horizontal adds from adds of shuffles.
18697 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18698 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18699 isHorizontalBinOp(LHS, RHS, true))
18700 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18704 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18705 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18706 const X86Subtarget *Subtarget) {
18707 EVT VT = N->getValueType(0);
18708 SDValue LHS = N->getOperand(0);
18709 SDValue RHS = N->getOperand(1);
18711 // Try to synthesize horizontal subs from subs of shuffles.
18712 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18713 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18714 isHorizontalBinOp(LHS, RHS, false))
18715 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18719 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18720 /// X86ISD::FXOR nodes.
18721 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18722 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18723 // F[X]OR(0.0, x) -> x
18724 // F[X]OR(x, 0.0) -> x
18725 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18726 if (C->getValueAPF().isPosZero())
18727 return N->getOperand(1);
18728 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18729 if (C->getValueAPF().isPosZero())
18730 return N->getOperand(0);
18734 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18735 /// X86ISD::FMAX nodes.
18736 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18737 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18739 // Only perform optimizations if UnsafeMath is used.
18740 if (!DAG.getTarget().Options.UnsafeFPMath)
18743 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18744 // into FMINC and FMAXC, which are Commutative operations.
18745 unsigned NewOp = 0;
18746 switch (N->getOpcode()) {
18747 default: llvm_unreachable("unknown opcode");
18748 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
18749 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
18752 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18753 N->getOperand(0), N->getOperand(1));
18756 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18757 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18758 // FAND(0.0, x) -> 0.0
18759 // FAND(x, 0.0) -> 0.0
18760 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18761 if (C->getValueAPF().isPosZero())
18762 return N->getOperand(0);
18763 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18764 if (C->getValueAPF().isPosZero())
18765 return N->getOperand(1);
18769 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18770 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18771 // FANDN(x, 0.0) -> 0.0
18772 // FANDN(0.0, x) -> x
18773 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18774 if (C->getValueAPF().isPosZero())
18775 return N->getOperand(1);
18776 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18777 if (C->getValueAPF().isPosZero())
18778 return N->getOperand(1);
18782 static SDValue PerformBTCombine(SDNode *N,
18784 TargetLowering::DAGCombinerInfo &DCI) {
18785 // BT ignores high bits in the bit index operand.
18786 SDValue Op1 = N->getOperand(1);
18787 if (Op1.hasOneUse()) {
18788 unsigned BitWidth = Op1.getValueSizeInBits();
18789 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18790 APInt KnownZero, KnownOne;
18791 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18792 !DCI.isBeforeLegalizeOps());
18793 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18794 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18795 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18796 DCI.CommitTargetLoweringOpt(TLO);
18801 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18802 SDValue Op = N->getOperand(0);
18803 if (Op.getOpcode() == ISD::BITCAST)
18804 Op = Op.getOperand(0);
18805 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18806 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18807 VT.getVectorElementType().getSizeInBits() ==
18808 OpVT.getVectorElementType().getSizeInBits()) {
18809 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18814 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18815 const X86Subtarget *Subtarget) {
18816 EVT VT = N->getValueType(0);
18817 if (!VT.isVector())
18820 SDValue N0 = N->getOperand(0);
18821 SDValue N1 = N->getOperand(1);
18822 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18825 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18826 // both SSE and AVX2 since there is no sign-extended shift right
18827 // operation on a vector with 64-bit elements.
18828 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18829 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18830 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18831 N0.getOpcode() == ISD::SIGN_EXTEND)) {
18832 SDValue N00 = N0.getOperand(0);
18834 // EXTLOAD has a better solution on AVX2,
18835 // it may be replaced with X86ISD::VSEXT node.
18836 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18837 if (!ISD::isNormalLoad(N00.getNode()))
18840 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18841 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18843 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18849 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18850 TargetLowering::DAGCombinerInfo &DCI,
18851 const X86Subtarget *Subtarget) {
18852 if (!DCI.isBeforeLegalizeOps())
18855 if (!Subtarget->hasFp256())
18858 EVT VT = N->getValueType(0);
18859 if (VT.isVector() && VT.getSizeInBits() == 256) {
18860 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18868 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18869 const X86Subtarget* Subtarget) {
18871 EVT VT = N->getValueType(0);
18873 // Let legalize expand this if it isn't a legal type yet.
18874 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18877 EVT ScalarVT = VT.getScalarType();
18878 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18879 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18882 SDValue A = N->getOperand(0);
18883 SDValue B = N->getOperand(1);
18884 SDValue C = N->getOperand(2);
18886 bool NegA = (A.getOpcode() == ISD::FNEG);
18887 bool NegB = (B.getOpcode() == ISD::FNEG);
18888 bool NegC = (C.getOpcode() == ISD::FNEG);
18890 // Negative multiplication when NegA xor NegB
18891 bool NegMul = (NegA != NegB);
18893 A = A.getOperand(0);
18895 B = B.getOperand(0);
18897 C = C.getOperand(0);
18901 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18903 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18905 return DAG.getNode(Opcode, dl, VT, A, B, C);
18908 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18909 TargetLowering::DAGCombinerInfo &DCI,
18910 const X86Subtarget *Subtarget) {
18911 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
18912 // (and (i32 x86isd::setcc_carry), 1)
18913 // This eliminates the zext. This transformation is necessary because
18914 // ISD::SETCC is always legalized to i8.
18916 SDValue N0 = N->getOperand(0);
18917 EVT VT = N->getValueType(0);
18919 if (N0.getOpcode() == ISD::AND &&
18921 N0.getOperand(0).hasOneUse()) {
18922 SDValue N00 = N0.getOperand(0);
18923 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18924 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18925 if (!C || C->getZExtValue() != 1)
18927 return DAG.getNode(ISD::AND, dl, VT,
18928 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18929 N00.getOperand(0), N00.getOperand(1)),
18930 DAG.getConstant(1, VT));
18934 if (VT.is256BitVector()) {
18935 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18943 // Optimize x == -y --> x+y == 0
18944 // x != -y --> x+y != 0
18945 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18946 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18947 SDValue LHS = N->getOperand(0);
18948 SDValue RHS = N->getOperand(1);
18950 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18951 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18952 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18953 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18954 LHS.getValueType(), RHS, LHS.getOperand(1));
18955 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18956 addV, DAG.getConstant(0, addV.getValueType()), CC);
18958 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18959 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18960 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18961 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18962 RHS.getValueType(), LHS, RHS.getOperand(1));
18963 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18964 addV, DAG.getConstant(0, addV.getValueType()), CC);
18969 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18970 // as "sbb reg,reg", since it can be extended without zext and produces
18971 // an all-ones bit which is more useful than 0/1 in some cases.
18972 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18973 return DAG.getNode(ISD::AND, DL, MVT::i8,
18974 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18975 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18976 DAG.getConstant(1, MVT::i8));
18979 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18980 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18981 TargetLowering::DAGCombinerInfo &DCI,
18982 const X86Subtarget *Subtarget) {
18984 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18985 SDValue EFLAGS = N->getOperand(1);
18987 if (CC == X86::COND_A) {
18988 // Try to convert COND_A into COND_B in an attempt to facilitate
18989 // materializing "setb reg".
18991 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18992 // cannot take an immediate as its first operand.
18994 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18995 EFLAGS.getValueType().isInteger() &&
18996 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18997 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18998 EFLAGS.getNode()->getVTList(),
18999 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19000 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19001 return MaterializeSETB(DL, NewEFLAGS, DAG);
19005 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19006 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19008 if (CC == X86::COND_B)
19009 return MaterializeSETB(DL, EFLAGS, DAG);
19013 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19014 if (Flags.getNode()) {
19015 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19016 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19022 // Optimize branch condition evaluation.
19024 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19025 TargetLowering::DAGCombinerInfo &DCI,
19026 const X86Subtarget *Subtarget) {
19028 SDValue Chain = N->getOperand(0);
19029 SDValue Dest = N->getOperand(1);
19030 SDValue EFLAGS = N->getOperand(3);
19031 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19035 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19036 if (Flags.getNode()) {
19037 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19038 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19045 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19046 const X86TargetLowering *XTLI) {
19047 SDValue Op0 = N->getOperand(0);
19048 EVT InVT = Op0->getValueType(0);
19050 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19051 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19053 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19054 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19055 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19058 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19059 // a 32-bit target where SSE doesn't support i64->FP operations.
19060 if (Op0.getOpcode() == ISD::LOAD) {
19061 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19062 EVT VT = Ld->getValueType(0);
19063 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19064 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19065 !XTLI->getSubtarget()->is64Bit() &&
19067 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19068 Ld->getChain(), Op0, DAG);
19069 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19076 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19077 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19078 X86TargetLowering::DAGCombinerInfo &DCI) {
19079 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19080 // the result is either zero or one (depending on the input carry bit).
19081 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19082 if (X86::isZeroNode(N->getOperand(0)) &&
19083 X86::isZeroNode(N->getOperand(1)) &&
19084 // We don't have a good way to replace an EFLAGS use, so only do this when
19086 SDValue(N, 1).use_empty()) {
19088 EVT VT = N->getValueType(0);
19089 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19090 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19091 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19092 DAG.getConstant(X86::COND_B,MVT::i8),
19094 DAG.getConstant(1, VT));
19095 return DCI.CombineTo(N, Res1, CarryOut);
19101 // fold (add Y, (sete X, 0)) -> adc 0, Y
19102 // (add Y, (setne X, 0)) -> sbb -1, Y
19103 // (sub (sete X, 0), Y) -> sbb 0, Y
19104 // (sub (setne X, 0), Y) -> adc -1, Y
19105 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19108 // Look through ZExts.
19109 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19110 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19113 SDValue SetCC = Ext.getOperand(0);
19114 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19117 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19118 if (CC != X86::COND_E && CC != X86::COND_NE)
19121 SDValue Cmp = SetCC.getOperand(1);
19122 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19123 !X86::isZeroNode(Cmp.getOperand(1)) ||
19124 !Cmp.getOperand(0).getValueType().isInteger())
19127 SDValue CmpOp0 = Cmp.getOperand(0);
19128 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19129 DAG.getConstant(1, CmpOp0.getValueType()));
19131 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19132 if (CC == X86::COND_NE)
19133 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19134 DL, OtherVal.getValueType(), OtherVal,
19135 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19136 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19137 DL, OtherVal.getValueType(), OtherVal,
19138 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19141 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19142 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19143 const X86Subtarget *Subtarget) {
19144 EVT VT = N->getValueType(0);
19145 SDValue Op0 = N->getOperand(0);
19146 SDValue Op1 = N->getOperand(1);
19148 // Try to synthesize horizontal adds from adds of shuffles.
19149 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19150 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19151 isHorizontalBinOp(Op0, Op1, true))
19152 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19154 return OptimizeConditionalInDecrement(N, DAG);
19157 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19158 const X86Subtarget *Subtarget) {
19159 SDValue Op0 = N->getOperand(0);
19160 SDValue Op1 = N->getOperand(1);
19162 // X86 can't encode an immediate LHS of a sub. See if we can push the
19163 // negation into a preceding instruction.
19164 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19165 // If the RHS of the sub is a XOR with one use and a constant, invert the
19166 // immediate. Then add one to the LHS of the sub so we can turn
19167 // X-Y -> X+~Y+1, saving one register.
19168 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19169 isa<ConstantSDNode>(Op1.getOperand(1))) {
19170 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19171 EVT VT = Op0.getValueType();
19172 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19174 DAG.getConstant(~XorC, VT));
19175 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19176 DAG.getConstant(C->getAPIntValue()+1, VT));
19180 // Try to synthesize horizontal adds from adds of shuffles.
19181 EVT VT = N->getValueType(0);
19182 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19183 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19184 isHorizontalBinOp(Op0, Op1, true))
19185 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19187 return OptimizeConditionalInDecrement(N, DAG);
19190 /// performVZEXTCombine - Performs build vector combines
19191 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19192 TargetLowering::DAGCombinerInfo &DCI,
19193 const X86Subtarget *Subtarget) {
19194 // (vzext (bitcast (vzext (x)) -> (vzext x)
19195 SDValue In = N->getOperand(0);
19196 while (In.getOpcode() == ISD::BITCAST)
19197 In = In.getOperand(0);
19199 if (In.getOpcode() != X86ISD::VZEXT)
19202 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19206 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19207 DAGCombinerInfo &DCI) const {
19208 SelectionDAG &DAG = DCI.DAG;
19209 switch (N->getOpcode()) {
19211 case ISD::EXTRACT_VECTOR_ELT:
19212 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19214 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19215 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19216 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19217 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19218 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19219 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19222 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19223 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19224 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19225 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19226 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19227 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19228 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19229 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19230 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19232 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19234 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19235 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19236 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19237 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19238 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19239 case ISD::ANY_EXTEND:
19240 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19241 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19242 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19243 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19244 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
19245 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19246 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19247 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19248 case X86ISD::SHUFP: // Handle all target specific shuffles
19249 case X86ISD::PALIGNR:
19250 case X86ISD::UNPCKH:
19251 case X86ISD::UNPCKL:
19252 case X86ISD::MOVHLPS:
19253 case X86ISD::MOVLHPS:
19254 case X86ISD::PSHUFD:
19255 case X86ISD::PSHUFHW:
19256 case X86ISD::PSHUFLW:
19257 case X86ISD::MOVSS:
19258 case X86ISD::MOVSD:
19259 case X86ISD::VPERMILP:
19260 case X86ISD::VPERM2X128:
19261 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19262 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19268 /// isTypeDesirableForOp - Return true if the target has native support for
19269 /// the specified value type and it is 'desirable' to use the type for the
19270 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19271 /// instruction encodings are longer and some i16 instructions are slow.
19272 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19273 if (!isTypeLegal(VT))
19275 if (VT != MVT::i16)
19282 case ISD::SIGN_EXTEND:
19283 case ISD::ZERO_EXTEND:
19284 case ISD::ANY_EXTEND:
19297 /// IsDesirableToPromoteOp - This method query the target whether it is
19298 /// beneficial for dag combiner to promote the specified node. If true, it
19299 /// should return the desired promotion type by reference.
19300 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19301 EVT VT = Op.getValueType();
19302 if (VT != MVT::i16)
19305 bool Promote = false;
19306 bool Commute = false;
19307 switch (Op.getOpcode()) {
19310 LoadSDNode *LD = cast<LoadSDNode>(Op);
19311 // If the non-extending load has a single use and it's not live out, then it
19312 // might be folded.
19313 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19314 Op.hasOneUse()*/) {
19315 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19316 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19317 // The only case where we'd want to promote LOAD (rather then it being
19318 // promoted as an operand is when it's only use is liveout.
19319 if (UI->getOpcode() != ISD::CopyToReg)
19326 case ISD::SIGN_EXTEND:
19327 case ISD::ZERO_EXTEND:
19328 case ISD::ANY_EXTEND:
19333 SDValue N0 = Op.getOperand(0);
19334 // Look out for (store (shl (load), x)).
19335 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19348 SDValue N0 = Op.getOperand(0);
19349 SDValue N1 = Op.getOperand(1);
19350 if (!Commute && MayFoldLoad(N1))
19352 // Avoid disabling potential load folding opportunities.
19353 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19355 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19365 //===----------------------------------------------------------------------===//
19366 // X86 Inline Assembly Support
19367 //===----------------------------------------------------------------------===//
19370 // Helper to match a string separated by whitespace.
19371 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19372 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19374 for (unsigned i = 0, e = args.size(); i != e; ++i) {
19375 StringRef piece(*args[i]);
19376 if (!s.startswith(piece)) // Check if the piece matches.
19379 s = s.substr(piece.size());
19380 StringRef::size_type pos = s.find_first_not_of(" \t");
19381 if (pos == 0) // We matched a prefix.
19389 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19392 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19394 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19395 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19396 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19397 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19399 if (AsmPieces.size() == 3)
19401 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19408 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19409 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19411 std::string AsmStr = IA->getAsmString();
19413 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19414 if (!Ty || Ty->getBitWidth() % 16 != 0)
19417 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19418 SmallVector<StringRef, 4> AsmPieces;
19419 SplitString(AsmStr, AsmPieces, ";\n");
19421 switch (AsmPieces.size()) {
19422 default: return false;
19424 // FIXME: this should verify that we are targeting a 486 or better. If not,
19425 // we will turn this bswap into something that will be lowered to logical
19426 // ops instead of emitting the bswap asm. For now, we don't support 486 or
19427 // lower so don't worry about this.
19429 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19430 matchAsm(AsmPieces[0], "bswapl", "$0") ||
19431 matchAsm(AsmPieces[0], "bswapq", "$0") ||
19432 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19433 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19434 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19435 // No need to check constraints, nothing other than the equivalent of
19436 // "=r,0" would be valid here.
19437 return IntrinsicLowering::LowerToByteSwap(CI);
19440 // rorw $$8, ${0:w} --> llvm.bswap.i16
19441 if (CI->getType()->isIntegerTy(16) &&
19442 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19443 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19444 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19446 const std::string &ConstraintsStr = IA->getConstraintString();
19447 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19448 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19449 if (clobbersFlagRegisters(AsmPieces))
19450 return IntrinsicLowering::LowerToByteSwap(CI);
19454 if (CI->getType()->isIntegerTy(32) &&
19455 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19456 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19457 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19458 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19460 const std::string &ConstraintsStr = IA->getConstraintString();
19461 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19462 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19463 if (clobbersFlagRegisters(AsmPieces))
19464 return IntrinsicLowering::LowerToByteSwap(CI);
19467 if (CI->getType()->isIntegerTy(64)) {
19468 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19469 if (Constraints.size() >= 2 &&
19470 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19471 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19472 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
19473 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19474 matchAsm(AsmPieces[1], "bswap", "%edx") &&
19475 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19476 return IntrinsicLowering::LowerToByteSwap(CI);
19484 /// getConstraintType - Given a constraint letter, return the type of
19485 /// constraint it is for this target.
19486 X86TargetLowering::ConstraintType
19487 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19488 if (Constraint.size() == 1) {
19489 switch (Constraint[0]) {
19500 return C_RegisterClass;
19524 return TargetLowering::getConstraintType(Constraint);
19527 /// Examine constraint type and operand type and determine a weight value.
19528 /// This object must already have been set up with the operand type
19529 /// and the current alternative constraint selected.
19530 TargetLowering::ConstraintWeight
19531 X86TargetLowering::getSingleConstraintMatchWeight(
19532 AsmOperandInfo &info, const char *constraint) const {
19533 ConstraintWeight weight = CW_Invalid;
19534 Value *CallOperandVal = info.CallOperandVal;
19535 // If we don't have a value, we can't do a match,
19536 // but allow it at the lowest weight.
19537 if (CallOperandVal == NULL)
19539 Type *type = CallOperandVal->getType();
19540 // Look at the constraint type.
19541 switch (*constraint) {
19543 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19554 if (CallOperandVal->getType()->isIntegerTy())
19555 weight = CW_SpecificReg;
19560 if (type->isFloatingPointTy())
19561 weight = CW_SpecificReg;
19564 if (type->isX86_MMXTy() && Subtarget->hasMMX())
19565 weight = CW_SpecificReg;
19569 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19570 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19571 weight = CW_Register;
19574 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19575 if (C->getZExtValue() <= 31)
19576 weight = CW_Constant;
19580 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19581 if (C->getZExtValue() <= 63)
19582 weight = CW_Constant;
19586 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19587 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19588 weight = CW_Constant;
19592 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19593 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19594 weight = CW_Constant;
19598 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19599 if (C->getZExtValue() <= 3)
19600 weight = CW_Constant;
19604 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19605 if (C->getZExtValue() <= 0xff)
19606 weight = CW_Constant;
19611 if (dyn_cast<ConstantFP>(CallOperandVal)) {
19612 weight = CW_Constant;
19616 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19617 if ((C->getSExtValue() >= -0x80000000LL) &&
19618 (C->getSExtValue() <= 0x7fffffffLL))
19619 weight = CW_Constant;
19623 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19624 if (C->getZExtValue() <= 0xffffffff)
19625 weight = CW_Constant;
19632 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19633 /// with another that has more specific requirements based on the type of the
19634 /// corresponding operand.
19635 const char *X86TargetLowering::
19636 LowerXConstraint(EVT ConstraintVT) const {
19637 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19638 // 'f' like normal targets.
19639 if (ConstraintVT.isFloatingPoint()) {
19640 if (Subtarget->hasSSE2())
19642 if (Subtarget->hasSSE1())
19646 return TargetLowering::LowerXConstraint(ConstraintVT);
19649 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19650 /// vector. If it is invalid, don't add anything to Ops.
19651 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19652 std::string &Constraint,
19653 std::vector<SDValue>&Ops,
19654 SelectionDAG &DAG) const {
19655 SDValue Result(0, 0);
19657 // Only support length 1 constraints for now.
19658 if (Constraint.length() > 1) return;
19660 char ConstraintLetter = Constraint[0];
19661 switch (ConstraintLetter) {
19664 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19665 if (C->getZExtValue() <= 31) {
19666 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19672 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19673 if (C->getZExtValue() <= 63) {
19674 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19680 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19681 if (isInt<8>(C->getSExtValue())) {
19682 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19688 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19689 if (C->getZExtValue() <= 255) {
19690 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19696 // 32-bit signed value
19697 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19698 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19699 C->getSExtValue())) {
19700 // Widen to 64 bits here to get it sign extended.
19701 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
19704 // FIXME gcc accepts some relocatable values here too, but only in certain
19705 // memory models; it's complicated.
19710 // 32-bit unsigned value
19711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19712 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19713 C->getZExtValue())) {
19714 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19718 // FIXME gcc accepts some relocatable values here too, but only in certain
19719 // memory models; it's complicated.
19723 // Literal immediates are always ok.
19724 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19725 // Widen to 64 bits here to get it sign extended.
19726 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19730 // In any sort of PIC mode addresses need to be computed at runtime by
19731 // adding in a register or some sort of table lookup. These can't
19732 // be used as immediates.
19733 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19736 // If we are in non-pic codegen mode, we allow the address of a global (with
19737 // an optional displacement) to be used with 'i'.
19738 GlobalAddressSDNode *GA = 0;
19739 int64_t Offset = 0;
19741 // Match either (GA), (GA+C), (GA+C1+C2), etc.
19743 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19744 Offset += GA->getOffset();
19746 } else if (Op.getOpcode() == ISD::ADD) {
19747 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19748 Offset += C->getZExtValue();
19749 Op = Op.getOperand(0);
19752 } else if (Op.getOpcode() == ISD::SUB) {
19753 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19754 Offset += -C->getZExtValue();
19755 Op = Op.getOperand(0);
19760 // Otherwise, this isn't something we can handle, reject it.
19764 const GlobalValue *GV = GA->getGlobal();
19765 // If we require an extra load to get this address, as in PIC mode, we
19766 // can't accept it.
19767 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19768 getTargetMachine())))
19771 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19772 GA->getValueType(0), Offset);
19777 if (Result.getNode()) {
19778 Ops.push_back(Result);
19781 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19784 std::pair<unsigned, const TargetRegisterClass*>
19785 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19787 // First, see if this is a constraint that directly corresponds to an LLVM
19789 if (Constraint.size() == 1) {
19790 // GCC Constraint Letters
19791 switch (Constraint[0]) {
19793 // TODO: Slight differences here in allocation order and leaving
19794 // RIP in the class. Do they matter any more here than they do
19795 // in the normal allocation?
19796 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19797 if (Subtarget->is64Bit()) {
19798 if (VT == MVT::i32 || VT == MVT::f32)
19799 return std::make_pair(0U, &X86::GR32RegClass);
19800 if (VT == MVT::i16)
19801 return std::make_pair(0U, &X86::GR16RegClass);
19802 if (VT == MVT::i8 || VT == MVT::i1)
19803 return std::make_pair(0U, &X86::GR8RegClass);
19804 if (VT == MVT::i64 || VT == MVT::f64)
19805 return std::make_pair(0U, &X86::GR64RegClass);
19808 // 32-bit fallthrough
19809 case 'Q': // Q_REGS
19810 if (VT == MVT::i32 || VT == MVT::f32)
19811 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19812 if (VT == MVT::i16)
19813 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19814 if (VT == MVT::i8 || VT == MVT::i1)
19815 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19816 if (VT == MVT::i64)
19817 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19819 case 'r': // GENERAL_REGS
19820 case 'l': // INDEX_REGS
19821 if (VT == MVT::i8 || VT == MVT::i1)
19822 return std::make_pair(0U, &X86::GR8RegClass);
19823 if (VT == MVT::i16)
19824 return std::make_pair(0U, &X86::GR16RegClass);
19825 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19826 return std::make_pair(0U, &X86::GR32RegClass);
19827 return std::make_pair(0U, &X86::GR64RegClass);
19828 case 'R': // LEGACY_REGS
19829 if (VT == MVT::i8 || VT == MVT::i1)
19830 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19831 if (VT == MVT::i16)
19832 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19833 if (VT == MVT::i32 || !Subtarget->is64Bit())
19834 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19835 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19836 case 'f': // FP Stack registers.
19837 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19838 // value to the correct fpstack register class.
19839 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19840 return std::make_pair(0U, &X86::RFP32RegClass);
19841 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19842 return std::make_pair(0U, &X86::RFP64RegClass);
19843 return std::make_pair(0U, &X86::RFP80RegClass);
19844 case 'y': // MMX_REGS if MMX allowed.
19845 if (!Subtarget->hasMMX()) break;
19846 return std::make_pair(0U, &X86::VR64RegClass);
19847 case 'Y': // SSE_REGS if SSE2 allowed
19848 if (!Subtarget->hasSSE2()) break;
19850 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19851 if (!Subtarget->hasSSE1()) break;
19853 switch (VT.SimpleTy) {
19855 // Scalar SSE types.
19858 return std::make_pair(0U, &X86::FR32RegClass);
19861 return std::make_pair(0U, &X86::FR64RegClass);
19869 return std::make_pair(0U, &X86::VR128RegClass);
19877 return std::make_pair(0U, &X86::VR256RegClass);
19882 return std::make_pair(0U, &X86::VR512RegClass);
19888 // Use the default implementation in TargetLowering to convert the register
19889 // constraint into a member of a register class.
19890 std::pair<unsigned, const TargetRegisterClass*> Res;
19891 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19893 // Not found as a standard register?
19894 if (Res.second == 0) {
19895 // Map st(0) -> st(7) -> ST0
19896 if (Constraint.size() == 7 && Constraint[0] == '{' &&
19897 tolower(Constraint[1]) == 's' &&
19898 tolower(Constraint[2]) == 't' &&
19899 Constraint[3] == '(' &&
19900 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19901 Constraint[5] == ')' &&
19902 Constraint[6] == '}') {
19904 Res.first = X86::ST0+Constraint[4]-'0';
19905 Res.second = &X86::RFP80RegClass;
19909 // GCC allows "st(0)" to be called just plain "st".
19910 if (StringRef("{st}").equals_lower(Constraint)) {
19911 Res.first = X86::ST0;
19912 Res.second = &X86::RFP80RegClass;
19917 if (StringRef("{flags}").equals_lower(Constraint)) {
19918 Res.first = X86::EFLAGS;
19919 Res.second = &X86::CCRRegClass;
19923 // 'A' means EAX + EDX.
19924 if (Constraint == "A") {
19925 Res.first = X86::EAX;
19926 Res.second = &X86::GR32_ADRegClass;
19932 // Otherwise, check to see if this is a register class of the wrong value
19933 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19934 // turn into {ax},{dx}.
19935 if (Res.second->hasType(VT))
19936 return Res; // Correct type already, nothing to do.
19938 // All of the single-register GCC register classes map their values onto
19939 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
19940 // really want an 8-bit or 32-bit register, map to the appropriate register
19941 // class and return the appropriate register.
19942 if (Res.second == &X86::GR16RegClass) {
19943 if (VT == MVT::i8 || VT == MVT::i1) {
19944 unsigned DestReg = 0;
19945 switch (Res.first) {
19947 case X86::AX: DestReg = X86::AL; break;
19948 case X86::DX: DestReg = X86::DL; break;
19949 case X86::CX: DestReg = X86::CL; break;
19950 case X86::BX: DestReg = X86::BL; break;
19953 Res.first = DestReg;
19954 Res.second = &X86::GR8RegClass;
19956 } else if (VT == MVT::i32 || VT == MVT::f32) {
19957 unsigned DestReg = 0;
19958 switch (Res.first) {
19960 case X86::AX: DestReg = X86::EAX; break;
19961 case X86::DX: DestReg = X86::EDX; break;
19962 case X86::CX: DestReg = X86::ECX; break;
19963 case X86::BX: DestReg = X86::EBX; break;
19964 case X86::SI: DestReg = X86::ESI; break;
19965 case X86::DI: DestReg = X86::EDI; break;
19966 case X86::BP: DestReg = X86::EBP; break;
19967 case X86::SP: DestReg = X86::ESP; break;
19970 Res.first = DestReg;
19971 Res.second = &X86::GR32RegClass;
19973 } else if (VT == MVT::i64 || VT == MVT::f64) {
19974 unsigned DestReg = 0;
19975 switch (Res.first) {
19977 case X86::AX: DestReg = X86::RAX; break;
19978 case X86::DX: DestReg = X86::RDX; break;
19979 case X86::CX: DestReg = X86::RCX; break;
19980 case X86::BX: DestReg = X86::RBX; break;
19981 case X86::SI: DestReg = X86::RSI; break;
19982 case X86::DI: DestReg = X86::RDI; break;
19983 case X86::BP: DestReg = X86::RBP; break;
19984 case X86::SP: DestReg = X86::RSP; break;
19987 Res.first = DestReg;
19988 Res.second = &X86::GR64RegClass;
19991 } else if (Res.second == &X86::FR32RegClass ||
19992 Res.second == &X86::FR64RegClass ||
19993 Res.second == &X86::VR128RegClass ||
19994 Res.second == &X86::VR256RegClass ||
19995 Res.second == &X86::FR32XRegClass ||
19996 Res.second == &X86::FR64XRegClass ||
19997 Res.second == &X86::VR128XRegClass ||
19998 Res.second == &X86::VR256XRegClass ||
19999 Res.second == &X86::VR512RegClass) {
20000 // Handle references to XMM physical registers that got mapped into the
20001 // wrong class. This can happen with constraints like {xmm0} where the
20002 // target independent register mapper will just pick the first match it can
20003 // find, ignoring the required type.
20005 if (VT == MVT::f32 || VT == MVT::i32)
20006 Res.second = &X86::FR32RegClass;
20007 else if (VT == MVT::f64 || VT == MVT::i64)
20008 Res.second = &X86::FR64RegClass;
20009 else if (X86::VR128RegClass.hasType(VT))
20010 Res.second = &X86::VR128RegClass;
20011 else if (X86::VR256RegClass.hasType(VT))
20012 Res.second = &X86::VR256RegClass;
20013 else if (X86::VR512RegClass.hasType(VT))
20014 Res.second = &X86::VR512RegClass;