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 "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62 SelectionDAG &DAG, SDLoc dl,
63 unsigned vectorWidth) {
64 assert((vectorWidth == 128 || vectorWidth == 256) &&
65 "Unsupported vector width");
66 EVT VT = Vec.getValueType();
67 EVT ElVT = VT.getVectorElementType();
68 unsigned Factor = VT.getSizeInBits()/vectorWidth;
69 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70 VT.getVectorNumElements()/Factor);
72 // Extract from UNDEF is UNDEF.
73 if (Vec.getOpcode() == ISD::UNDEF)
74 return DAG.getUNDEF(ResultVT);
76 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
77 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79 // This is the index of the first element of the vectorWidth-bit chunk
81 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84 // If the input is a buildvector just emit a smaller one.
85 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103 SelectionDAG &DAG, SDLoc dl) {
104 assert((Vec.getValueType().is256BitVector() ||
105 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111 SelectionDAG &DAG, SDLoc dl) {
112 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117 unsigned IdxVal, SelectionDAG &DAG,
118 SDLoc dl, unsigned vectorWidth) {
119 assert((vectorWidth == 128 || vectorWidth == 256) &&
120 "Unsupported vector width");
121 // Inserting UNDEF is Result
122 if (Vec.getOpcode() == ISD::UNDEF)
124 EVT VT = Vec.getValueType();
125 EVT ElVT = VT.getVectorElementType();
126 EVT ResultVT = Result.getValueType();
128 // Insert the relevant vectorWidth bits.
129 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131 // This is the index of the first element of the vectorWidth-bit chunk
133 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
136 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
140 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference. Idx is an index in the 128 bits
144 /// we want. It need not be aligned to a 128-bit bounday. That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147 unsigned IdxVal, SelectionDAG &DAG,
149 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154 unsigned IdxVal, SelectionDAG &DAG,
156 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165 unsigned NumElems, SelectionDAG &DAG,
167 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172 unsigned NumElems, SelectionDAG &DAG,
174 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180 bool is64Bit = Subtarget->is64Bit();
182 if (Subtarget->isTargetEnvMacho()) {
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
188 if (Subtarget->isTargetLinux())
189 return new X86LinuxTargetObjectFile();
190 if (Subtarget->isTargetELF())
191 return new TargetLoweringObjectFileELF();
192 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
193 return new TargetLoweringObjectFileCOFF();
194 llvm_unreachable("unknown subtarget type");
197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
198 : TargetLowering(TM, createTLOF(TM)) {
199 Subtarget = &TM.getSubtarget<X86Subtarget>();
200 X86ScalarSSEf64 = Subtarget->hasSSE2();
201 X86ScalarSSEf32 = Subtarget->hasSSE1();
202 TD = getDataLayout();
204 resetOperationActions();
207 void X86TargetLowering::resetOperationActions() {
208 const TargetMachine &TM = getTargetMachine();
209 static bool FirstTimeThrough = true;
211 // If none of the target options have changed, then we don't need to reset the
212 // operation actions.
213 if (!FirstTimeThrough && TO == TM.Options) return;
215 if (!FirstTimeThrough) {
216 // Reinitialize the actions.
218 FirstTimeThrough = false;
223 // Set up the TargetLowering object.
224 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
226 // X86 is weird, it always uses i8 for shift amounts and setcc results.
227 setBooleanContents(ZeroOrOneBooleanContent);
228 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
229 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231 // For 64-bit since we have so many registers use the ILP scheduler, for
232 // 32-bit code use the register pressure specific scheduling.
233 // For Atom, always use ILP scheduling.
234 if (Subtarget->isAtom())
235 setSchedulingPreference(Sched::ILP);
236 else if (Subtarget->is64Bit())
237 setSchedulingPreference(Sched::ILP);
239 setSchedulingPreference(Sched::RegPressure);
240 const X86RegisterInfo *RegInfo =
241 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
242 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
244 // Bypass expensive divides on Atom when compiling with O2
245 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
246 addBypassSlowDiv(32, 8);
247 if (Subtarget->is64Bit())
248 addBypassSlowDiv(64, 16);
251 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
252 // Setup Windows compiler runtime calls.
253 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
254 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
255 setLibcallName(RTLIB::SREM_I64, "_allrem");
256 setLibcallName(RTLIB::UREM_I64, "_aullrem");
257 setLibcallName(RTLIB::MUL_I64, "_allmul");
258 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
259 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
260 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
264 // The _ftol2 runtime function has an unusual calling conv, which
265 // is modeled by a special pseudo-instruction.
266 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
267 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
268 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
269 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
272 if (Subtarget->isTargetDarwin()) {
273 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
274 setUseUnderscoreSetJmp(false);
275 setUseUnderscoreLongJmp(false);
276 } else if (Subtarget->isTargetMingw()) {
277 // MS runtime is weird: it exports _setjmp, but longjmp!
278 setUseUnderscoreSetJmp(true);
279 setUseUnderscoreLongJmp(false);
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(true);
285 // Set up the register classes.
286 addRegisterClass(MVT::i8, &X86::GR8RegClass);
287 addRegisterClass(MVT::i16, &X86::GR16RegClass);
288 addRegisterClass(MVT::i32, &X86::GR32RegClass);
289 if (Subtarget->is64Bit())
290 addRegisterClass(MVT::i64, &X86::GR64RegClass);
292 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
294 // We don't accept any truncstore of integer registers.
295 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
296 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
297 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
298 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
302 // SETOEQ and SETUNE require checking two conditions.
303 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
304 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
305 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
306 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
310 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
312 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
313 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
314 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
316 if (Subtarget->is64Bit()) {
317 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
319 } else if (!TM.Options.UseSoftFloat) {
320 // We have an algorithm for SSE2->double, and we turn this into a
321 // 64-bit FILD followed by conditional FADD for other targets.
322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
323 // We have an algorithm for SSE2, and we turn this into a 64-bit
324 // FILD for other targets.
325 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
328 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
330 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
331 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
333 if (!TM.Options.UseSoftFloat) {
334 // SSE has no i16 to fp conversion, only i32
335 if (X86ScalarSSEf32) {
336 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
337 // f32 and f64 cases are Legal, f80 case is not
338 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
348 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
349 // are Legal, f80 is custom lowered.
350 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
351 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
353 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
355 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
356 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
358 if (X86ScalarSSEf32) {
359 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
360 // f32 and f64 cases are Legal, f80 case is not
361 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
367 // Handle FP_TO_UINT by promoting the destination to a larger signed
369 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
370 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
371 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
373 if (Subtarget->is64Bit()) {
374 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
376 } else if (!TM.Options.UseSoftFloat) {
377 // Since AVX is a superset of SSE3, only check for SSE here.
378 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
379 // Expand FP_TO_UINT into a select.
380 // FIXME: We would like to use a Custom expander here eventually to do
381 // the optimal thing for SSE vs. the default expansion in the legalizer.
382 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
384 // With SSE3 we can use fisttpll to convert to a signed i64; without
385 // SSE, we're stuck with a fistpll.
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
389 if (isTargetFTOL()) {
390 // Use the _ftol2 runtime function, which has a pseudo-instruction
391 // to handle its weird calling convention.
392 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
395 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
396 if (!X86ScalarSSEf64) {
397 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
398 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
399 if (Subtarget->is64Bit()) {
400 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
401 // Without SSE, i64->f64 goes through memory.
402 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
406 // Scalar integer divide and remainder are lowered to use operations that
407 // produce two results, to match the available instructions. This exposes
408 // the two-result form to trivial CSE, which is able to combine x/y and x%y
409 // into a single instruction.
411 // Scalar integer multiply-high is also lowered to use two-result
412 // operations, to match the available instructions. However, plain multiply
413 // (low) operations are left as Legal, as there are single-result
414 // instructions for this in x86. Using the two-result multiply instructions
415 // when both high and low results are needed must be arranged by dagcombine.
416 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
418 setOperationAction(ISD::MULHS, VT, Expand);
419 setOperationAction(ISD::MULHU, VT, Expand);
420 setOperationAction(ISD::SDIV, VT, Expand);
421 setOperationAction(ISD::UDIV, VT, Expand);
422 setOperationAction(ISD::SREM, VT, Expand);
423 setOperationAction(ISD::UREM, VT, Expand);
425 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
426 setOperationAction(ISD::ADDC, VT, Custom);
427 setOperationAction(ISD::ADDE, VT, Custom);
428 setOperationAction(ISD::SUBC, VT, Custom);
429 setOperationAction(ISD::SUBE, VT, Custom);
432 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
433 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
434 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
435 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
436 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
437 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
438 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
441 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
442 if (Subtarget->is64Bit())
443 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
444 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
447 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
448 setOperationAction(ISD::FREM , MVT::f32 , Expand);
449 setOperationAction(ISD::FREM , MVT::f64 , Expand);
450 setOperationAction(ISD::FREM , MVT::f80 , Expand);
451 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
453 // Promote the i8 variants and force them on up to i32 which has a shorter
455 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
456 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
457 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
459 if (Subtarget->hasBMI()) {
460 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
461 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
462 if (Subtarget->is64Bit())
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
465 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
466 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
467 if (Subtarget->is64Bit())
468 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
471 if (Subtarget->hasLZCNT()) {
472 // When promoting the i8 variants, force them to i32 for a shorter
474 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
475 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
480 if (Subtarget->is64Bit())
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
483 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
484 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
485 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
487 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
489 if (Subtarget->is64Bit()) {
490 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
495 if (Subtarget->hasPOPCNT()) {
496 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
498 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
499 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
500 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
501 if (Subtarget->is64Bit())
502 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
505 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
506 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
508 // These should be promoted to a larger select which is supported.
509 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
510 // X86 wants to expand cmov itself.
511 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
512 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
513 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
514 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
515 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
516 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
517 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
518 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
519 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
520 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
521 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
522 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
523 if (Subtarget->is64Bit()) {
524 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
527 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
528 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
529 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
530 // support continuation, user-level threading, and etc.. As a result, no
531 // other SjLj exception interfaces are implemented and please don't build
532 // your own exception handling based on them.
533 // LLVM/Clang supports zero-cost DWARF exception handling.
534 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
535 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
538 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
539 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
540 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
541 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
542 if (Subtarget->is64Bit())
543 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
544 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
545 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
546 if (Subtarget->is64Bit()) {
547 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
548 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
549 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
550 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
551 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
553 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
554 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
555 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
556 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
557 if (Subtarget->is64Bit()) {
558 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
563 if (Subtarget->hasSSE1())
564 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
566 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
568 // Expand certain atomics
569 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
571 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
572 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
573 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
576 if (!Subtarget->is64Bit()) {
577 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
578 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
579 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
580 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
581 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
591 if (Subtarget->hasCmpxchg16b()) {
592 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
595 // FIXME - use subtarget debug flags
596 if (!Subtarget->isTargetDarwin() &&
597 !Subtarget->isTargetELF() &&
598 !Subtarget->isTargetCygMing()) {
599 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
602 if (Subtarget->is64Bit()) {
603 setExceptionPointerRegister(X86::RAX);
604 setExceptionSelectorRegister(X86::RDX);
606 setExceptionPointerRegister(X86::EAX);
607 setExceptionSelectorRegister(X86::EDX);
609 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
610 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
612 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
613 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
615 setOperationAction(ISD::TRAP, MVT::Other, Legal);
616 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
618 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
619 setOperationAction(ISD::VASTART , MVT::Other, Custom);
620 setOperationAction(ISD::VAEND , MVT::Other, Expand);
621 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
622 // TargetInfo::X86_64ABIBuiltinVaList
623 setOperationAction(ISD::VAARG , MVT::Other, Custom);
624 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
626 // TargetInfo::CharPtrBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Expand);
628 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
631 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
632 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
634 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
635 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
636 MVT::i64 : MVT::i32, Custom);
637 else if (TM.Options.EnableSegmentedStacks)
638 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639 MVT::i64 : MVT::i32, Custom);
641 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642 MVT::i64 : MVT::i32, Expand);
644 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645 // f32 and f64 use SSE.
646 // Set up the FP register classes.
647 addRegisterClass(MVT::f32, &X86::FR32RegClass);
648 addRegisterClass(MVT::f64, &X86::FR64RegClass);
650 // Use ANDPD to simulate FABS.
651 setOperationAction(ISD::FABS , MVT::f64, Custom);
652 setOperationAction(ISD::FABS , MVT::f32, Custom);
654 // Use XORP to simulate FNEG.
655 setOperationAction(ISD::FNEG , MVT::f64, Custom);
656 setOperationAction(ISD::FNEG , MVT::f32, Custom);
658 // Use ANDPD and ORPD to simulate FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
662 // Lower this to FGETSIGNx86 plus an AND.
663 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
666 // We don't support sin/cos/fmod
667 setOperationAction(ISD::FSIN , MVT::f64, Expand);
668 setOperationAction(ISD::FCOS , MVT::f64, Expand);
669 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670 setOperationAction(ISD::FSIN , MVT::f32, Expand);
671 setOperationAction(ISD::FCOS , MVT::f32, Expand);
672 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
674 // Expand FP immediates into loads from the stack, except for the special
676 addLegalFPImmediate(APFloat(+0.0)); // xorpd
677 addLegalFPImmediate(APFloat(+0.0f)); // xorps
678 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679 // Use SSE for f32, x87 for f64.
680 // Set up the FP register classes.
681 addRegisterClass(MVT::f32, &X86::FR32RegClass);
682 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
684 // Use ANDPS to simulate FABS.
685 setOperationAction(ISD::FABS , MVT::f32, Custom);
687 // Use XORP to simulate FNEG.
688 setOperationAction(ISD::FNEG , MVT::f32, Custom);
690 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
692 // Use ANDPS and ORPS to simulate FCOPYSIGN.
693 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
696 // We don't support sin/cos/fmod
697 setOperationAction(ISD::FSIN , MVT::f32, Expand);
698 setOperationAction(ISD::FCOS , MVT::f32, Expand);
699 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
701 // Special cases we handle for FP constants.
702 addLegalFPImmediate(APFloat(+0.0f)); // xorps
703 addLegalFPImmediate(APFloat(+0.0)); // FLD0
704 addLegalFPImmediate(APFloat(+1.0)); // FLD1
705 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
708 if (!TM.Options.UnsafeFPMath) {
709 setOperationAction(ISD::FSIN , MVT::f64, Expand);
710 setOperationAction(ISD::FCOS , MVT::f64, Expand);
711 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
713 } else if (!TM.Options.UseSoftFloat) {
714 // f32 and f64 in x87.
715 // Set up the FP register classes.
716 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
719 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
720 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
721 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
724 if (!TM.Options.UnsafeFPMath) {
725 setOperationAction(ISD::FSIN , MVT::f64, Expand);
726 setOperationAction(ISD::FSIN , MVT::f32, Expand);
727 setOperationAction(ISD::FCOS , MVT::f64, Expand);
728 setOperationAction(ISD::FCOS , MVT::f32, Expand);
729 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
732 addLegalFPImmediate(APFloat(+0.0)); // FLD0
733 addLegalFPImmediate(APFloat(+1.0)); // FLD1
734 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
742 // We don't support FMA.
743 setOperationAction(ISD::FMA, MVT::f64, Expand);
744 setOperationAction(ISD::FMA, MVT::f32, Expand);
746 // Long double always uses X87.
747 if (!TM.Options.UseSoftFloat) {
748 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
750 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
752 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753 addLegalFPImmediate(TmpFlt); // FLD0
755 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
758 APFloat TmpFlt2(+1.0);
759 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
761 addLegalFPImmediate(TmpFlt2); // FLD1
762 TmpFlt2.changeSign();
763 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
766 if (!TM.Options.UnsafeFPMath) {
767 setOperationAction(ISD::FSIN , MVT::f80, Expand);
768 setOperationAction(ISD::FCOS , MVT::f80, Expand);
769 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
772 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
774 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775 setOperationAction(ISD::FRINT, MVT::f80, Expand);
776 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777 setOperationAction(ISD::FMA, MVT::f80, Expand);
780 // Always use a library call for pow.
781 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
782 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
783 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
785 setOperationAction(ISD::FLOG, MVT::f80, Expand);
786 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788 setOperationAction(ISD::FEXP, MVT::f80, Expand);
789 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
791 // First set operation action for all vector types to either promote
792 // (for widening) or expand (for scalarization). Then we will selectively
793 // turn on ones that can be effectively codegen'd.
794 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796 MVT VT = (MVT::SimpleValueType)i;
797 setOperationAction(ISD::ADD , VT, Expand);
798 setOperationAction(ISD::SUB , VT, Expand);
799 setOperationAction(ISD::FADD, VT, Expand);
800 setOperationAction(ISD::FNEG, VT, Expand);
801 setOperationAction(ISD::FSUB, VT, Expand);
802 setOperationAction(ISD::MUL , VT, Expand);
803 setOperationAction(ISD::FMUL, VT, Expand);
804 setOperationAction(ISD::SDIV, VT, Expand);
805 setOperationAction(ISD::UDIV, VT, Expand);
806 setOperationAction(ISD::FDIV, VT, Expand);
807 setOperationAction(ISD::SREM, VT, Expand);
808 setOperationAction(ISD::UREM, VT, Expand);
809 setOperationAction(ISD::LOAD, VT, Expand);
810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815 setOperationAction(ISD::FABS, VT, Expand);
816 setOperationAction(ISD::FSIN, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FCOS, VT, Expand);
819 setOperationAction(ISD::FSINCOS, VT, Expand);
820 setOperationAction(ISD::FREM, VT, Expand);
821 setOperationAction(ISD::FMA, VT, Expand);
822 setOperationAction(ISD::FPOWI, VT, Expand);
823 setOperationAction(ISD::FSQRT, VT, Expand);
824 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825 setOperationAction(ISD::FFLOOR, VT, Expand);
826 setOperationAction(ISD::FCEIL, VT, Expand);
827 setOperationAction(ISD::FTRUNC, VT, Expand);
828 setOperationAction(ISD::FRINT, VT, Expand);
829 setOperationAction(ISD::FNEARBYINT, VT, Expand);
830 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832 setOperationAction(ISD::SDIVREM, VT, Expand);
833 setOperationAction(ISD::UDIVREM, VT, Expand);
834 setOperationAction(ISD::FPOW, VT, Expand);
835 setOperationAction(ISD::CTPOP, VT, Expand);
836 setOperationAction(ISD::CTTZ, VT, Expand);
837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::CTLZ, VT, Expand);
839 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::SHL, VT, Expand);
841 setOperationAction(ISD::SRA, VT, Expand);
842 setOperationAction(ISD::SRL, VT, Expand);
843 setOperationAction(ISD::ROTL, VT, Expand);
844 setOperationAction(ISD::ROTR, VT, Expand);
845 setOperationAction(ISD::BSWAP, VT, Expand);
846 setOperationAction(ISD::SETCC, VT, Expand);
847 setOperationAction(ISD::FLOG, VT, Expand);
848 setOperationAction(ISD::FLOG2, VT, Expand);
849 setOperationAction(ISD::FLOG10, VT, Expand);
850 setOperationAction(ISD::FEXP, VT, Expand);
851 setOperationAction(ISD::FEXP2, VT, Expand);
852 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857 setOperationAction(ISD::TRUNCATE, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861 setOperationAction(ISD::VSELECT, VT, Expand);
862 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864 setTruncStoreAction(VT,
865 (MVT::SimpleValueType)InnerVT, Expand);
866 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872 // with -msoft-float, disable use of MMX as well.
873 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875 // No operations on x86mmx supported, everything uses intrinsics.
878 // MMX-sized vectors (other than x86mmx) are expected to be expanded
879 // into smaller operations.
880 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
881 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
882 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
883 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
884 setOperationAction(ISD::AND, MVT::v8i8, Expand);
885 setOperationAction(ISD::AND, MVT::v4i16, Expand);
886 setOperationAction(ISD::AND, MVT::v2i32, Expand);
887 setOperationAction(ISD::AND, MVT::v1i64, Expand);
888 setOperationAction(ISD::OR, MVT::v8i8, Expand);
889 setOperationAction(ISD::OR, MVT::v4i16, Expand);
890 setOperationAction(ISD::OR, MVT::v2i32, Expand);
891 setOperationAction(ISD::OR, MVT::v1i64, Expand);
892 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
893 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
894 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
895 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
901 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
902 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
903 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
904 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
910 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
914 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
915 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
916 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
917 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
918 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
919 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
920 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
921 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931 // registers cannot be used even for integer operations.
932 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
938 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
939 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
940 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
941 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
942 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
943 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
944 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
945 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
946 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
947 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
948 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
949 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
950 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
951 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
953 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
954 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
956 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
957 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
958 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
959 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
961 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
967 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
968 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
969 MVT VT = (MVT::SimpleValueType)i;
970 // Do not attempt to custom lower non-power-of-2 vectors
971 if (!isPowerOf2_32(VT.getVectorNumElements()))
973 // Do not attempt to custom lower non-128-bit vectors
974 if (!VT.is128BitVector())
976 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
977 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
981 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
982 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
983 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
984 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
986 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
988 if (Subtarget->is64Bit()) {
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
993 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
994 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
995 MVT VT = (MVT::SimpleValueType)i;
997 // Do not attempt to promote non-128-bit vectors
998 if (!VT.is128BitVector())
1001 setOperationAction(ISD::AND, VT, Promote);
1002 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1003 setOperationAction(ISD::OR, VT, Promote);
1004 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1005 setOperationAction(ISD::XOR, VT, Promote);
1006 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1007 setOperationAction(ISD::LOAD, VT, Promote);
1008 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1009 setOperationAction(ISD::SELECT, VT, Promote);
1010 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1013 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1015 // Custom lower v2i64 and v2f64 selects.
1016 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1017 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1018 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1019 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1021 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1022 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1024 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1025 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1026 // As there is no 64-bit GPR available, we need build a special custom
1027 // sequence to convert from v2i32 to v2f32.
1028 if (!Subtarget->is64Bit())
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1031 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1032 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1034 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1037 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1038 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1039 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1040 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1041 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1042 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1043 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1044 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1045 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1046 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1047 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1049 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1050 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1053 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1055 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1057 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1060 // FIXME: Do we need to handle scalar-to-vector here?
1061 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1063 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1069 // i8 and i16 vectors are custom , because the source register and source
1070 // source memory operand types are not the same width. f32 vectors are
1071 // custom since the immediate controlling the insert encodes additional
1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1075 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1076 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1078 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1080 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1081 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1083 // FIXME: these should be Legal but thats only for the case where
1084 // the index is constant. For now custom expand to deal with that.
1085 if (Subtarget->is64Bit()) {
1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1091 if (Subtarget->hasSSE2()) {
1092 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1093 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1095 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1096 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1098 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1099 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1101 // In the customized shift lowering, the legal cases in AVX2 will be
1103 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1104 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1106 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1107 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1109 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1111 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1112 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1115 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1117 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1123 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1124 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1125 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1127 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1138 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1140 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1141 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1151 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1153 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1154 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1156 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1158 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1159 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1161 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1163 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1167 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1169 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1186 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1187 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1189 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1191 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1192 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1201 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1202 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1203 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1205 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1206 setOperationAction(ISD::FMA, MVT::f32, Legal);
1207 setOperationAction(ISD::FMA, MVT::f64, Legal);
1210 if (Subtarget->hasInt256()) {
1211 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1212 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1213 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1214 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1216 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1217 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1218 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1219 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1221 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1222 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1223 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1224 // Don't lower v32i8 because there is no 128-bit byte mul
1226 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1228 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1230 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1231 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1232 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1233 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1235 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1236 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1237 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1238 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1240 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1241 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1242 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1243 // Don't lower v32i8 because there is no 128-bit byte mul
1246 // In the customized shift lowering, the legal cases in AVX2 will be
1248 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1249 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1256 // Custom lower several nodes for 256-bit types.
1257 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1258 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1259 MVT VT = (MVT::SimpleValueType)i;
1261 // Extract subvector is special because the value type
1262 // (result) is 128-bit but the source is 256-bit wide.
1263 if (VT.is128BitVector())
1264 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1266 // Do not attempt to custom lower other non-256-bit vectors
1267 if (!VT.is256BitVector())
1270 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1271 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1272 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1273 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1275 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1276 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1279 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281 MVT VT = (MVT::SimpleValueType)i;
1283 // Do not attempt to promote non-256-bit vectors
1284 if (!VT.is256BitVector())
1287 setOperationAction(ISD::AND, VT, Promote);
1288 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1289 setOperationAction(ISD::OR, VT, Promote);
1290 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1291 setOperationAction(ISD::XOR, VT, Promote);
1292 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1293 setOperationAction(ISD::LOAD, VT, Promote);
1294 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1295 setOperationAction(ISD::SELECT, VT, Promote);
1296 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1301 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1304 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1307 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1309 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1310 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1311 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1312 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1313 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1314 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1316 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1317 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1318 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1319 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1320 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1321 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1323 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1324 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1325 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1326 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1327 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1328 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1329 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1330 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1331 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1334 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1335 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1336 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1337 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1338 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1339 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1340 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1341 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1343 setOperationAction(ISD::TRUNCATE, MVT::i1, Legal);
1344 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1345 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1346 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1347 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1348 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1349 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1350 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1351 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1352 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1353 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1354 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1356 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1357 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1358 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1359 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1360 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1362 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1363 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1365 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1367 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1368 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1369 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1370 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1373 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1374 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1376 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1377 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1379 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1381 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1382 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1384 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1385 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1387 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1388 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1390 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1391 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1392 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1394 // Custom lower several nodes.
1395 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1396 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1397 MVT VT = (MVT::SimpleValueType)i;
1399 // Extract subvector is special because the value type
1400 // (result) is 256/128-bit but the source is 512-bit wide.
1401 if (VT.is128BitVector() || VT.is256BitVector())
1402 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1404 if (VT.getVectorElementType() == MVT::i1)
1405 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1407 // Do not attempt to custom lower other non-512-bit vectors
1408 if (!VT.is512BitVector())
1411 if (VT != MVT::v8i64) {
1412 setOperationAction(ISD::XOR, VT, Promote);
1413 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1414 setOperationAction(ISD::OR, VT, Promote);
1415 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1416 setOperationAction(ISD::AND, VT, Promote);
1417 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1419 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1420 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1421 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1422 setOperationAction(ISD::VSELECT, VT, Legal);
1423 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1424 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1425 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1427 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1428 MVT VT = (MVT::SimpleValueType)i;
1430 // Do not attempt to promote non-256-bit vectors
1431 if (!VT.is512BitVector())
1434 setOperationAction(ISD::LOAD, VT, Promote);
1435 AddPromotedToType (ISD::LOAD, VT, MVT::v8i64);
1436 setOperationAction(ISD::SELECT, VT, Promote);
1437 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1441 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1442 // of this type with custom code.
1443 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1444 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1445 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1449 // We want to custom lower some of our intrinsics.
1450 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1451 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1453 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1454 // handle type legalization for these operations here.
1456 // FIXME: We really should do custom legalization for addition and
1457 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1458 // than generic legalization for 64-bit multiplication-with-overflow, though.
1459 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1460 // Add/Sub/Mul with overflow operations are custom lowered.
1462 setOperationAction(ISD::SADDO, VT, Custom);
1463 setOperationAction(ISD::UADDO, VT, Custom);
1464 setOperationAction(ISD::SSUBO, VT, Custom);
1465 setOperationAction(ISD::USUBO, VT, Custom);
1466 setOperationAction(ISD::SMULO, VT, Custom);
1467 setOperationAction(ISD::UMULO, VT, Custom);
1470 // There are no 8-bit 3-address imul/mul instructions
1471 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1472 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1474 if (!Subtarget->is64Bit()) {
1475 // These libcalls are not available in 32-bit.
1476 setLibcallName(RTLIB::SHL_I128, 0);
1477 setLibcallName(RTLIB::SRL_I128, 0);
1478 setLibcallName(RTLIB::SRA_I128, 0);
1481 // Combine sin / cos into one node or libcall if possible.
1482 if (Subtarget->hasSinCos()) {
1483 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1484 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1485 if (Subtarget->isTargetDarwin()) {
1486 // For MacOSX, we don't want to the normal expansion of a libcall to
1487 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1489 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1490 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1494 // We have target-specific dag combine patterns for the following nodes:
1495 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1496 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1497 setTargetDAGCombine(ISD::VSELECT);
1498 setTargetDAGCombine(ISD::SELECT);
1499 setTargetDAGCombine(ISD::SHL);
1500 setTargetDAGCombine(ISD::SRA);
1501 setTargetDAGCombine(ISD::SRL);
1502 setTargetDAGCombine(ISD::OR);
1503 setTargetDAGCombine(ISD::AND);
1504 setTargetDAGCombine(ISD::ADD);
1505 setTargetDAGCombine(ISD::FADD);
1506 setTargetDAGCombine(ISD::FSUB);
1507 setTargetDAGCombine(ISD::FMA);
1508 setTargetDAGCombine(ISD::SUB);
1509 setTargetDAGCombine(ISD::LOAD);
1510 setTargetDAGCombine(ISD::STORE);
1511 setTargetDAGCombine(ISD::ZERO_EXTEND);
1512 setTargetDAGCombine(ISD::ANY_EXTEND);
1513 setTargetDAGCombine(ISD::SIGN_EXTEND);
1514 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1515 setTargetDAGCombine(ISD::TRUNCATE);
1516 setTargetDAGCombine(ISD::SINT_TO_FP);
1517 setTargetDAGCombine(ISD::SETCC);
1518 if (Subtarget->is64Bit())
1519 setTargetDAGCombine(ISD::MUL);
1520 setTargetDAGCombine(ISD::XOR);
1522 computeRegisterProperties();
1524 // On Darwin, -Os means optimize for size without hurting performance,
1525 // do not reduce the limit.
1526 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1527 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1528 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1529 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1530 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1531 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1532 setPrefLoopAlignment(4); // 2^4 bytes.
1534 // Predictable cmov don't hurt on atom because it's in-order.
1535 PredictableSelectIsExpensive = !Subtarget->isAtom();
1537 setPrefFunctionAlignment(4); // 2^4 bytes.
1540 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1541 if (!VT.isVector()) return MVT::i8;
1542 return VT.changeVectorElementTypeToInteger();
1545 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1546 /// the desired ByVal argument alignment.
1547 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1550 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1551 if (VTy->getBitWidth() == 128)
1553 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1554 unsigned EltAlign = 0;
1555 getMaxByValAlign(ATy->getElementType(), EltAlign);
1556 if (EltAlign > MaxAlign)
1557 MaxAlign = EltAlign;
1558 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1559 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1560 unsigned EltAlign = 0;
1561 getMaxByValAlign(STy->getElementType(i), EltAlign);
1562 if (EltAlign > MaxAlign)
1563 MaxAlign = EltAlign;
1570 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1571 /// function arguments in the caller parameter area. For X86, aggregates
1572 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1573 /// are at 4-byte boundaries.
1574 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1575 if (Subtarget->is64Bit()) {
1576 // Max of 8 and alignment of type.
1577 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1584 if (Subtarget->hasSSE1())
1585 getMaxByValAlign(Ty, Align);
1589 /// getOptimalMemOpType - Returns the target specific optimal type for load
1590 /// and store operations as a result of memset, memcpy, and memmove
1591 /// lowering. If DstAlign is zero that means it's safe to destination
1592 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1593 /// means there isn't a need to check it against alignment requirement,
1594 /// probably because the source does not need to be loaded. If 'IsMemset' is
1595 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1596 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1597 /// source is constant so it does not need to be loaded.
1598 /// It returns EVT::Other if the type should be determined using generic
1599 /// target-independent logic.
1601 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1602 unsigned DstAlign, unsigned SrcAlign,
1603 bool IsMemset, bool ZeroMemset,
1605 MachineFunction &MF) const {
1606 const Function *F = MF.getFunction();
1607 if ((!IsMemset || ZeroMemset) &&
1608 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1609 Attribute::NoImplicitFloat)) {
1611 (Subtarget->isUnalignedMemAccessFast() ||
1612 ((DstAlign == 0 || DstAlign >= 16) &&
1613 (SrcAlign == 0 || SrcAlign >= 16)))) {
1615 if (Subtarget->hasInt256())
1617 if (Subtarget->hasFp256())
1620 if (Subtarget->hasSSE2())
1622 if (Subtarget->hasSSE1())
1624 } else if (!MemcpyStrSrc && Size >= 8 &&
1625 !Subtarget->is64Bit() &&
1626 Subtarget->hasSSE2()) {
1627 // Do not use f64 to lower memcpy if source is string constant. It's
1628 // better to use i32 to avoid the loads.
1632 if (Subtarget->is64Bit() && Size >= 8)
1637 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1639 return X86ScalarSSEf32;
1640 else if (VT == MVT::f64)
1641 return X86ScalarSSEf64;
1646 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1648 *Fast = Subtarget->isUnalignedMemAccessFast();
1652 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1653 /// current function. The returned value is a member of the
1654 /// MachineJumpTableInfo::JTEntryKind enum.
1655 unsigned X86TargetLowering::getJumpTableEncoding() const {
1656 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1658 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1659 Subtarget->isPICStyleGOT())
1660 return MachineJumpTableInfo::EK_Custom32;
1662 // Otherwise, use the normal jump table encoding heuristics.
1663 return TargetLowering::getJumpTableEncoding();
1667 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1668 const MachineBasicBlock *MBB,
1669 unsigned uid,MCContext &Ctx) const{
1670 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1671 Subtarget->isPICStyleGOT());
1672 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1674 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1675 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1678 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1680 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1681 SelectionDAG &DAG) const {
1682 if (!Subtarget->is64Bit())
1683 // This doesn't have SDLoc associated with it, but is not really the
1684 // same as a Register.
1685 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1689 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1690 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1692 const MCExpr *X86TargetLowering::
1693 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1694 MCContext &Ctx) const {
1695 // X86-64 uses RIP relative addressing based on the jump table label.
1696 if (Subtarget->isPICStyleRIPRel())
1697 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1699 // Otherwise, the reference is relative to the PIC base.
1700 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1703 // FIXME: Why this routine is here? Move to RegInfo!
1704 std::pair<const TargetRegisterClass*, uint8_t>
1705 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1706 const TargetRegisterClass *RRC = 0;
1708 switch (VT.SimpleTy) {
1710 return TargetLowering::findRepresentativeClass(VT);
1711 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1712 RRC = Subtarget->is64Bit() ?
1713 (const TargetRegisterClass*)&X86::GR64RegClass :
1714 (const TargetRegisterClass*)&X86::GR32RegClass;
1717 RRC = &X86::VR64RegClass;
1719 case MVT::f32: case MVT::f64:
1720 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1721 case MVT::v4f32: case MVT::v2f64:
1722 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1724 RRC = &X86::VR128RegClass;
1727 return std::make_pair(RRC, Cost);
1730 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1731 unsigned &Offset) const {
1732 if (!Subtarget->isTargetLinux())
1735 if (Subtarget->is64Bit()) {
1736 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1738 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1750 //===----------------------------------------------------------------------===//
1751 // Return Value Calling Convention Implementation
1752 //===----------------------------------------------------------------------===//
1754 #include "X86GenCallingConv.inc"
1757 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1758 MachineFunction &MF, bool isVarArg,
1759 const SmallVectorImpl<ISD::OutputArg> &Outs,
1760 LLVMContext &Context) const {
1761 SmallVector<CCValAssign, 16> RVLocs;
1762 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1764 return CCInfo.CheckReturn(Outs, RetCC_X86);
1768 X86TargetLowering::LowerReturn(SDValue Chain,
1769 CallingConv::ID CallConv, bool isVarArg,
1770 const SmallVectorImpl<ISD::OutputArg> &Outs,
1771 const SmallVectorImpl<SDValue> &OutVals,
1772 SDLoc dl, SelectionDAG &DAG) const {
1773 MachineFunction &MF = DAG.getMachineFunction();
1774 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1776 SmallVector<CCValAssign, 16> RVLocs;
1777 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1778 RVLocs, *DAG.getContext());
1779 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1782 SmallVector<SDValue, 6> RetOps;
1783 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1784 // Operand #1 = Bytes To Pop
1785 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1788 // Copy the result values into the output registers.
1789 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1790 CCValAssign &VA = RVLocs[i];
1791 assert(VA.isRegLoc() && "Can only return in registers!");
1792 SDValue ValToCopy = OutVals[i];
1793 EVT ValVT = ValToCopy.getValueType();
1795 // Promote values to the appropriate types
1796 if (VA.getLocInfo() == CCValAssign::SExt)
1797 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1798 else if (VA.getLocInfo() == CCValAssign::ZExt)
1799 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1800 else if (VA.getLocInfo() == CCValAssign::AExt)
1801 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1802 else if (VA.getLocInfo() == CCValAssign::BCvt)
1803 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1805 // If this is x86-64, and we disabled SSE, we can't return FP values,
1806 // or SSE or MMX vectors.
1807 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1808 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1809 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1810 report_fatal_error("SSE register return with SSE disabled");
1812 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1813 // llvm-gcc has never done it right and no one has noticed, so this
1814 // should be OK for now.
1815 if (ValVT == MVT::f64 &&
1816 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1817 report_fatal_error("SSE2 register return with SSE2 disabled");
1819 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1820 // the RET instruction and handled by the FP Stackifier.
1821 if (VA.getLocReg() == X86::ST0 ||
1822 VA.getLocReg() == X86::ST1) {
1823 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1824 // change the value to the FP stack register class.
1825 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1826 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1827 RetOps.push_back(ValToCopy);
1828 // Don't emit a copytoreg.
1832 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1833 // which is returned in RAX / RDX.
1834 if (Subtarget->is64Bit()) {
1835 if (ValVT == MVT::x86mmx) {
1836 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1837 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1838 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1840 // If we don't have SSE2 available, convert to v4f32 so the generated
1841 // register is legal.
1842 if (!Subtarget->hasSSE2())
1843 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1848 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1849 Flag = Chain.getValue(1);
1850 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1853 // The x86-64 ABIs require that for returning structs by value we copy
1854 // the sret argument into %rax/%eax (depending on ABI) for the return.
1855 // Win32 requires us to put the sret argument to %eax as well.
1856 // We saved the argument into a virtual register in the entry block,
1857 // so now we copy the value out and into %rax/%eax.
1858 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1859 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1860 MachineFunction &MF = DAG.getMachineFunction();
1861 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1862 unsigned Reg = FuncInfo->getSRetReturnReg();
1864 "SRetReturnReg should have been set in LowerFormalArguments().");
1865 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1868 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1869 X86::RAX : X86::EAX;
1870 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1871 Flag = Chain.getValue(1);
1873 // RAX/EAX now acts like a return value.
1874 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1877 RetOps[0] = Chain; // Update chain.
1879 // Add the flag if we have it.
1881 RetOps.push_back(Flag);
1883 return DAG.getNode(X86ISD::RET_FLAG, dl,
1884 MVT::Other, &RetOps[0], RetOps.size());
1887 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1888 if (N->getNumValues() != 1)
1890 if (!N->hasNUsesOfValue(1, 0))
1893 SDValue TCChain = Chain;
1894 SDNode *Copy = *N->use_begin();
1895 if (Copy->getOpcode() == ISD::CopyToReg) {
1896 // If the copy has a glue operand, we conservatively assume it isn't safe to
1897 // perform a tail call.
1898 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1900 TCChain = Copy->getOperand(0);
1901 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1904 bool HasRet = false;
1905 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1907 if (UI->getOpcode() != X86ISD::RET_FLAG)
1920 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1921 ISD::NodeType ExtendKind) const {
1923 // TODO: Is this also valid on 32-bit?
1924 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1925 ReturnMVT = MVT::i8;
1927 ReturnMVT = MVT::i32;
1929 MVT MinVT = getRegisterType(ReturnMVT);
1930 return VT.bitsLT(MinVT) ? MinVT : VT;
1933 /// LowerCallResult - Lower the result values of a call into the
1934 /// appropriate copies out of appropriate physical registers.
1937 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1938 CallingConv::ID CallConv, bool isVarArg,
1939 const SmallVectorImpl<ISD::InputArg> &Ins,
1940 SDLoc dl, SelectionDAG &DAG,
1941 SmallVectorImpl<SDValue> &InVals) const {
1943 // Assign locations to each value returned by this call.
1944 SmallVector<CCValAssign, 16> RVLocs;
1945 bool Is64Bit = Subtarget->is64Bit();
1946 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1947 getTargetMachine(), RVLocs, *DAG.getContext());
1948 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1950 // Copy all of the result registers out of their specified physreg.
1951 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1952 CCValAssign &VA = RVLocs[i];
1953 EVT CopyVT = VA.getValVT();
1955 // If this is x86-64, and we disabled SSE, we can't return FP values
1956 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1957 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1958 report_fatal_error("SSE register return with SSE disabled");
1963 // If this is a call to a function that returns an fp value on the floating
1964 // point stack, we must guarantee the value is popped from the stack, so
1965 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1966 // if the return value is not used. We use the FpPOP_RETVAL instruction
1968 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1969 // If we prefer to use the value in xmm registers, copy it out as f80 and
1970 // use a truncate to move it from fp stack reg to xmm reg.
1971 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1972 SDValue Ops[] = { Chain, InFlag };
1973 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1974 MVT::Other, MVT::Glue, Ops), 1);
1975 Val = Chain.getValue(0);
1977 // Round the f80 to the right size, which also moves it to the appropriate
1979 if (CopyVT != VA.getValVT())
1980 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1981 // This truncation won't change the value.
1982 DAG.getIntPtrConstant(1));
1984 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1985 CopyVT, InFlag).getValue(1);
1986 Val = Chain.getValue(0);
1988 InFlag = Chain.getValue(2);
1989 InVals.push_back(Val);
1995 //===----------------------------------------------------------------------===//
1996 // C & StdCall & Fast Calling Convention implementation
1997 //===----------------------------------------------------------------------===//
1998 // StdCall calling convention seems to be standard for many Windows' API
1999 // routines and around. It differs from C calling convention just a little:
2000 // callee should clean up the stack, not caller. Symbols should be also
2001 // decorated in some fancy way :) It doesn't support any vector arguments.
2002 // For info on fast calling convention see Fast Calling Convention (tail call)
2003 // implementation LowerX86_32FastCCCallTo.
2005 /// CallIsStructReturn - Determines whether a call uses struct return
2007 enum StructReturnType {
2012 static StructReturnType
2013 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2015 return NotStructReturn;
2017 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2018 if (!Flags.isSRet())
2019 return NotStructReturn;
2020 if (Flags.isInReg())
2021 return RegStructReturn;
2022 return StackStructReturn;
2025 /// ArgsAreStructReturn - Determines whether a function uses struct
2026 /// return semantics.
2027 static StructReturnType
2028 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2030 return NotStructReturn;
2032 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2033 if (!Flags.isSRet())
2034 return NotStructReturn;
2035 if (Flags.isInReg())
2036 return RegStructReturn;
2037 return StackStructReturn;
2040 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2041 /// by "Src" to address "Dst" with size and alignment information specified by
2042 /// the specific parameter attribute. The copy will be passed as a byval
2043 /// function parameter.
2045 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2046 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2048 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2050 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2051 /*isVolatile*/false, /*AlwaysInline=*/true,
2052 MachinePointerInfo(), MachinePointerInfo());
2055 /// IsTailCallConvention - Return true if the calling convention is one that
2056 /// supports tail call optimization.
2057 static bool IsTailCallConvention(CallingConv::ID CC) {
2058 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2059 CC == CallingConv::HiPE);
2062 /// \brief Return true if the calling convention is a C calling convention.
2063 static bool IsCCallConvention(CallingConv::ID CC) {
2064 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2065 CC == CallingConv::X86_64_SysV);
2068 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2069 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2073 CallingConv::ID CalleeCC = CS.getCallingConv();
2074 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2080 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2081 /// a tailcall target by changing its ABI.
2082 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2083 bool GuaranteedTailCallOpt) {
2084 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2088 X86TargetLowering::LowerMemArgument(SDValue Chain,
2089 CallingConv::ID CallConv,
2090 const SmallVectorImpl<ISD::InputArg> &Ins,
2091 SDLoc dl, SelectionDAG &DAG,
2092 const CCValAssign &VA,
2093 MachineFrameInfo *MFI,
2095 // Create the nodes corresponding to a load from this parameter slot.
2096 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2097 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2098 getTargetMachine().Options.GuaranteedTailCallOpt);
2099 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2102 // If value is passed by pointer we have address passed instead of the value
2104 if (VA.getLocInfo() == CCValAssign::Indirect)
2105 ValVT = VA.getLocVT();
2107 ValVT = VA.getValVT();
2109 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2110 // changed with more analysis.
2111 // In case of tail call optimization mark all arguments mutable. Since they
2112 // could be overwritten by lowering of arguments in case of a tail call.
2113 if (Flags.isByVal()) {
2114 unsigned Bytes = Flags.getByValSize();
2115 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2116 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2117 return DAG.getFrameIndex(FI, getPointerTy());
2119 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2120 VA.getLocMemOffset(), isImmutable);
2121 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2122 return DAG.getLoad(ValVT, dl, Chain, FIN,
2123 MachinePointerInfo::getFixedStack(FI),
2124 false, false, false, 0);
2129 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2130 CallingConv::ID CallConv,
2132 const SmallVectorImpl<ISD::InputArg> &Ins,
2135 SmallVectorImpl<SDValue> &InVals)
2137 MachineFunction &MF = DAG.getMachineFunction();
2138 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2140 const Function* Fn = MF.getFunction();
2141 if (Fn->hasExternalLinkage() &&
2142 Subtarget->isTargetCygMing() &&
2143 Fn->getName() == "main")
2144 FuncInfo->setForceFramePointer(true);
2146 MachineFrameInfo *MFI = MF.getFrameInfo();
2147 bool Is64Bit = Subtarget->is64Bit();
2148 bool IsWindows = Subtarget->isTargetWindows();
2149 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2151 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2152 "Var args not supported with calling convention fastcc, ghc or hipe");
2154 // Assign locations to all of the incoming arguments.
2155 SmallVector<CCValAssign, 16> ArgLocs;
2156 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2157 ArgLocs, *DAG.getContext());
2159 // Allocate shadow area for Win64
2161 CCInfo.AllocateStack(32, 8);
2163 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2165 unsigned LastVal = ~0U;
2167 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2168 CCValAssign &VA = ArgLocs[i];
2169 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2171 assert(VA.getValNo() != LastVal &&
2172 "Don't support value assigned to multiple locs yet");
2174 LastVal = VA.getValNo();
2176 if (VA.isRegLoc()) {
2177 EVT RegVT = VA.getLocVT();
2178 const TargetRegisterClass *RC;
2179 if (RegVT == MVT::i32)
2180 RC = &X86::GR32RegClass;
2181 else if (Is64Bit && RegVT == MVT::i64)
2182 RC = &X86::GR64RegClass;
2183 else if (RegVT == MVT::f32)
2184 RC = &X86::FR32RegClass;
2185 else if (RegVT == MVT::f64)
2186 RC = &X86::FR64RegClass;
2187 else if (RegVT.is512BitVector())
2188 RC = &X86::VR512RegClass;
2189 else if (RegVT.is256BitVector())
2190 RC = &X86::VR256RegClass;
2191 else if (RegVT.is128BitVector())
2192 RC = &X86::VR128RegClass;
2193 else if (RegVT == MVT::x86mmx)
2194 RC = &X86::VR64RegClass;
2195 else if (RegVT == MVT::v8i1)
2196 RC = &X86::VK8RegClass;
2197 else if (RegVT == MVT::v16i1)
2198 RC = &X86::VK16RegClass;
2200 llvm_unreachable("Unknown argument type!");
2202 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2203 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2205 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2206 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2208 if (VA.getLocInfo() == CCValAssign::SExt)
2209 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2210 DAG.getValueType(VA.getValVT()));
2211 else if (VA.getLocInfo() == CCValAssign::ZExt)
2212 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2213 DAG.getValueType(VA.getValVT()));
2214 else if (VA.getLocInfo() == CCValAssign::BCvt)
2215 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2217 if (VA.isExtInLoc()) {
2218 // Handle MMX values passed in XMM regs.
2219 if (RegVT.isVector())
2220 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2222 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2225 assert(VA.isMemLoc());
2226 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2229 // If value is passed via pointer - do a load.
2230 if (VA.getLocInfo() == CCValAssign::Indirect)
2231 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2232 MachinePointerInfo(), false, false, false, 0);
2234 InVals.push_back(ArgValue);
2237 // The x86-64 ABIs require that for returning structs by value we copy
2238 // the sret argument into %rax/%eax (depending on ABI) for the return.
2239 // Win32 requires us to put the sret argument to %eax as well.
2240 // Save the argument into a virtual register so that we can access it
2241 // from the return points.
2242 if (MF.getFunction()->hasStructRetAttr() &&
2243 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2244 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2245 unsigned Reg = FuncInfo->getSRetReturnReg();
2247 MVT PtrTy = getPointerTy();
2248 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2249 FuncInfo->setSRetReturnReg(Reg);
2251 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2252 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2255 unsigned StackSize = CCInfo.getNextStackOffset();
2256 // Align stack specially for tail calls.
2257 if (FuncIsMadeTailCallSafe(CallConv,
2258 MF.getTarget().Options.GuaranteedTailCallOpt))
2259 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2261 // If the function takes variable number of arguments, make a frame index for
2262 // the start of the first vararg value... for expansion of llvm.va_start.
2264 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2265 CallConv != CallingConv::X86_ThisCall)) {
2266 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2269 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2271 // FIXME: We should really autogenerate these arrays
2272 static const uint16_t GPR64ArgRegsWin64[] = {
2273 X86::RCX, X86::RDX, X86::R8, X86::R9
2275 static const uint16_t GPR64ArgRegs64Bit[] = {
2276 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2278 static const uint16_t XMMArgRegs64Bit[] = {
2279 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2280 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2282 const uint16_t *GPR64ArgRegs;
2283 unsigned NumXMMRegs = 0;
2286 // The XMM registers which might contain var arg parameters are shadowed
2287 // in their paired GPR. So we only need to save the GPR to their home
2289 TotalNumIntRegs = 4;
2290 GPR64ArgRegs = GPR64ArgRegsWin64;
2292 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2293 GPR64ArgRegs = GPR64ArgRegs64Bit;
2295 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2298 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2301 bool NoImplicitFloatOps = Fn->getAttributes().
2302 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2303 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2304 "SSE register cannot be used when SSE is disabled!");
2305 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2306 NoImplicitFloatOps) &&
2307 "SSE register cannot be used when SSE is disabled!");
2308 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2309 !Subtarget->hasSSE1())
2310 // Kernel mode asks for SSE to be disabled, so don't push them
2312 TotalNumXMMRegs = 0;
2315 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2316 // Get to the caller-allocated home save location. Add 8 to account
2317 // for the return address.
2318 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2319 FuncInfo->setRegSaveFrameIndex(
2320 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2321 // Fixup to set vararg frame on shadow area (4 x i64).
2323 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2325 // For X86-64, if there are vararg parameters that are passed via
2326 // registers, then we must store them to their spots on the stack so
2327 // they may be loaded by deferencing the result of va_next.
2328 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2329 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2330 FuncInfo->setRegSaveFrameIndex(
2331 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2335 // Store the integer parameter registers.
2336 SmallVector<SDValue, 8> MemOps;
2337 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2339 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2340 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2341 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2342 DAG.getIntPtrConstant(Offset));
2343 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2344 &X86::GR64RegClass);
2345 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2347 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2348 MachinePointerInfo::getFixedStack(
2349 FuncInfo->getRegSaveFrameIndex(), Offset),
2351 MemOps.push_back(Store);
2355 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2356 // Now store the XMM (fp + vector) parameter registers.
2357 SmallVector<SDValue, 11> SaveXMMOps;
2358 SaveXMMOps.push_back(Chain);
2360 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2361 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2362 SaveXMMOps.push_back(ALVal);
2364 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2365 FuncInfo->getRegSaveFrameIndex()));
2366 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2367 FuncInfo->getVarArgsFPOffset()));
2369 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2370 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2371 &X86::VR128RegClass);
2372 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2373 SaveXMMOps.push_back(Val);
2375 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2377 &SaveXMMOps[0], SaveXMMOps.size()));
2380 if (!MemOps.empty())
2381 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2382 &MemOps[0], MemOps.size());
2386 // Some CCs need callee pop.
2387 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2388 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2389 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2391 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2392 // If this is an sret function, the return should pop the hidden pointer.
2393 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2394 argsAreStructReturn(Ins) == StackStructReturn)
2395 FuncInfo->setBytesToPopOnReturn(4);
2399 // RegSaveFrameIndex is X86-64 only.
2400 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2401 if (CallConv == CallingConv::X86_FastCall ||
2402 CallConv == CallingConv::X86_ThisCall)
2403 // fastcc functions can't have varargs.
2404 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2407 FuncInfo->setArgumentStackSize(StackSize);
2413 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2414 SDValue StackPtr, SDValue Arg,
2415 SDLoc dl, SelectionDAG &DAG,
2416 const CCValAssign &VA,
2417 ISD::ArgFlagsTy Flags) const {
2418 unsigned LocMemOffset = VA.getLocMemOffset();
2419 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2420 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2421 if (Flags.isByVal())
2422 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2424 return DAG.getStore(Chain, dl, Arg, PtrOff,
2425 MachinePointerInfo::getStack(LocMemOffset),
2429 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2430 /// optimization is performed and it is required.
2432 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2433 SDValue &OutRetAddr, SDValue Chain,
2434 bool IsTailCall, bool Is64Bit,
2435 int FPDiff, SDLoc dl) const {
2436 // Adjust the Return address stack slot.
2437 EVT VT = getPointerTy();
2438 OutRetAddr = getReturnAddressFrameIndex(DAG);
2440 // Load the "old" Return address.
2441 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2442 false, false, false, 0);
2443 return SDValue(OutRetAddr.getNode(), 1);
2446 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2447 /// optimization is performed and it is required (FPDiff!=0).
2449 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2450 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2451 unsigned SlotSize, int FPDiff, SDLoc dl) {
2452 // Store the return address to the appropriate stack slot.
2453 if (!FPDiff) return Chain;
2454 // Calculate the new stack slot for the return address.
2455 int NewReturnAddrFI =
2456 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2457 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2458 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2459 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2465 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2466 SmallVectorImpl<SDValue> &InVals) const {
2467 SelectionDAG &DAG = CLI.DAG;
2469 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2470 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2471 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2472 SDValue Chain = CLI.Chain;
2473 SDValue Callee = CLI.Callee;
2474 CallingConv::ID CallConv = CLI.CallConv;
2475 bool &isTailCall = CLI.IsTailCall;
2476 bool isVarArg = CLI.IsVarArg;
2478 MachineFunction &MF = DAG.getMachineFunction();
2479 bool Is64Bit = Subtarget->is64Bit();
2480 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2481 bool IsWindows = Subtarget->isTargetWindows();
2482 StructReturnType SR = callIsStructReturn(Outs);
2483 bool IsSibcall = false;
2485 if (MF.getTarget().Options.DisableTailCalls)
2489 // Check if it's really possible to do a tail call.
2490 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2491 isVarArg, SR != NotStructReturn,
2492 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2493 Outs, OutVals, Ins, DAG);
2495 // Sibcalls are automatically detected tailcalls which do not require
2497 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2504 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2505 "Var args not supported with calling convention fastcc, ghc or hipe");
2507 // Analyze operands of the call, assigning locations to each operand.
2508 SmallVector<CCValAssign, 16> ArgLocs;
2509 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2510 ArgLocs, *DAG.getContext());
2512 // Allocate shadow area for Win64
2514 CCInfo.AllocateStack(32, 8);
2516 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2518 // Get a count of how many bytes are to be pushed on the stack.
2519 unsigned NumBytes = CCInfo.getNextStackOffset();
2521 // This is a sibcall. The memory operands are available in caller's
2522 // own caller's stack.
2524 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2525 IsTailCallConvention(CallConv))
2526 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2529 if (isTailCall && !IsSibcall) {
2530 // Lower arguments at fp - stackoffset + fpdiff.
2531 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2532 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2534 FPDiff = NumBytesCallerPushed - NumBytes;
2536 // Set the delta of movement of the returnaddr stackslot.
2537 // But only set if delta is greater than previous delta.
2538 if (FPDiff < X86Info->getTCReturnAddrDelta())
2539 X86Info->setTCReturnAddrDelta(FPDiff);
2543 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2546 SDValue RetAddrFrIdx;
2547 // Load return address for tail calls.
2548 if (isTailCall && FPDiff)
2549 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2550 Is64Bit, FPDiff, dl);
2552 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2553 SmallVector<SDValue, 8> MemOpChains;
2556 // Walk the register/memloc assignments, inserting copies/loads. In the case
2557 // of tail call optimization arguments are handle later.
2558 const X86RegisterInfo *RegInfo =
2559 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2560 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2561 CCValAssign &VA = ArgLocs[i];
2562 EVT RegVT = VA.getLocVT();
2563 SDValue Arg = OutVals[i];
2564 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2565 bool isByVal = Flags.isByVal();
2567 // Promote the value if needed.
2568 switch (VA.getLocInfo()) {
2569 default: llvm_unreachable("Unknown loc info!");
2570 case CCValAssign::Full: break;
2571 case CCValAssign::SExt:
2572 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2574 case CCValAssign::ZExt:
2575 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2577 case CCValAssign::AExt:
2578 if (RegVT.is128BitVector()) {
2579 // Special case: passing MMX values in XMM registers.
2580 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2581 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2582 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2584 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2586 case CCValAssign::BCvt:
2587 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2589 case CCValAssign::Indirect: {
2590 // Store the argument.
2591 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2592 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2593 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2594 MachinePointerInfo::getFixedStack(FI),
2601 if (VA.isRegLoc()) {
2602 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2603 if (isVarArg && IsWin64) {
2604 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2605 // shadow reg if callee is a varargs function.
2606 unsigned ShadowReg = 0;
2607 switch (VA.getLocReg()) {
2608 case X86::XMM0: ShadowReg = X86::RCX; break;
2609 case X86::XMM1: ShadowReg = X86::RDX; break;
2610 case X86::XMM2: ShadowReg = X86::R8; break;
2611 case X86::XMM3: ShadowReg = X86::R9; break;
2614 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2616 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2617 assert(VA.isMemLoc());
2618 if (StackPtr.getNode() == 0)
2619 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2621 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2622 dl, DAG, VA, Flags));
2626 if (!MemOpChains.empty())
2627 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2628 &MemOpChains[0], MemOpChains.size());
2630 if (Subtarget->isPICStyleGOT()) {
2631 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2634 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2635 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2637 // If we are tail calling and generating PIC/GOT style code load the
2638 // address of the callee into ECX. The value in ecx is used as target of
2639 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2640 // for tail calls on PIC/GOT architectures. Normally we would just put the
2641 // address of GOT into ebx and then call target@PLT. But for tail calls
2642 // ebx would be restored (since ebx is callee saved) before jumping to the
2645 // Note: The actual moving to ECX is done further down.
2646 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2647 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2648 !G->getGlobal()->hasProtectedVisibility())
2649 Callee = LowerGlobalAddress(Callee, DAG);
2650 else if (isa<ExternalSymbolSDNode>(Callee))
2651 Callee = LowerExternalSymbol(Callee, DAG);
2655 if (Is64Bit && isVarArg && !IsWin64) {
2656 // From AMD64 ABI document:
2657 // For calls that may call functions that use varargs or stdargs
2658 // (prototype-less calls or calls to functions containing ellipsis (...) in
2659 // the declaration) %al is used as hidden argument to specify the number
2660 // of SSE registers used. The contents of %al do not need to match exactly
2661 // the number of registers, but must be an ubound on the number of SSE
2662 // registers used and is in the range 0 - 8 inclusive.
2664 // Count the number of XMM registers allocated.
2665 static const uint16_t XMMArgRegs[] = {
2666 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2667 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2669 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2670 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2671 && "SSE registers cannot be used when SSE is disabled");
2673 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2674 DAG.getConstant(NumXMMRegs, MVT::i8)));
2677 // For tail calls lower the arguments to the 'real' stack slot.
2679 // Force all the incoming stack arguments to be loaded from the stack
2680 // before any new outgoing arguments are stored to the stack, because the
2681 // outgoing stack slots may alias the incoming argument stack slots, and
2682 // the alias isn't otherwise explicit. This is slightly more conservative
2683 // than necessary, because it means that each store effectively depends
2684 // on every argument instead of just those arguments it would clobber.
2685 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2687 SmallVector<SDValue, 8> MemOpChains2;
2690 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2691 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2692 CCValAssign &VA = ArgLocs[i];
2695 assert(VA.isMemLoc());
2696 SDValue Arg = OutVals[i];
2697 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2698 // Create frame index.
2699 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2700 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2701 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2702 FIN = DAG.getFrameIndex(FI, getPointerTy());
2704 if (Flags.isByVal()) {
2705 // Copy relative to framepointer.
2706 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2707 if (StackPtr.getNode() == 0)
2708 StackPtr = DAG.getCopyFromReg(Chain, dl,
2709 RegInfo->getStackRegister(),
2711 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2713 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2717 // Store relative to framepointer.
2718 MemOpChains2.push_back(
2719 DAG.getStore(ArgChain, dl, Arg, FIN,
2720 MachinePointerInfo::getFixedStack(FI),
2726 if (!MemOpChains2.empty())
2727 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2728 &MemOpChains2[0], MemOpChains2.size());
2730 // Store the return address to the appropriate stack slot.
2731 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2732 getPointerTy(), RegInfo->getSlotSize(),
2736 // Build a sequence of copy-to-reg nodes chained together with token chain
2737 // and flag operands which copy the outgoing args into registers.
2739 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2740 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2741 RegsToPass[i].second, InFlag);
2742 InFlag = Chain.getValue(1);
2745 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2746 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2747 // In the 64-bit large code model, we have to make all calls
2748 // through a register, since the call instruction's 32-bit
2749 // pc-relative offset may not be large enough to hold the whole
2751 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2752 // If the callee is a GlobalAddress node (quite common, every direct call
2753 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2756 // We should use extra load for direct calls to dllimported functions in
2758 const GlobalValue *GV = G->getGlobal();
2759 if (!GV->hasDLLImportLinkage()) {
2760 unsigned char OpFlags = 0;
2761 bool ExtraLoad = false;
2762 unsigned WrapperKind = ISD::DELETED_NODE;
2764 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2765 // external symbols most go through the PLT in PIC mode. If the symbol
2766 // has hidden or protected visibility, or if it is static or local, then
2767 // we don't need to use the PLT - we can directly call it.
2768 if (Subtarget->isTargetELF() &&
2769 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2770 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2771 OpFlags = X86II::MO_PLT;
2772 } else if (Subtarget->isPICStyleStubAny() &&
2773 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2774 (!Subtarget->getTargetTriple().isMacOSX() ||
2775 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2776 // PC-relative references to external symbols should go through $stub,
2777 // unless we're building with the leopard linker or later, which
2778 // automatically synthesizes these stubs.
2779 OpFlags = X86II::MO_DARWIN_STUB;
2780 } else if (Subtarget->isPICStyleRIPRel() &&
2781 isa<Function>(GV) &&
2782 cast<Function>(GV)->getAttributes().
2783 hasAttribute(AttributeSet::FunctionIndex,
2784 Attribute::NonLazyBind)) {
2785 // If the function is marked as non-lazy, generate an indirect call
2786 // which loads from the GOT directly. This avoids runtime overhead
2787 // at the cost of eager binding (and one extra byte of encoding).
2788 OpFlags = X86II::MO_GOTPCREL;
2789 WrapperKind = X86ISD::WrapperRIP;
2793 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2794 G->getOffset(), OpFlags);
2796 // Add a wrapper if needed.
2797 if (WrapperKind != ISD::DELETED_NODE)
2798 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2799 // Add extra indirection if needed.
2801 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2802 MachinePointerInfo::getGOT(),
2803 false, false, false, 0);
2805 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2806 unsigned char OpFlags = 0;
2808 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2809 // external symbols should go through the PLT.
2810 if (Subtarget->isTargetELF() &&
2811 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2812 OpFlags = X86II::MO_PLT;
2813 } else if (Subtarget->isPICStyleStubAny() &&
2814 (!Subtarget->getTargetTriple().isMacOSX() ||
2815 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2816 // PC-relative references to external symbols should go through $stub,
2817 // unless we're building with the leopard linker or later, which
2818 // automatically synthesizes these stubs.
2819 OpFlags = X86II::MO_DARWIN_STUB;
2822 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2826 // Returns a chain & a flag for retval copy to use.
2827 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2828 SmallVector<SDValue, 8> Ops;
2830 if (!IsSibcall && isTailCall) {
2831 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2832 DAG.getIntPtrConstant(0, true), InFlag, dl);
2833 InFlag = Chain.getValue(1);
2836 Ops.push_back(Chain);
2837 Ops.push_back(Callee);
2840 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2842 // Add argument registers to the end of the list so that they are known live
2844 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2845 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2846 RegsToPass[i].second.getValueType()));
2848 // Add a register mask operand representing the call-preserved registers.
2849 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2850 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2851 assert(Mask && "Missing call preserved mask for calling convention");
2852 Ops.push_back(DAG.getRegisterMask(Mask));
2854 if (InFlag.getNode())
2855 Ops.push_back(InFlag);
2859 //// If this is the first return lowered for this function, add the regs
2860 //// to the liveout set for the function.
2861 // This isn't right, although it's probably harmless on x86; liveouts
2862 // should be computed from returns not tail calls. Consider a void
2863 // function making a tail call to a function returning int.
2864 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2867 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2868 InFlag = Chain.getValue(1);
2870 // Create the CALLSEQ_END node.
2871 unsigned NumBytesForCalleeToPush;
2872 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2873 getTargetMachine().Options.GuaranteedTailCallOpt))
2874 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2875 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2876 SR == StackStructReturn)
2877 // If this is a call to a struct-return function, the callee
2878 // pops the hidden struct pointer, so we have to push it back.
2879 // This is common for Darwin/X86, Linux & Mingw32 targets.
2880 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2881 NumBytesForCalleeToPush = 4;
2883 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2885 // Returns a flag for retval copy to use.
2887 Chain = DAG.getCALLSEQ_END(Chain,
2888 DAG.getIntPtrConstant(NumBytes, true),
2889 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2892 InFlag = Chain.getValue(1);
2895 // Handle result values, copying them out of physregs into vregs that we
2897 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2898 Ins, dl, DAG, InVals);
2901 //===----------------------------------------------------------------------===//
2902 // Fast Calling Convention (tail call) implementation
2903 //===----------------------------------------------------------------------===//
2905 // Like std call, callee cleans arguments, convention except that ECX is
2906 // reserved for storing the tail called function address. Only 2 registers are
2907 // free for argument passing (inreg). Tail call optimization is performed
2909 // * tailcallopt is enabled
2910 // * caller/callee are fastcc
2911 // On X86_64 architecture with GOT-style position independent code only local
2912 // (within module) calls are supported at the moment.
2913 // To keep the stack aligned according to platform abi the function
2914 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2915 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2916 // If a tail called function callee has more arguments than the caller the
2917 // caller needs to make sure that there is room to move the RETADDR to. This is
2918 // achieved by reserving an area the size of the argument delta right after the
2919 // original REtADDR, but before the saved framepointer or the spilled registers
2920 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2932 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2933 /// for a 16 byte align requirement.
2935 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2936 SelectionDAG& DAG) const {
2937 MachineFunction &MF = DAG.getMachineFunction();
2938 const TargetMachine &TM = MF.getTarget();
2939 const X86RegisterInfo *RegInfo =
2940 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2941 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2942 unsigned StackAlignment = TFI.getStackAlignment();
2943 uint64_t AlignMask = StackAlignment - 1;
2944 int64_t Offset = StackSize;
2945 unsigned SlotSize = RegInfo->getSlotSize();
2946 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2947 // Number smaller than 12 so just add the difference.
2948 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2950 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2951 Offset = ((~AlignMask) & Offset) + StackAlignment +
2952 (StackAlignment-SlotSize);
2957 /// MatchingStackOffset - Return true if the given stack call argument is
2958 /// already available in the same position (relatively) of the caller's
2959 /// incoming argument stack.
2961 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2962 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2963 const X86InstrInfo *TII) {
2964 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2966 if (Arg.getOpcode() == ISD::CopyFromReg) {
2967 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2968 if (!TargetRegisterInfo::isVirtualRegister(VR))
2970 MachineInstr *Def = MRI->getVRegDef(VR);
2973 if (!Flags.isByVal()) {
2974 if (!TII->isLoadFromStackSlot(Def, FI))
2977 unsigned Opcode = Def->getOpcode();
2978 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2979 Def->getOperand(1).isFI()) {
2980 FI = Def->getOperand(1).getIndex();
2981 Bytes = Flags.getByValSize();
2985 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2986 if (Flags.isByVal())
2987 // ByVal argument is passed in as a pointer but it's now being
2988 // dereferenced. e.g.
2989 // define @foo(%struct.X* %A) {
2990 // tail call @bar(%struct.X* byval %A)
2993 SDValue Ptr = Ld->getBasePtr();
2994 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2997 FI = FINode->getIndex();
2998 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2999 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3000 FI = FINode->getIndex();
3001 Bytes = Flags.getByValSize();
3005 assert(FI != INT_MAX);
3006 if (!MFI->isFixedObjectIndex(FI))
3008 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3011 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3012 /// for tail call optimization. Targets which want to do tail call
3013 /// optimization should implement this function.
3015 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3016 CallingConv::ID CalleeCC,
3018 bool isCalleeStructRet,
3019 bool isCallerStructRet,
3021 const SmallVectorImpl<ISD::OutputArg> &Outs,
3022 const SmallVectorImpl<SDValue> &OutVals,
3023 const SmallVectorImpl<ISD::InputArg> &Ins,
3024 SelectionDAG &DAG) const {
3025 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3028 // If -tailcallopt is specified, make fastcc functions tail-callable.
3029 const MachineFunction &MF = DAG.getMachineFunction();
3030 const Function *CallerF = MF.getFunction();
3032 // If the function return type is x86_fp80 and the callee return type is not,
3033 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3034 // perform a tailcall optimization here.
3035 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3038 CallingConv::ID CallerCC = CallerF->getCallingConv();
3039 bool CCMatch = CallerCC == CalleeCC;
3040 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3041 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3043 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3044 if (IsTailCallConvention(CalleeCC) && CCMatch)
3049 // Look for obvious safe cases to perform tail call optimization that do not
3050 // require ABI changes. This is what gcc calls sibcall.
3052 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3053 // emit a special epilogue.
3054 const X86RegisterInfo *RegInfo =
3055 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3056 if (RegInfo->needsStackRealignment(MF))
3059 // Also avoid sibcall optimization if either caller or callee uses struct
3060 // return semantics.
3061 if (isCalleeStructRet || isCallerStructRet)
3064 // An stdcall caller is expected to clean up its arguments; the callee
3065 // isn't going to do that.
3066 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3069 // Do not sibcall optimize vararg calls unless all arguments are passed via
3071 if (isVarArg && !Outs.empty()) {
3073 // Optimizing for varargs on Win64 is unlikely to be safe without
3074 // additional testing.
3075 if (IsCalleeWin64 || IsCallerWin64)
3078 SmallVector<CCValAssign, 16> ArgLocs;
3079 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3080 getTargetMachine(), ArgLocs, *DAG.getContext());
3082 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3083 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3084 if (!ArgLocs[i].isRegLoc())
3088 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3089 // stack. Therefore, if it's not used by the call it is not safe to optimize
3090 // this into a sibcall.
3091 bool Unused = false;
3092 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3099 SmallVector<CCValAssign, 16> RVLocs;
3100 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3101 getTargetMachine(), RVLocs, *DAG.getContext());
3102 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3103 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3104 CCValAssign &VA = RVLocs[i];
3105 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3110 // If the calling conventions do not match, then we'd better make sure the
3111 // results are returned in the same way as what the caller expects.
3113 SmallVector<CCValAssign, 16> RVLocs1;
3114 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3115 getTargetMachine(), RVLocs1, *DAG.getContext());
3116 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3118 SmallVector<CCValAssign, 16> RVLocs2;
3119 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3120 getTargetMachine(), RVLocs2, *DAG.getContext());
3121 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3123 if (RVLocs1.size() != RVLocs2.size())
3125 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3126 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3128 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3130 if (RVLocs1[i].isRegLoc()) {
3131 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3134 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3140 // If the callee takes no arguments then go on to check the results of the
3142 if (!Outs.empty()) {
3143 // Check if stack adjustment is needed. For now, do not do this if any
3144 // argument is passed on the stack.
3145 SmallVector<CCValAssign, 16> ArgLocs;
3146 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3147 getTargetMachine(), ArgLocs, *DAG.getContext());
3149 // Allocate shadow area for Win64
3151 CCInfo.AllocateStack(32, 8);
3153 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3154 if (CCInfo.getNextStackOffset()) {
3155 MachineFunction &MF = DAG.getMachineFunction();
3156 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3159 // Check if the arguments are already laid out in the right way as
3160 // the caller's fixed stack objects.
3161 MachineFrameInfo *MFI = MF.getFrameInfo();
3162 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3163 const X86InstrInfo *TII =
3164 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3165 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3166 CCValAssign &VA = ArgLocs[i];
3167 SDValue Arg = OutVals[i];
3168 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3169 if (VA.getLocInfo() == CCValAssign::Indirect)
3171 if (!VA.isRegLoc()) {
3172 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3179 // If the tailcall address may be in a register, then make sure it's
3180 // possible to register allocate for it. In 32-bit, the call address can
3181 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3182 // callee-saved registers are restored. These happen to be the same
3183 // registers used to pass 'inreg' arguments so watch out for those.
3184 if (!Subtarget->is64Bit() &&
3185 ((!isa<GlobalAddressSDNode>(Callee) &&
3186 !isa<ExternalSymbolSDNode>(Callee)) ||
3187 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3188 unsigned NumInRegs = 0;
3189 // In PIC we need an extra register to formulate the address computation
3191 unsigned MaxInRegs =
3192 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3194 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3195 CCValAssign &VA = ArgLocs[i];
3198 unsigned Reg = VA.getLocReg();
3201 case X86::EAX: case X86::EDX: case X86::ECX:
3202 if (++NumInRegs == MaxInRegs)
3214 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3215 const TargetLibraryInfo *libInfo) const {
3216 return X86::createFastISel(funcInfo, libInfo);
3219 //===----------------------------------------------------------------------===//
3220 // Other Lowering Hooks
3221 //===----------------------------------------------------------------------===//
3223 static bool MayFoldLoad(SDValue Op) {
3224 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3227 static bool MayFoldIntoStore(SDValue Op) {
3228 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3231 static bool isTargetShuffle(unsigned Opcode) {
3233 default: return false;
3234 case X86ISD::PSHUFD:
3235 case X86ISD::PSHUFHW:
3236 case X86ISD::PSHUFLW:
3238 case X86ISD::PALIGNR:
3239 case X86ISD::MOVLHPS:
3240 case X86ISD::MOVLHPD:
3241 case X86ISD::MOVHLPS:
3242 case X86ISD::MOVLPS:
3243 case X86ISD::MOVLPD:
3244 case X86ISD::MOVSHDUP:
3245 case X86ISD::MOVSLDUP:
3246 case X86ISD::MOVDDUP:
3249 case X86ISD::UNPCKL:
3250 case X86ISD::UNPCKH:
3251 case X86ISD::VPERMILP:
3252 case X86ISD::VPERM2X128:
3253 case X86ISD::VPERMI:
3258 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3259 SDValue V1, SelectionDAG &DAG) {
3261 default: llvm_unreachable("Unknown x86 shuffle node");
3262 case X86ISD::MOVSHDUP:
3263 case X86ISD::MOVSLDUP:
3264 case X86ISD::MOVDDUP:
3265 return DAG.getNode(Opc, dl, VT, V1);
3269 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3270 SDValue V1, unsigned TargetMask,
3271 SelectionDAG &DAG) {
3273 default: llvm_unreachable("Unknown x86 shuffle node");
3274 case X86ISD::PSHUFD:
3275 case X86ISD::PSHUFHW:
3276 case X86ISD::PSHUFLW:
3277 case X86ISD::VPERMILP:
3278 case X86ISD::VPERMI:
3279 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3283 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3284 SDValue V1, SDValue V2, unsigned TargetMask,
3285 SelectionDAG &DAG) {
3287 default: llvm_unreachable("Unknown x86 shuffle node");
3288 case X86ISD::PALIGNR:
3290 case X86ISD::VPERM2X128:
3291 return DAG.getNode(Opc, dl, VT, V1, V2,
3292 DAG.getConstant(TargetMask, MVT::i8));
3296 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3297 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3299 default: llvm_unreachable("Unknown x86 shuffle node");
3300 case X86ISD::MOVLHPS:
3301 case X86ISD::MOVLHPD:
3302 case X86ISD::MOVHLPS:
3303 case X86ISD::MOVLPS:
3304 case X86ISD::MOVLPD:
3307 case X86ISD::UNPCKL:
3308 case X86ISD::UNPCKH:
3309 return DAG.getNode(Opc, dl, VT, V1, V2);
3313 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3314 MachineFunction &MF = DAG.getMachineFunction();
3315 const X86RegisterInfo *RegInfo =
3316 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3317 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3318 int ReturnAddrIndex = FuncInfo->getRAIndex();
3320 if (ReturnAddrIndex == 0) {
3321 // Set up a frame object for the return address.
3322 unsigned SlotSize = RegInfo->getSlotSize();
3323 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3325 FuncInfo->setRAIndex(ReturnAddrIndex);
3328 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3331 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3332 bool hasSymbolicDisplacement) {
3333 // Offset should fit into 32 bit immediate field.
3334 if (!isInt<32>(Offset))
3337 // If we don't have a symbolic displacement - we don't have any extra
3339 if (!hasSymbolicDisplacement)
3342 // FIXME: Some tweaks might be needed for medium code model.
3343 if (M != CodeModel::Small && M != CodeModel::Kernel)
3346 // For small code model we assume that latest object is 16MB before end of 31
3347 // bits boundary. We may also accept pretty large negative constants knowing
3348 // that all objects are in the positive half of address space.
3349 if (M == CodeModel::Small && Offset < 16*1024*1024)
3352 // For kernel code model we know that all object resist in the negative half
3353 // of 32bits address space. We may not accept negative offsets, since they may
3354 // be just off and we may accept pretty large positive ones.
3355 if (M == CodeModel::Kernel && Offset > 0)
3361 /// isCalleePop - Determines whether the callee is required to pop its
3362 /// own arguments. Callee pop is necessary to support tail calls.
3363 bool X86::isCalleePop(CallingConv::ID CallingConv,
3364 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3368 switch (CallingConv) {
3371 case CallingConv::X86_StdCall:
3373 case CallingConv::X86_FastCall:
3375 case CallingConv::X86_ThisCall:
3377 case CallingConv::Fast:
3379 case CallingConv::GHC:
3381 case CallingConv::HiPE:
3386 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3387 /// specific condition code, returning the condition code and the LHS/RHS of the
3388 /// comparison to make.
3389 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3390 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3392 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3393 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3394 // X > -1 -> X == 0, jump !sign.
3395 RHS = DAG.getConstant(0, RHS.getValueType());
3396 return X86::COND_NS;
3398 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3399 // X < 0 -> X == 0, jump on sign.
3402 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3404 RHS = DAG.getConstant(0, RHS.getValueType());
3405 return X86::COND_LE;
3409 switch (SetCCOpcode) {
3410 default: llvm_unreachable("Invalid integer condition!");
3411 case ISD::SETEQ: return X86::COND_E;
3412 case ISD::SETGT: return X86::COND_G;
3413 case ISD::SETGE: return X86::COND_GE;
3414 case ISD::SETLT: return X86::COND_L;
3415 case ISD::SETLE: return X86::COND_LE;
3416 case ISD::SETNE: return X86::COND_NE;
3417 case ISD::SETULT: return X86::COND_B;
3418 case ISD::SETUGT: return X86::COND_A;
3419 case ISD::SETULE: return X86::COND_BE;
3420 case ISD::SETUGE: return X86::COND_AE;
3424 // First determine if it is required or is profitable to flip the operands.
3426 // If LHS is a foldable load, but RHS is not, flip the condition.
3427 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3428 !ISD::isNON_EXTLoad(RHS.getNode())) {
3429 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3430 std::swap(LHS, RHS);
3433 switch (SetCCOpcode) {
3439 std::swap(LHS, RHS);
3443 // On a floating point condition, the flags are set as follows:
3445 // 0 | 0 | 0 | X > Y
3446 // 0 | 0 | 1 | X < Y
3447 // 1 | 0 | 0 | X == Y
3448 // 1 | 1 | 1 | unordered
3449 switch (SetCCOpcode) {
3450 default: llvm_unreachable("Condcode should be pre-legalized away");
3452 case ISD::SETEQ: return X86::COND_E;
3453 case ISD::SETOLT: // flipped
3455 case ISD::SETGT: return X86::COND_A;
3456 case ISD::SETOLE: // flipped
3458 case ISD::SETGE: return X86::COND_AE;
3459 case ISD::SETUGT: // flipped
3461 case ISD::SETLT: return X86::COND_B;
3462 case ISD::SETUGE: // flipped
3464 case ISD::SETLE: return X86::COND_BE;
3466 case ISD::SETNE: return X86::COND_NE;
3467 case ISD::SETUO: return X86::COND_P;
3468 case ISD::SETO: return X86::COND_NP;
3470 case ISD::SETUNE: return X86::COND_INVALID;
3474 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3475 /// code. Current x86 isa includes the following FP cmov instructions:
3476 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3477 static bool hasFPCMov(unsigned X86CC) {
3493 /// isFPImmLegal - Returns true if the target can instruction select the
3494 /// specified FP immediate natively. If false, the legalizer will
3495 /// materialize the FP immediate as a load from a constant pool.
3496 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3497 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3498 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3504 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3505 /// the specified range (L, H].
3506 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3507 return (Val < 0) || (Val >= Low && Val < Hi);
3510 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3511 /// specified value.
3512 static bool isUndefOrEqual(int Val, int CmpVal) {
3513 return (Val < 0 || Val == CmpVal);
3516 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3517 /// from position Pos and ending in Pos+Size, falls within the specified
3518 /// sequential range (L, L+Pos]. or is undef.
3519 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3520 unsigned Pos, unsigned Size, int Low) {
3521 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3522 if (!isUndefOrEqual(Mask[i], Low))
3527 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3528 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3529 /// the second operand.
3530 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3531 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3532 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3533 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3534 return (Mask[0] < 2 && Mask[1] < 2);
3538 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3539 /// is suitable for input to PSHUFHW.
3540 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3541 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3544 // Lower quadword copied in order or undef.
3545 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3548 // Upper quadword shuffled.
3549 for (unsigned i = 4; i != 8; ++i)
3550 if (!isUndefOrInRange(Mask[i], 4, 8))
3553 if (VT == MVT::v16i16) {
3554 // Lower quadword copied in order or undef.
3555 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3558 // Upper quadword shuffled.
3559 for (unsigned i = 12; i != 16; ++i)
3560 if (!isUndefOrInRange(Mask[i], 12, 16))
3567 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3568 /// is suitable for input to PSHUFLW.
3569 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3570 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3573 // Upper quadword copied in order.
3574 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3577 // Lower quadword shuffled.
3578 for (unsigned i = 0; i != 4; ++i)
3579 if (!isUndefOrInRange(Mask[i], 0, 4))
3582 if (VT == MVT::v16i16) {
3583 // Upper quadword copied in order.
3584 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3587 // Lower quadword shuffled.
3588 for (unsigned i = 8; i != 12; ++i)
3589 if (!isUndefOrInRange(Mask[i], 8, 12))
3596 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3597 /// is suitable for input to PALIGNR.
3598 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3599 const X86Subtarget *Subtarget) {
3600 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3601 (VT.is256BitVector() && !Subtarget->hasInt256()))
3604 unsigned NumElts = VT.getVectorNumElements();
3605 unsigned NumLanes = VT.getSizeInBits()/128;
3606 unsigned NumLaneElts = NumElts/NumLanes;
3608 // Do not handle 64-bit element shuffles with palignr.
3609 if (NumLaneElts == 2)
3612 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3614 for (i = 0; i != NumLaneElts; ++i) {
3619 // Lane is all undef, go to next lane
3620 if (i == NumLaneElts)
3623 int Start = Mask[i+l];
3625 // Make sure its in this lane in one of the sources
3626 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3627 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3630 // If not lane 0, then we must match lane 0
3631 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3634 // Correct second source to be contiguous with first source
3635 if (Start >= (int)NumElts)
3636 Start -= NumElts - NumLaneElts;
3638 // Make sure we're shifting in the right direction.
3639 if (Start <= (int)(i+l))
3644 // Check the rest of the elements to see if they are consecutive.
3645 for (++i; i != NumLaneElts; ++i) {
3646 int Idx = Mask[i+l];
3648 // Make sure its in this lane
3649 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3650 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3653 // If not lane 0, then we must match lane 0
3654 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3657 if (Idx >= (int)NumElts)
3658 Idx -= NumElts - NumLaneElts;
3660 if (!isUndefOrEqual(Idx, Start+i))
3669 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3670 /// the two vector operands have swapped position.
3671 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3672 unsigned NumElems) {
3673 for (unsigned i = 0; i != NumElems; ++i) {
3677 else if (idx < (int)NumElems)
3678 Mask[i] = idx + NumElems;
3680 Mask[i] = idx - NumElems;
3684 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3685 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3686 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3687 /// reverse of what x86 shuffles want.
3688 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3689 bool Commuted = false) {
3690 if (!HasFp256 && VT.is256BitVector())
3693 unsigned NumElems = VT.getVectorNumElements();
3694 unsigned NumLanes = VT.getSizeInBits()/128;
3695 unsigned NumLaneElems = NumElems/NumLanes;
3697 if (NumLaneElems != 2 && NumLaneElems != 4)
3700 // VSHUFPSY divides the resulting vector into 4 chunks.
3701 // The sources are also splitted into 4 chunks, and each destination
3702 // chunk must come from a different source chunk.
3704 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3705 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3707 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3708 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3710 // VSHUFPDY divides the resulting vector into 4 chunks.
3711 // The sources are also splitted into 4 chunks, and each destination
3712 // chunk must come from a different source chunk.
3714 // SRC1 => X3 X2 X1 X0
3715 // SRC2 => Y3 Y2 Y1 Y0
3717 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3719 unsigned HalfLaneElems = NumLaneElems/2;
3720 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3721 for (unsigned i = 0; i != NumLaneElems; ++i) {
3722 int Idx = Mask[i+l];
3723 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3724 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3726 // For VSHUFPSY, the mask of the second half must be the same as the
3727 // first but with the appropriate offsets. This works in the same way as
3728 // VPERMILPS works with masks.
3729 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3731 if (!isUndefOrEqual(Idx, Mask[i]+l))
3739 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3740 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3741 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3742 if (!VT.is128BitVector())
3745 unsigned NumElems = VT.getVectorNumElements();
3750 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3751 return isUndefOrEqual(Mask[0], 6) &&
3752 isUndefOrEqual(Mask[1], 7) &&
3753 isUndefOrEqual(Mask[2], 2) &&
3754 isUndefOrEqual(Mask[3], 3);
3757 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3758 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3760 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3761 if (!VT.is128BitVector())
3764 unsigned NumElems = VT.getVectorNumElements();
3769 return isUndefOrEqual(Mask[0], 2) &&
3770 isUndefOrEqual(Mask[1], 3) &&
3771 isUndefOrEqual(Mask[2], 2) &&
3772 isUndefOrEqual(Mask[3], 3);
3775 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3776 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3777 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3778 if (!VT.is128BitVector())
3781 unsigned NumElems = VT.getVectorNumElements();
3783 if (NumElems != 2 && NumElems != 4)
3786 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3787 if (!isUndefOrEqual(Mask[i], i + NumElems))
3790 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3791 if (!isUndefOrEqual(Mask[i], i))
3797 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3798 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3799 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3800 if (!VT.is128BitVector())
3803 unsigned NumElems = VT.getVectorNumElements();
3805 if (NumElems != 2 && NumElems != 4)
3808 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3809 if (!isUndefOrEqual(Mask[i], i))
3812 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3813 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3820 // Some special combinations that can be optimized.
3823 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3824 SelectionDAG &DAG) {
3825 MVT VT = SVOp->getValueType(0).getSimpleVT();
3828 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3831 ArrayRef<int> Mask = SVOp->getMask();
3833 // These are the special masks that may be optimized.
3834 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3835 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3836 bool MatchEvenMask = true;
3837 bool MatchOddMask = true;
3838 for (int i=0; i<8; ++i) {
3839 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3840 MatchEvenMask = false;
3841 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3842 MatchOddMask = false;
3845 if (!MatchEvenMask && !MatchOddMask)
3848 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3850 SDValue Op0 = SVOp->getOperand(0);
3851 SDValue Op1 = SVOp->getOperand(1);
3853 if (MatchEvenMask) {
3854 // Shift the second operand right to 32 bits.
3855 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3856 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3858 // Shift the first operand left to 32 bits.
3859 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3860 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3862 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3863 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3866 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3867 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3868 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3869 bool HasInt256, bool V2IsSplat = false) {
3870 unsigned NumElts = VT.getVectorNumElements();
3872 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3873 "Unsupported vector type for unpckh");
3875 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3876 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3879 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3880 // independently on 128-bit lanes.
3881 unsigned NumLanes = VT.getSizeInBits()/128;
3882 unsigned NumLaneElts = NumElts/NumLanes;
3884 for (unsigned l = 0; l != NumLanes; ++l) {
3885 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3886 i != (l+1)*NumLaneElts;
3889 int BitI1 = Mask[i+1];
3890 if (!isUndefOrEqual(BitI, j))
3893 if (!isUndefOrEqual(BitI1, NumElts))
3896 if (!isUndefOrEqual(BitI1, j + NumElts))
3905 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3907 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3908 bool HasInt256, bool V2IsSplat = false) {
3909 unsigned NumElts = VT.getVectorNumElements();
3911 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3912 "Unsupported vector type for unpckh");
3914 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3915 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3918 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3919 // independently on 128-bit lanes.
3920 unsigned NumLanes = VT.getSizeInBits()/128;
3921 unsigned NumLaneElts = NumElts/NumLanes;
3923 for (unsigned l = 0; l != NumLanes; ++l) {
3924 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3925 i != (l+1)*NumLaneElts; i += 2, ++j) {
3927 int BitI1 = Mask[i+1];
3928 if (!isUndefOrEqual(BitI, j))
3931 if (isUndefOrEqual(BitI1, NumElts))
3934 if (!isUndefOrEqual(BitI1, j+NumElts))
3942 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3943 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3945 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3946 unsigned NumElts = VT.getVectorNumElements();
3947 bool Is256BitVec = VT.is256BitVector();
3949 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3950 "Unsupported vector type for unpckh");
3952 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3953 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3956 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3957 // FIXME: Need a better way to get rid of this, there's no latency difference
3958 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3959 // the former later. We should also remove the "_undef" special mask.
3960 if (NumElts == 4 && Is256BitVec)
3963 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3964 // independently on 128-bit lanes.
3965 unsigned NumLanes = VT.getSizeInBits()/128;
3966 unsigned NumLaneElts = NumElts/NumLanes;
3968 for (unsigned l = 0; l != NumLanes; ++l) {
3969 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3970 i != (l+1)*NumLaneElts;
3973 int BitI1 = Mask[i+1];
3975 if (!isUndefOrEqual(BitI, j))
3977 if (!isUndefOrEqual(BitI1, j))
3985 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3986 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3988 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3989 unsigned NumElts = VT.getVectorNumElements();
3991 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3992 "Unsupported vector type for unpckh");
3994 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3995 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3998 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3999 // independently on 128-bit lanes.
4000 unsigned NumLanes = VT.getSizeInBits()/128;
4001 unsigned NumLaneElts = NumElts/NumLanes;
4003 for (unsigned l = 0; l != NumLanes; ++l) {
4004 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
4005 i != (l+1)*NumLaneElts; i += 2, ++j) {
4007 int BitI1 = Mask[i+1];
4008 if (!isUndefOrEqual(BitI, j))
4010 if (!isUndefOrEqual(BitI1, j))
4017 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4018 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4019 /// MOVSD, and MOVD, i.e. setting the lowest element.
4020 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4021 if (VT.getVectorElementType().getSizeInBits() < 32)
4023 if (!VT.is128BitVector())
4026 unsigned NumElts = VT.getVectorNumElements();
4028 if (!isUndefOrEqual(Mask[0], NumElts))
4031 for (unsigned i = 1; i != NumElts; ++i)
4032 if (!isUndefOrEqual(Mask[i], i))
4038 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4039 /// as permutations between 128-bit chunks or halves. As an example: this
4041 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4042 /// The first half comes from the second half of V1 and the second half from the
4043 /// the second half of V2.
4044 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4045 if (!HasFp256 || !VT.is256BitVector())
4048 // The shuffle result is divided into half A and half B. In total the two
4049 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4050 // B must come from C, D, E or F.
4051 unsigned HalfSize = VT.getVectorNumElements()/2;
4052 bool MatchA = false, MatchB = false;
4054 // Check if A comes from one of C, D, E, F.
4055 for (unsigned Half = 0; Half != 4; ++Half) {
4056 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4062 // Check if B comes from one of C, D, E, F.
4063 for (unsigned Half = 0; Half != 4; ++Half) {
4064 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4070 return MatchA && MatchB;
4073 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4074 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4075 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4076 MVT VT = SVOp->getValueType(0).getSimpleVT();
4078 unsigned HalfSize = VT.getVectorNumElements()/2;
4080 unsigned FstHalf = 0, SndHalf = 0;
4081 for (unsigned i = 0; i < HalfSize; ++i) {
4082 if (SVOp->getMaskElt(i) > 0) {
4083 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4087 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4088 if (SVOp->getMaskElt(i) > 0) {
4089 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4094 return (FstHalf | (SndHalf << 4));
4097 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4098 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4099 /// Note that VPERMIL mask matching is different depending whether theunderlying
4100 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4101 /// to the same elements of the low, but to the higher half of the source.
4102 /// In VPERMILPD the two lanes could be shuffled independently of each other
4103 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4104 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4108 unsigned NumElts = VT.getVectorNumElements();
4109 // Only match 256-bit with 32/64-bit types
4110 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4113 unsigned NumLanes = VT.getSizeInBits()/128;
4114 unsigned LaneSize = NumElts/NumLanes;
4115 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4116 for (unsigned i = 0; i != LaneSize; ++i) {
4117 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4119 if (NumElts != 8 || l == 0)
4121 // VPERMILPS handling
4124 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4132 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4133 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4134 /// element of vector 2 and the other elements to come from vector 1 in order.
4135 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
4136 bool V2IsSplat = false, bool V2IsUndef = false) {
4137 if (!VT.is128BitVector())
4140 unsigned NumOps = VT.getVectorNumElements();
4141 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4144 if (!isUndefOrEqual(Mask[0], 0))
4147 for (unsigned i = 1; i != NumOps; ++i)
4148 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4149 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4150 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4156 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4157 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4158 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4159 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
4160 const X86Subtarget *Subtarget) {
4161 if (!Subtarget->hasSSE3())
4164 unsigned NumElems = VT.getVectorNumElements();
4166 if ((VT.is128BitVector() && NumElems != 4) ||
4167 (VT.is256BitVector() && NumElems != 8))
4170 // "i+1" is the value the indexed mask element must have
4171 for (unsigned i = 0; i != NumElems; i += 2)
4172 if (!isUndefOrEqual(Mask[i], i+1) ||
4173 !isUndefOrEqual(Mask[i+1], i+1))
4179 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4180 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4181 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4182 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
4183 const X86Subtarget *Subtarget) {
4184 if (!Subtarget->hasSSE3())
4187 unsigned NumElems = VT.getVectorNumElements();
4189 if ((VT.is128BitVector() && NumElems != 4) ||
4190 (VT.is256BitVector() && NumElems != 8))
4193 // "i" is the value the indexed mask element must have
4194 for (unsigned i = 0; i != NumElems; i += 2)
4195 if (!isUndefOrEqual(Mask[i], i) ||
4196 !isUndefOrEqual(Mask[i+1], i))
4202 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4203 /// specifies a shuffle of elements that is suitable for input to 256-bit
4204 /// version of MOVDDUP.
4205 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4206 if (!HasFp256 || !VT.is256BitVector())
4209 unsigned NumElts = VT.getVectorNumElements();
4213 for (unsigned i = 0; i != NumElts/2; ++i)
4214 if (!isUndefOrEqual(Mask[i], 0))
4216 for (unsigned i = NumElts/2; i != NumElts; ++i)
4217 if (!isUndefOrEqual(Mask[i], NumElts/2))
4222 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4223 /// specifies a shuffle of elements that is suitable for input to 128-bit
4224 /// version of MOVDDUP.
4225 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4226 if (!VT.is128BitVector())
4229 unsigned e = VT.getVectorNumElements() / 2;
4230 for (unsigned i = 0; i != e; ++i)
4231 if (!isUndefOrEqual(Mask[i], i))
4233 for (unsigned i = 0; i != e; ++i)
4234 if (!isUndefOrEqual(Mask[e+i], i))
4239 /// isVEXTRACTIndex - Return true if the specified
4240 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4241 /// suitable for instruction that extract 128 or 256 bit vectors
4242 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4243 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4244 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4247 // The index should be aligned on a vecWidth-bit boundary.
4249 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4251 MVT VT = N->getValueType(0).getSimpleVT();
4252 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4253 bool Result = (Index * ElSize) % vecWidth == 0;
4258 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4259 /// operand specifies a subvector insert that is suitable for input to
4260 /// insertion of 128 or 256-bit subvectors
4261 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4262 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4263 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4265 // The index should be aligned on a vecWidth-bit boundary.
4267 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4269 MVT VT = N->getValueType(0).getSimpleVT();
4270 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4271 bool Result = (Index * ElSize) % vecWidth == 0;
4276 bool X86::isVINSERT128Index(SDNode *N) {
4277 return isVINSERTIndex(N, 128);
4280 bool X86::isVINSERT256Index(SDNode *N) {
4281 return isVINSERTIndex(N, 256);
4284 bool X86::isVEXTRACT128Index(SDNode *N) {
4285 return isVEXTRACTIndex(N, 128);
4288 bool X86::isVEXTRACT256Index(SDNode *N) {
4289 return isVEXTRACTIndex(N, 256);
4292 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4293 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4294 /// Handles 128-bit and 256-bit.
4295 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4296 MVT VT = N->getValueType(0).getSimpleVT();
4298 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4299 "Unsupported vector type for PSHUF/SHUFP");
4301 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4302 // independently on 128-bit lanes.
4303 unsigned NumElts = VT.getVectorNumElements();
4304 unsigned NumLanes = VT.getSizeInBits()/128;
4305 unsigned NumLaneElts = NumElts/NumLanes;
4307 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4308 "Only supports 2 or 4 elements per lane");
4310 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4312 for (unsigned i = 0; i != NumElts; ++i) {
4313 int Elt = N->getMaskElt(i);
4314 if (Elt < 0) continue;
4315 Elt &= NumLaneElts - 1;
4316 unsigned ShAmt = (i << Shift) % 8;
4317 Mask |= Elt << ShAmt;
4323 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4324 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4325 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4326 MVT VT = N->getValueType(0).getSimpleVT();
4328 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4329 "Unsupported vector type for PSHUFHW");
4331 unsigned NumElts = VT.getVectorNumElements();
4334 for (unsigned l = 0; l != NumElts; l += 8) {
4335 // 8 nodes per lane, but we only care about the last 4.
4336 for (unsigned i = 0; i < 4; ++i) {
4337 int Elt = N->getMaskElt(l+i+4);
4338 if (Elt < 0) continue;
4339 Elt &= 0x3; // only 2-bits.
4340 Mask |= Elt << (i * 2);
4347 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4348 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4349 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4350 MVT VT = N->getValueType(0).getSimpleVT();
4352 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4353 "Unsupported vector type for PSHUFHW");
4355 unsigned NumElts = VT.getVectorNumElements();
4358 for (unsigned l = 0; l != NumElts; l += 8) {
4359 // 8 nodes per lane, but we only care about the first 4.
4360 for (unsigned i = 0; i < 4; ++i) {
4361 int Elt = N->getMaskElt(l+i);
4362 if (Elt < 0) continue;
4363 Elt &= 0x3; // only 2-bits
4364 Mask |= Elt << (i * 2);
4371 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4372 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4373 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4374 MVT VT = SVOp->getValueType(0).getSimpleVT();
4375 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4377 unsigned NumElts = VT.getVectorNumElements();
4378 unsigned NumLanes = VT.getSizeInBits()/128;
4379 unsigned NumLaneElts = NumElts/NumLanes;
4383 for (i = 0; i != NumElts; ++i) {
4384 Val = SVOp->getMaskElt(i);
4388 if (Val >= (int)NumElts)
4389 Val -= NumElts - NumLaneElts;
4391 assert(Val - i > 0 && "PALIGNR imm should be positive");
4392 return (Val - i) * EltSize;
4395 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4396 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4397 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4398 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4401 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4403 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4404 MVT ElVT = VecVT.getVectorElementType();
4406 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4407 return Index / NumElemsPerChunk;
4410 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4411 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4412 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4413 llvm_unreachable("Illegal insert subvector for VINSERT");
4416 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4418 MVT VecVT = N->getValueType(0).getSimpleVT();
4419 MVT ElVT = VecVT.getVectorElementType();
4421 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4422 return Index / NumElemsPerChunk;
4425 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4426 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4427 /// and VINSERTI128 instructions.
4428 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4429 return getExtractVEXTRACTImmediate(N, 128);
4432 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4433 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4434 /// and VINSERTI64x4 instructions.
4435 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4436 return getExtractVEXTRACTImmediate(N, 256);
4439 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4440 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4441 /// and VINSERTI128 instructions.
4442 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4443 return getInsertVINSERTImmediate(N, 128);
4446 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4447 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4448 /// and VINSERTI64x4 instructions.
4449 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4450 return getInsertVINSERTImmediate(N, 256);
4453 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4454 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4455 /// Handles 256-bit.
4456 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4457 MVT VT = N->getValueType(0).getSimpleVT();
4459 unsigned NumElts = VT.getVectorNumElements();
4461 assert((VT.is256BitVector() && NumElts == 4) &&
4462 "Unsupported vector type for VPERMQ/VPERMPD");
4465 for (unsigned i = 0; i != NumElts; ++i) {
4466 int Elt = N->getMaskElt(i);
4469 Mask |= Elt << (i*2);
4474 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4476 bool X86::isZeroNode(SDValue Elt) {
4477 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4478 return CN->isNullValue();
4479 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4480 return CFP->getValueAPF().isPosZero();
4484 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4485 /// their permute mask.
4486 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4487 SelectionDAG &DAG) {
4488 MVT VT = SVOp->getValueType(0).getSimpleVT();
4489 unsigned NumElems = VT.getVectorNumElements();
4490 SmallVector<int, 8> MaskVec;
4492 for (unsigned i = 0; i != NumElems; ++i) {
4493 int Idx = SVOp->getMaskElt(i);
4495 if (Idx < (int)NumElems)
4500 MaskVec.push_back(Idx);
4502 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4503 SVOp->getOperand(0), &MaskVec[0]);
4506 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4507 /// match movhlps. The lower half elements should come from upper half of
4508 /// V1 (and in order), and the upper half elements should come from the upper
4509 /// half of V2 (and in order).
4510 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4511 if (!VT.is128BitVector())
4513 if (VT.getVectorNumElements() != 4)
4515 for (unsigned i = 0, e = 2; i != e; ++i)
4516 if (!isUndefOrEqual(Mask[i], i+2))
4518 for (unsigned i = 2; i != 4; ++i)
4519 if (!isUndefOrEqual(Mask[i], i+4))
4524 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4525 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4527 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4528 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4530 N = N->getOperand(0).getNode();
4531 if (!ISD::isNON_EXTLoad(N))
4534 *LD = cast<LoadSDNode>(N);
4538 // Test whether the given value is a vector value which will be legalized
4540 static bool WillBeConstantPoolLoad(SDNode *N) {
4541 if (N->getOpcode() != ISD::BUILD_VECTOR)
4544 // Check for any non-constant elements.
4545 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4546 switch (N->getOperand(i).getNode()->getOpcode()) {
4548 case ISD::ConstantFP:
4555 // Vectors of all-zeros and all-ones are materialized with special
4556 // instructions rather than being loaded.
4557 return !ISD::isBuildVectorAllZeros(N) &&
4558 !ISD::isBuildVectorAllOnes(N);
4561 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4562 /// match movlp{s|d}. The lower half elements should come from lower half of
4563 /// V1 (and in order), and the upper half elements should come from the upper
4564 /// half of V2 (and in order). And since V1 will become the source of the
4565 /// MOVLP, it must be either a vector load or a scalar load to vector.
4566 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4567 ArrayRef<int> Mask, EVT VT) {
4568 if (!VT.is128BitVector())
4571 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4573 // Is V2 is a vector load, don't do this transformation. We will try to use
4574 // load folding shufps op.
4575 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4578 unsigned NumElems = VT.getVectorNumElements();
4580 if (NumElems != 2 && NumElems != 4)
4582 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4583 if (!isUndefOrEqual(Mask[i], i))
4585 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4586 if (!isUndefOrEqual(Mask[i], i+NumElems))
4591 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4593 static bool isSplatVector(SDNode *N) {
4594 if (N->getOpcode() != ISD::BUILD_VECTOR)
4597 SDValue SplatValue = N->getOperand(0);
4598 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4599 if (N->getOperand(i) != SplatValue)
4604 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4605 /// to an zero vector.
4606 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4607 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4608 SDValue V1 = N->getOperand(0);
4609 SDValue V2 = N->getOperand(1);
4610 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4611 for (unsigned i = 0; i != NumElems; ++i) {
4612 int Idx = N->getMaskElt(i);
4613 if (Idx >= (int)NumElems) {
4614 unsigned Opc = V2.getOpcode();
4615 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4617 if (Opc != ISD::BUILD_VECTOR ||
4618 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4620 } else if (Idx >= 0) {
4621 unsigned Opc = V1.getOpcode();
4622 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4624 if (Opc != ISD::BUILD_VECTOR ||
4625 !X86::isZeroNode(V1.getOperand(Idx)))
4632 /// getZeroVector - Returns a vector of specified type with all zero elements.
4634 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4635 SelectionDAG &DAG, SDLoc dl) {
4636 assert(VT.isVector() && "Expected a vector type");
4638 // Always build SSE zero vectors as <4 x i32> bitcasted
4639 // to their dest type. This ensures they get CSE'd.
4641 if (VT.is128BitVector()) { // SSE
4642 if (Subtarget->hasSSE2()) { // SSE2
4643 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4644 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4646 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4647 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4649 } else if (VT.is256BitVector()) { // AVX
4650 if (Subtarget->hasInt256()) { // AVX2
4651 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4652 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4653 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4654 array_lengthof(Ops));
4656 // 256-bit logic and arithmetic instructions in AVX are all
4657 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4658 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4659 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4660 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4661 array_lengthof(Ops));
4664 llvm_unreachable("Unexpected vector type");
4666 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4669 /// getOnesVector - Returns a vector of specified type with all bits set.
4670 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4671 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4672 /// Then bitcast to their original type, ensuring they get CSE'd.
4673 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4675 assert(VT.isVector() && "Expected a vector type");
4677 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4679 if (VT.is256BitVector()) {
4680 if (HasInt256) { // AVX2
4681 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4682 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4683 array_lengthof(Ops));
4685 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4686 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4688 } else if (VT.is128BitVector()) {
4689 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4691 llvm_unreachable("Unexpected vector type");
4693 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4696 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4697 /// that point to V2 points to its first element.
4698 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4699 for (unsigned i = 0; i != NumElems; ++i) {
4700 if (Mask[i] > (int)NumElems) {
4706 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4707 /// operation of specified width.
4708 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4710 unsigned NumElems = VT.getVectorNumElements();
4711 SmallVector<int, 8> Mask;
4712 Mask.push_back(NumElems);
4713 for (unsigned i = 1; i != NumElems; ++i)
4715 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4718 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4719 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4721 unsigned NumElems = VT.getVectorNumElements();
4722 SmallVector<int, 8> Mask;
4723 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4725 Mask.push_back(i + NumElems);
4727 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4730 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4731 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4733 unsigned NumElems = VT.getVectorNumElements();
4734 SmallVector<int, 8> Mask;
4735 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4736 Mask.push_back(i + Half);
4737 Mask.push_back(i + NumElems + Half);
4739 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4742 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4743 // a generic shuffle instruction because the target has no such instructions.
4744 // Generate shuffles which repeat i16 and i8 several times until they can be
4745 // represented by v4f32 and then be manipulated by target suported shuffles.
4746 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4747 EVT VT = V.getValueType();
4748 int NumElems = VT.getVectorNumElements();
4751 while (NumElems > 4) {
4752 if (EltNo < NumElems/2) {
4753 V = getUnpackl(DAG, dl, VT, V, V);
4755 V = getUnpackh(DAG, dl, VT, V, V);
4756 EltNo -= NumElems/2;
4763 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4764 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4765 EVT VT = V.getValueType();
4768 if (VT.is128BitVector()) {
4769 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4770 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4771 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4773 } else if (VT.is256BitVector()) {
4774 // To use VPERMILPS to splat scalars, the second half of indicies must
4775 // refer to the higher part, which is a duplication of the lower one,
4776 // because VPERMILPS can only handle in-lane permutations.
4777 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4778 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4780 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4781 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4784 llvm_unreachable("Vector size not supported");
4786 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4789 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4790 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4791 EVT SrcVT = SV->getValueType(0);
4792 SDValue V1 = SV->getOperand(0);
4795 int EltNo = SV->getSplatIndex();
4796 int NumElems = SrcVT.getVectorNumElements();
4797 bool Is256BitVec = SrcVT.is256BitVector();
4799 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4800 "Unknown how to promote splat for type");
4802 // Extract the 128-bit part containing the splat element and update
4803 // the splat element index when it refers to the higher register.
4805 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4806 if (EltNo >= NumElems/2)
4807 EltNo -= NumElems/2;
4810 // All i16 and i8 vector types can't be used directly by a generic shuffle
4811 // instruction because the target has no such instruction. Generate shuffles
4812 // which repeat i16 and i8 several times until they fit in i32, and then can
4813 // be manipulated by target suported shuffles.
4814 EVT EltVT = SrcVT.getVectorElementType();
4815 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4816 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4818 // Recreate the 256-bit vector and place the same 128-bit vector
4819 // into the low and high part. This is necessary because we want
4820 // to use VPERM* to shuffle the vectors
4822 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4825 return getLegalSplat(DAG, V1, EltNo);
4828 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4829 /// vector of zero or undef vector. This produces a shuffle where the low
4830 /// element of V2 is swizzled into the zero/undef vector, landing at element
4831 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4832 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4834 const X86Subtarget *Subtarget,
4835 SelectionDAG &DAG) {
4836 EVT VT = V2.getValueType();
4838 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4839 unsigned NumElems = VT.getVectorNumElements();
4840 SmallVector<int, 16> MaskVec;
4841 for (unsigned i = 0; i != NumElems; ++i)
4842 // If this is the insertion idx, put the low elt of V2 here.
4843 MaskVec.push_back(i == Idx ? NumElems : i);
4844 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4847 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4848 /// target specific opcode. Returns true if the Mask could be calculated.
4849 /// Sets IsUnary to true if only uses one source.
4850 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4851 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4852 unsigned NumElems = VT.getVectorNumElements();
4856 switch(N->getOpcode()) {
4858 ImmN = N->getOperand(N->getNumOperands()-1);
4859 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4861 case X86ISD::UNPCKH:
4862 DecodeUNPCKHMask(VT, Mask);
4864 case X86ISD::UNPCKL:
4865 DecodeUNPCKLMask(VT, Mask);
4867 case X86ISD::MOVHLPS:
4868 DecodeMOVHLPSMask(NumElems, Mask);
4870 case X86ISD::MOVLHPS:
4871 DecodeMOVLHPSMask(NumElems, Mask);
4873 case X86ISD::PALIGNR:
4874 ImmN = N->getOperand(N->getNumOperands()-1);
4875 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4877 case X86ISD::PSHUFD:
4878 case X86ISD::VPERMILP:
4879 ImmN = N->getOperand(N->getNumOperands()-1);
4880 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4883 case X86ISD::PSHUFHW:
4884 ImmN = N->getOperand(N->getNumOperands()-1);
4885 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4888 case X86ISD::PSHUFLW:
4889 ImmN = N->getOperand(N->getNumOperands()-1);
4890 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4893 case X86ISD::VPERMI:
4894 ImmN = N->getOperand(N->getNumOperands()-1);
4895 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4899 case X86ISD::MOVSD: {
4900 // The index 0 always comes from the first element of the second source,
4901 // this is why MOVSS and MOVSD are used in the first place. The other
4902 // elements come from the other positions of the first source vector
4903 Mask.push_back(NumElems);
4904 for (unsigned i = 1; i != NumElems; ++i) {
4909 case X86ISD::VPERM2X128:
4910 ImmN = N->getOperand(N->getNumOperands()-1);
4911 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4912 if (Mask.empty()) return false;
4914 case X86ISD::MOVDDUP:
4915 case X86ISD::MOVLHPD:
4916 case X86ISD::MOVLPD:
4917 case X86ISD::MOVLPS:
4918 case X86ISD::MOVSHDUP:
4919 case X86ISD::MOVSLDUP:
4920 // Not yet implemented
4922 default: llvm_unreachable("unknown target shuffle node");
4928 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4929 /// element of the result of the vector shuffle.
4930 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4933 return SDValue(); // Limit search depth.
4935 SDValue V = SDValue(N, 0);
4936 EVT VT = V.getValueType();
4937 unsigned Opcode = V.getOpcode();
4939 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4940 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4941 int Elt = SV->getMaskElt(Index);
4944 return DAG.getUNDEF(VT.getVectorElementType());
4946 unsigned NumElems = VT.getVectorNumElements();
4947 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4948 : SV->getOperand(1);
4949 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4952 // Recurse into target specific vector shuffles to find scalars.
4953 if (isTargetShuffle(Opcode)) {
4954 MVT ShufVT = V.getValueType().getSimpleVT();
4955 unsigned NumElems = ShufVT.getVectorNumElements();
4956 SmallVector<int, 16> ShuffleMask;
4959 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4962 int Elt = ShuffleMask[Index];
4964 return DAG.getUNDEF(ShufVT.getVectorElementType());
4966 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4968 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4972 // Actual nodes that may contain scalar elements
4973 if (Opcode == ISD::BITCAST) {
4974 V = V.getOperand(0);
4975 EVT SrcVT = V.getValueType();
4976 unsigned NumElems = VT.getVectorNumElements();
4978 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4982 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4983 return (Index == 0) ? V.getOperand(0)
4984 : DAG.getUNDEF(VT.getVectorElementType());
4986 if (V.getOpcode() == ISD::BUILD_VECTOR)
4987 return V.getOperand(Index);
4992 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4993 /// shuffle operation which come from a consecutively from a zero. The
4994 /// search can start in two different directions, from left or right.
4995 /// We count undefs as zeros until PreferredNum is reached.
4996 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4997 unsigned NumElems, bool ZerosFromLeft,
4999 unsigned PreferredNum = -1U) {
5000 unsigned NumZeros = 0;
5001 for (unsigned i = 0; i != NumElems; ++i) {
5002 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5003 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5007 if (X86::isZeroNode(Elt))
5009 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5010 NumZeros = std::min(NumZeros + 1, PreferredNum);
5018 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5019 /// correspond consecutively to elements from one of the vector operands,
5020 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5022 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5023 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5024 unsigned NumElems, unsigned &OpNum) {
5025 bool SeenV1 = false;
5026 bool SeenV2 = false;
5028 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5029 int Idx = SVOp->getMaskElt(i);
5030 // Ignore undef indicies
5034 if (Idx < (int)NumElems)
5039 // Only accept consecutive elements from the same vector
5040 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5044 OpNum = SeenV1 ? 0 : 1;
5048 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5049 /// logical left shift of a vector.
5050 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5051 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5052 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5053 unsigned NumZeros = getNumOfConsecutiveZeros(
5054 SVOp, NumElems, false /* check zeros from right */, DAG,
5055 SVOp->getMaskElt(0));
5061 // Considering the elements in the mask that are not consecutive zeros,
5062 // check if they consecutively come from only one of the source vectors.
5064 // V1 = {X, A, B, C} 0
5066 // vector_shuffle V1, V2 <1, 2, 3, X>
5068 if (!isShuffleMaskConsecutive(SVOp,
5069 0, // Mask Start Index
5070 NumElems-NumZeros, // Mask End Index(exclusive)
5071 NumZeros, // Where to start looking in the src vector
5072 NumElems, // Number of elements in vector
5073 OpSrc)) // Which source operand ?
5078 ShVal = SVOp->getOperand(OpSrc);
5082 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5083 /// logical left shift of a vector.
5084 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5085 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5086 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5087 unsigned NumZeros = getNumOfConsecutiveZeros(
5088 SVOp, NumElems, true /* check zeros from left */, DAG,
5089 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5095 // Considering the elements in the mask that are not consecutive zeros,
5096 // check if they consecutively come from only one of the source vectors.
5098 // 0 { A, B, X, X } = V2
5100 // vector_shuffle V1, V2 <X, X, 4, 5>
5102 if (!isShuffleMaskConsecutive(SVOp,
5103 NumZeros, // Mask Start Index
5104 NumElems, // Mask End Index(exclusive)
5105 0, // Where to start looking in the src vector
5106 NumElems, // Number of elements in vector
5107 OpSrc)) // Which source operand ?
5112 ShVal = SVOp->getOperand(OpSrc);
5116 /// isVectorShift - Returns true if the shuffle can be implemented as a
5117 /// logical left or right shift of a vector.
5118 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5119 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5120 // Although the logic below support any bitwidth size, there are no
5121 // shift instructions which handle more than 128-bit vectors.
5122 if (!SVOp->getValueType(0).is128BitVector())
5125 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5126 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5132 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5134 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5135 unsigned NumNonZero, unsigned NumZero,
5137 const X86Subtarget* Subtarget,
5138 const TargetLowering &TLI) {
5145 for (unsigned i = 0; i < 16; ++i) {
5146 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5147 if (ThisIsNonZero && First) {
5149 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5151 V = DAG.getUNDEF(MVT::v8i16);
5156 SDValue ThisElt(0, 0), LastElt(0, 0);
5157 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5158 if (LastIsNonZero) {
5159 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5160 MVT::i16, Op.getOperand(i-1));
5162 if (ThisIsNonZero) {
5163 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5164 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5165 ThisElt, DAG.getConstant(8, MVT::i8));
5167 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5171 if (ThisElt.getNode())
5172 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5173 DAG.getIntPtrConstant(i/2));
5177 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5180 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5182 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5183 unsigned NumNonZero, unsigned NumZero,
5185 const X86Subtarget* Subtarget,
5186 const TargetLowering &TLI) {
5193 for (unsigned i = 0; i < 8; ++i) {
5194 bool isNonZero = (NonZeros & (1 << i)) != 0;
5198 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5200 V = DAG.getUNDEF(MVT::v8i16);
5203 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5204 MVT::v8i16, V, Op.getOperand(i),
5205 DAG.getIntPtrConstant(i));
5212 /// getVShift - Return a vector logical shift node.
5214 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5215 unsigned NumBits, SelectionDAG &DAG,
5216 const TargetLowering &TLI, SDLoc dl) {
5217 assert(VT.is128BitVector() && "Unknown type for VShift");
5218 EVT ShVT = MVT::v2i64;
5219 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5220 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5221 return DAG.getNode(ISD::BITCAST, dl, VT,
5222 DAG.getNode(Opc, dl, ShVT, SrcOp,
5223 DAG.getConstant(NumBits,
5224 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5228 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5229 SelectionDAG &DAG) const {
5231 // Check if the scalar load can be widened into a vector load. And if
5232 // the address is "base + cst" see if the cst can be "absorbed" into
5233 // the shuffle mask.
5234 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5235 SDValue Ptr = LD->getBasePtr();
5236 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5238 EVT PVT = LD->getValueType(0);
5239 if (PVT != MVT::i32 && PVT != MVT::f32)
5244 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5245 FI = FINode->getIndex();
5247 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5248 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5249 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5250 Offset = Ptr.getConstantOperandVal(1);
5251 Ptr = Ptr.getOperand(0);
5256 // FIXME: 256-bit vector instructions don't require a strict alignment,
5257 // improve this code to support it better.
5258 unsigned RequiredAlign = VT.getSizeInBits()/8;
5259 SDValue Chain = LD->getChain();
5260 // Make sure the stack object alignment is at least 16 or 32.
5261 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5262 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5263 if (MFI->isFixedObjectIndex(FI)) {
5264 // Can't change the alignment. FIXME: It's possible to compute
5265 // the exact stack offset and reference FI + adjust offset instead.
5266 // If someone *really* cares about this. That's the way to implement it.
5269 MFI->setObjectAlignment(FI, RequiredAlign);
5273 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5274 // Ptr + (Offset & ~15).
5277 if ((Offset % RequiredAlign) & 3)
5279 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5281 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5282 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5284 int EltNo = (Offset - StartOffset) >> 2;
5285 unsigned NumElems = VT.getVectorNumElements();
5287 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5288 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5289 LD->getPointerInfo().getWithOffset(StartOffset),
5290 false, false, false, 0);
5292 SmallVector<int, 8> Mask;
5293 for (unsigned i = 0; i != NumElems; ++i)
5294 Mask.push_back(EltNo);
5296 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5302 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5303 /// vector of type 'VT', see if the elements can be replaced by a single large
5304 /// load which has the same value as a build_vector whose operands are 'elts'.
5306 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5308 /// FIXME: we'd also like to handle the case where the last elements are zero
5309 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5310 /// There's even a handy isZeroNode for that purpose.
5311 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5312 SDLoc &DL, SelectionDAG &DAG) {
5313 EVT EltVT = VT.getVectorElementType();
5314 unsigned NumElems = Elts.size();
5316 LoadSDNode *LDBase = NULL;
5317 unsigned LastLoadedElt = -1U;
5319 // For each element in the initializer, see if we've found a load or an undef.
5320 // If we don't find an initial load element, or later load elements are
5321 // non-consecutive, bail out.
5322 for (unsigned i = 0; i < NumElems; ++i) {
5323 SDValue Elt = Elts[i];
5325 if (!Elt.getNode() ||
5326 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5329 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5331 LDBase = cast<LoadSDNode>(Elt.getNode());
5335 if (Elt.getOpcode() == ISD::UNDEF)
5338 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5339 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5344 // If we have found an entire vector of loads and undefs, then return a large
5345 // load of the entire vector width starting at the base pointer. If we found
5346 // consecutive loads for the low half, generate a vzext_load node.
5347 if (LastLoadedElt == NumElems - 1) {
5348 SDValue NewLd = SDValue();
5349 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5350 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5351 LDBase->getPointerInfo(),
5352 LDBase->isVolatile(), LDBase->isNonTemporal(),
5353 LDBase->isInvariant(), 0);
5354 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5355 LDBase->getPointerInfo(),
5356 LDBase->isVolatile(), LDBase->isNonTemporal(),
5357 LDBase->isInvariant(), LDBase->getAlignment());
5359 if (LDBase->hasAnyUseOfValue(1)) {
5360 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5362 SDValue(NewLd.getNode(), 1));
5363 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5364 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5365 SDValue(NewLd.getNode(), 1));
5370 if (NumElems == 4 && LastLoadedElt == 1 &&
5371 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5372 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5373 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5375 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5376 array_lengthof(Ops), MVT::i64,
5377 LDBase->getPointerInfo(),
5378 LDBase->getAlignment(),
5379 false/*isVolatile*/, true/*ReadMem*/,
5382 // Make sure the newly-created LOAD is in the same position as LDBase in
5383 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5384 // update uses of LDBase's output chain to use the TokenFactor.
5385 if (LDBase->hasAnyUseOfValue(1)) {
5386 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5387 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5388 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5389 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5390 SDValue(ResNode.getNode(), 1));
5393 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5398 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5399 /// to generate a splat value for the following cases:
5400 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5401 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5402 /// a scalar load, or a constant.
5403 /// The VBROADCAST node is returned when a pattern is found,
5404 /// or SDValue() otherwise.
5406 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5407 if (!Subtarget->hasFp256())
5410 MVT VT = Op.getValueType().getSimpleVT();
5413 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5414 "Unsupported vector type for broadcast.");
5419 switch (Op.getOpcode()) {
5421 // Unknown pattern found.
5424 case ISD::BUILD_VECTOR: {
5425 // The BUILD_VECTOR node must be a splat.
5426 if (!isSplatVector(Op.getNode()))
5429 Ld = Op.getOperand(0);
5430 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5431 Ld.getOpcode() == ISD::ConstantFP);
5433 // The suspected load node has several users. Make sure that all
5434 // of its users are from the BUILD_VECTOR node.
5435 // Constants may have multiple users.
5436 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5441 case ISD::VECTOR_SHUFFLE: {
5442 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5444 // Shuffles must have a splat mask where the first element is
5446 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5449 SDValue Sc = Op.getOperand(0);
5450 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5451 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5453 if (!Subtarget->hasInt256())
5456 // Use the register form of the broadcast instruction available on AVX2.
5457 if (VT.is256BitVector())
5458 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5459 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5462 Ld = Sc.getOperand(0);
5463 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5464 Ld.getOpcode() == ISD::ConstantFP);
5466 // The scalar_to_vector node and the suspected
5467 // load node must have exactly one user.
5468 // Constants may have multiple users.
5469 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5475 bool Is256 = VT.is256BitVector();
5477 // Handle the broadcasting a single constant scalar from the constant pool
5478 // into a vector. On Sandybridge it is still better to load a constant vector
5479 // from the constant pool and not to broadcast it from a scalar.
5480 if (ConstSplatVal && Subtarget->hasInt256()) {
5481 EVT CVT = Ld.getValueType();
5482 assert(!CVT.isVector() && "Must not broadcast a vector type");
5483 unsigned ScalarSize = CVT.getSizeInBits();
5485 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5486 const Constant *C = 0;
5487 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5488 C = CI->getConstantIntValue();
5489 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5490 C = CF->getConstantFPValue();
5492 assert(C && "Invalid constant type");
5494 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5495 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5496 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5497 MachinePointerInfo::getConstantPool(),
5498 false, false, false, Alignment);
5500 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5504 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5505 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5507 // Handle AVX2 in-register broadcasts.
5508 if (!IsLoad && Subtarget->hasInt256() &&
5509 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5510 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5512 // The scalar source must be a normal load.
5516 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5517 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5519 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5520 // double since there is no vbroadcastsd xmm
5521 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5522 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5523 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5526 // Unsupported broadcast.
5531 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5532 EVT VT = Op.getValueType();
5534 // Skip if insert_vec_elt is not supported.
5535 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5539 unsigned NumElems = Op.getNumOperands();
5543 SmallVector<unsigned, 4> InsertIndices;
5544 SmallVector<int, 8> Mask(NumElems, -1);
5546 for (unsigned i = 0; i != NumElems; ++i) {
5547 unsigned Opc = Op.getOperand(i).getOpcode();
5549 if (Opc == ISD::UNDEF)
5552 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5553 // Quit if more than 1 elements need inserting.
5554 if (InsertIndices.size() > 1)
5557 InsertIndices.push_back(i);
5561 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5562 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5564 // Quit if extracted from vector of different type.
5565 if (ExtractedFromVec.getValueType() != VT)
5568 // Quit if non-constant index.
5569 if (!isa<ConstantSDNode>(ExtIdx))
5572 if (VecIn1.getNode() == 0)
5573 VecIn1 = ExtractedFromVec;
5574 else if (VecIn1 != ExtractedFromVec) {
5575 if (VecIn2.getNode() == 0)
5576 VecIn2 = ExtractedFromVec;
5577 else if (VecIn2 != ExtractedFromVec)
5578 // Quit if more than 2 vectors to shuffle
5582 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5584 if (ExtractedFromVec == VecIn1)
5586 else if (ExtractedFromVec == VecIn2)
5587 Mask[i] = Idx + NumElems;
5590 if (VecIn1.getNode() == 0)
5593 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5594 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5595 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5596 unsigned Idx = InsertIndices[i];
5597 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5598 DAG.getIntPtrConstant(Idx));
5605 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5608 MVT VT = Op.getValueType().getSimpleVT();
5609 MVT ExtVT = VT.getVectorElementType();
5610 unsigned NumElems = Op.getNumOperands();
5612 // Vectors containing all zeros can be matched by pxor and xorps later
5613 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5614 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5615 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5616 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5619 return getZeroVector(VT, Subtarget, DAG, dl);
5622 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5623 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5624 // vpcmpeqd on 256-bit vectors.
5625 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5626 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5629 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5632 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5633 if (Broadcast.getNode())
5636 unsigned EVTBits = ExtVT.getSizeInBits();
5638 unsigned NumZero = 0;
5639 unsigned NumNonZero = 0;
5640 unsigned NonZeros = 0;
5641 bool IsAllConstants = true;
5642 SmallSet<SDValue, 8> Values;
5643 for (unsigned i = 0; i < NumElems; ++i) {
5644 SDValue Elt = Op.getOperand(i);
5645 if (Elt.getOpcode() == ISD::UNDEF)
5648 if (Elt.getOpcode() != ISD::Constant &&
5649 Elt.getOpcode() != ISD::ConstantFP)
5650 IsAllConstants = false;
5651 if (X86::isZeroNode(Elt))
5654 NonZeros |= (1 << i);
5659 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5660 if (NumNonZero == 0)
5661 return DAG.getUNDEF(VT);
5663 // Special case for single non-zero, non-undef, element.
5664 if (NumNonZero == 1) {
5665 unsigned Idx = countTrailingZeros(NonZeros);
5666 SDValue Item = Op.getOperand(Idx);
5668 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5669 // the value are obviously zero, truncate the value to i32 and do the
5670 // insertion that way. Only do this if the value is non-constant or if the
5671 // value is a constant being inserted into element 0. It is cheaper to do
5672 // a constant pool load than it is to do a movd + shuffle.
5673 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5674 (!IsAllConstants || Idx == 0)) {
5675 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5677 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5678 EVT VecVT = MVT::v4i32;
5679 unsigned VecElts = 4;
5681 // Truncate the value (which may itself be a constant) to i32, and
5682 // convert it to a vector with movd (S2V+shuffle to zero extend).
5683 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5684 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5685 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5687 // Now we have our 32-bit value zero extended in the low element of
5688 // a vector. If Idx != 0, swizzle it into place.
5690 SmallVector<int, 4> Mask;
5691 Mask.push_back(Idx);
5692 for (unsigned i = 1; i != VecElts; ++i)
5694 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5697 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5701 // If we have a constant or non-constant insertion into the low element of
5702 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5703 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5704 // depending on what the source datatype is.
5707 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5709 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5710 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5711 if (VT.is256BitVector()) {
5712 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5713 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5714 Item, DAG.getIntPtrConstant(0));
5716 assert(VT.is128BitVector() && "Expected an SSE value type!");
5717 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5718 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5719 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5722 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5723 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5724 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5725 if (VT.is256BitVector()) {
5726 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5727 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5729 assert(VT.is128BitVector() && "Expected an SSE value type!");
5730 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5732 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5736 // Is it a vector logical left shift?
5737 if (NumElems == 2 && Idx == 1 &&
5738 X86::isZeroNode(Op.getOperand(0)) &&
5739 !X86::isZeroNode(Op.getOperand(1))) {
5740 unsigned NumBits = VT.getSizeInBits();
5741 return getVShift(true, VT,
5742 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5743 VT, Op.getOperand(1)),
5744 NumBits/2, DAG, *this, dl);
5747 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5750 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5751 // is a non-constant being inserted into an element other than the low one,
5752 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5753 // movd/movss) to move this into the low element, then shuffle it into
5755 if (EVTBits == 32) {
5756 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5758 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5759 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5760 SmallVector<int, 8> MaskVec;
5761 for (unsigned i = 0; i != NumElems; ++i)
5762 MaskVec.push_back(i == Idx ? 0 : 1);
5763 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5767 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5768 if (Values.size() == 1) {
5769 if (EVTBits == 32) {
5770 // Instead of a shuffle like this:
5771 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5772 // Check if it's possible to issue this instead.
5773 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5774 unsigned Idx = countTrailingZeros(NonZeros);
5775 SDValue Item = Op.getOperand(Idx);
5776 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5777 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5782 // A vector full of immediates; various special cases are already
5783 // handled, so this is best done with a single constant-pool load.
5787 // For AVX-length vectors, build the individual 128-bit pieces and use
5788 // shuffles to put them in place.
5789 if (VT.is256BitVector()) {
5790 SmallVector<SDValue, 32> V;
5791 for (unsigned i = 0; i != NumElems; ++i)
5792 V.push_back(Op.getOperand(i));
5794 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5796 // Build both the lower and upper subvector.
5797 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5798 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5801 // Recreate the wider vector with the lower and upper part.
5802 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5805 // Let legalizer expand 2-wide build_vectors.
5806 if (EVTBits == 64) {
5807 if (NumNonZero == 1) {
5808 // One half is zero or undef.
5809 unsigned Idx = countTrailingZeros(NonZeros);
5810 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5811 Op.getOperand(Idx));
5812 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5817 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5818 if (EVTBits == 8 && NumElems == 16) {
5819 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5821 if (V.getNode()) return V;
5824 if (EVTBits == 16 && NumElems == 8) {
5825 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5827 if (V.getNode()) return V;
5830 // If element VT is == 32 bits, turn it into a number of shuffles.
5831 SmallVector<SDValue, 8> V(NumElems);
5832 if (NumElems == 4 && NumZero > 0) {
5833 for (unsigned i = 0; i < 4; ++i) {
5834 bool isZero = !(NonZeros & (1 << i));
5836 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5838 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5841 for (unsigned i = 0; i < 2; ++i) {
5842 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5845 V[i] = V[i*2]; // Must be a zero vector.
5848 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5851 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5854 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5859 bool Reverse1 = (NonZeros & 0x3) == 2;
5860 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5864 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5865 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5867 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5870 if (Values.size() > 1 && VT.is128BitVector()) {
5871 // Check for a build vector of consecutive loads.
5872 for (unsigned i = 0; i < NumElems; ++i)
5873 V[i] = Op.getOperand(i);
5875 // Check for elements which are consecutive loads.
5876 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5880 // Check for a build vector from mostly shuffle plus few inserting.
5881 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5885 // For SSE 4.1, use insertps to put the high elements into the low element.
5886 if (getSubtarget()->hasSSE41()) {
5888 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5889 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5891 Result = DAG.getUNDEF(VT);
5893 for (unsigned i = 1; i < NumElems; ++i) {
5894 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5895 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5896 Op.getOperand(i), DAG.getIntPtrConstant(i));
5901 // Otherwise, expand into a number of unpckl*, start by extending each of
5902 // our (non-undef) elements to the full vector width with the element in the
5903 // bottom slot of the vector (which generates no code for SSE).
5904 for (unsigned i = 0; i < NumElems; ++i) {
5905 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5906 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5908 V[i] = DAG.getUNDEF(VT);
5911 // Next, we iteratively mix elements, e.g. for v4f32:
5912 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5913 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5914 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5915 unsigned EltStride = NumElems >> 1;
5916 while (EltStride != 0) {
5917 for (unsigned i = 0; i < EltStride; ++i) {
5918 // If V[i+EltStride] is undef and this is the first round of mixing,
5919 // then it is safe to just drop this shuffle: V[i] is already in the
5920 // right place, the one element (since it's the first round) being
5921 // inserted as undef can be dropped. This isn't safe for successive
5922 // rounds because they will permute elements within both vectors.
5923 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5924 EltStride == NumElems/2)
5927 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5936 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5937 // to create 256-bit vectors from two other 128-bit ones.
5938 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5940 MVT ResVT = Op.getValueType().getSimpleVT();
5942 assert((ResVT.is256BitVector() ||
5943 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5945 SDValue V1 = Op.getOperand(0);
5946 SDValue V2 = Op.getOperand(1);
5947 unsigned NumElems = ResVT.getVectorNumElements();
5948 if(ResVT.is256BitVector())
5949 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5951 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5954 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5955 assert(Op.getNumOperands() == 2);
5957 // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
5958 // from two other 128-bit ones.
5959 return LowerAVXCONCAT_VECTORS(Op, DAG);
5962 // Try to lower a shuffle node into a simple blend instruction.
5964 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5965 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5966 SDValue V1 = SVOp->getOperand(0);
5967 SDValue V2 = SVOp->getOperand(1);
5969 MVT VT = SVOp->getValueType(0).getSimpleVT();
5970 MVT EltVT = VT.getVectorElementType();
5971 unsigned NumElems = VT.getVectorNumElements();
5973 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5975 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5978 // Check the mask for BLEND and build the value.
5979 unsigned MaskValue = 0;
5980 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5981 unsigned NumLanes = (NumElems-1)/8 + 1;
5982 unsigned NumElemsInLane = NumElems / NumLanes;
5984 // Blend for v16i16 should be symetric for the both lanes.
5985 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5987 int SndLaneEltIdx = (NumLanes == 2) ?
5988 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5989 int EltIdx = SVOp->getMaskElt(i);
5991 if ((EltIdx < 0 || EltIdx == (int)i) &&
5992 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5995 if (((unsigned)EltIdx == (i + NumElems)) &&
5996 (SndLaneEltIdx < 0 ||
5997 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5998 MaskValue |= (1<<i);
6003 // Convert i32 vectors to floating point if it is not AVX2.
6004 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6006 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6007 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6009 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6010 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6013 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6014 DAG.getConstant(MaskValue, MVT::i32));
6015 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6018 // v8i16 shuffles - Prefer shuffles in the following order:
6019 // 1. [all] pshuflw, pshufhw, optional move
6020 // 2. [ssse3] 1 x pshufb
6021 // 3. [ssse3] 2 x pshufb + 1 x por
6022 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6024 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6025 SelectionDAG &DAG) {
6026 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6027 SDValue V1 = SVOp->getOperand(0);
6028 SDValue V2 = SVOp->getOperand(1);
6030 SmallVector<int, 8> MaskVals;
6032 // Determine if more than 1 of the words in each of the low and high quadwords
6033 // of the result come from the same quadword of one of the two inputs. Undef
6034 // mask values count as coming from any quadword, for better codegen.
6035 unsigned LoQuad[] = { 0, 0, 0, 0 };
6036 unsigned HiQuad[] = { 0, 0, 0, 0 };
6037 std::bitset<4> InputQuads;
6038 for (unsigned i = 0; i < 8; ++i) {
6039 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6040 int EltIdx = SVOp->getMaskElt(i);
6041 MaskVals.push_back(EltIdx);
6050 InputQuads.set(EltIdx / 4);
6053 int BestLoQuad = -1;
6054 unsigned MaxQuad = 1;
6055 for (unsigned i = 0; i < 4; ++i) {
6056 if (LoQuad[i] > MaxQuad) {
6058 MaxQuad = LoQuad[i];
6062 int BestHiQuad = -1;
6064 for (unsigned i = 0; i < 4; ++i) {
6065 if (HiQuad[i] > MaxQuad) {
6067 MaxQuad = HiQuad[i];
6071 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6072 // of the two input vectors, shuffle them into one input vector so only a
6073 // single pshufb instruction is necessary. If There are more than 2 input
6074 // quads, disable the next transformation since it does not help SSSE3.
6075 bool V1Used = InputQuads[0] || InputQuads[1];
6076 bool V2Used = InputQuads[2] || InputQuads[3];
6077 if (Subtarget->hasSSSE3()) {
6078 if (InputQuads.count() == 2 && V1Used && V2Used) {
6079 BestLoQuad = InputQuads[0] ? 0 : 1;
6080 BestHiQuad = InputQuads[2] ? 2 : 3;
6082 if (InputQuads.count() > 2) {
6088 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6089 // the shuffle mask. If a quad is scored as -1, that means that it contains
6090 // words from all 4 input quadwords.
6092 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6094 BestLoQuad < 0 ? 0 : BestLoQuad,
6095 BestHiQuad < 0 ? 1 : BestHiQuad
6097 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6098 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6099 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6100 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6102 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6103 // source words for the shuffle, to aid later transformations.
6104 bool AllWordsInNewV = true;
6105 bool InOrder[2] = { true, true };
6106 for (unsigned i = 0; i != 8; ++i) {
6107 int idx = MaskVals[i];
6109 InOrder[i/4] = false;
6110 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6112 AllWordsInNewV = false;
6116 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6117 if (AllWordsInNewV) {
6118 for (int i = 0; i != 8; ++i) {
6119 int idx = MaskVals[i];
6122 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6123 if ((idx != i) && idx < 4)
6125 if ((idx != i) && idx > 3)
6134 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6135 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6136 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6137 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6138 unsigned TargetMask = 0;
6139 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6140 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6141 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6142 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6143 getShufflePSHUFLWImmediate(SVOp);
6144 V1 = NewV.getOperand(0);
6145 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6149 // Promote splats to a larger type which usually leads to more efficient code.
6150 // FIXME: Is this true if pshufb is available?
6151 if (SVOp->isSplat())
6152 return PromoteSplat(SVOp, DAG);
6154 // If we have SSSE3, and all words of the result are from 1 input vector,
6155 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6156 // is present, fall back to case 4.
6157 if (Subtarget->hasSSSE3()) {
6158 SmallVector<SDValue,16> pshufbMask;
6160 // If we have elements from both input vectors, set the high bit of the
6161 // shuffle mask element to zero out elements that come from V2 in the V1
6162 // mask, and elements that come from V1 in the V2 mask, so that the two
6163 // results can be OR'd together.
6164 bool TwoInputs = V1Used && V2Used;
6165 for (unsigned i = 0; i != 8; ++i) {
6166 int EltIdx = MaskVals[i] * 2;
6167 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6168 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6169 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6170 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6172 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6173 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6174 DAG.getNode(ISD::BUILD_VECTOR, dl,
6175 MVT::v16i8, &pshufbMask[0], 16));
6177 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6179 // Calculate the shuffle mask for the second input, shuffle it, and
6180 // OR it with the first shuffled input.
6182 for (unsigned i = 0; i != 8; ++i) {
6183 int EltIdx = MaskVals[i] * 2;
6184 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6185 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6186 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6187 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6189 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6190 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6191 DAG.getNode(ISD::BUILD_VECTOR, dl,
6192 MVT::v16i8, &pshufbMask[0], 16));
6193 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6194 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6197 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6198 // and update MaskVals with new element order.
6199 std::bitset<8> InOrder;
6200 if (BestLoQuad >= 0) {
6201 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6202 for (int i = 0; i != 4; ++i) {
6203 int idx = MaskVals[i];
6206 } else if ((idx / 4) == BestLoQuad) {
6211 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6214 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6215 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6216 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6218 getShufflePSHUFLWImmediate(SVOp), DAG);
6222 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6223 // and update MaskVals with the new element order.
6224 if (BestHiQuad >= 0) {
6225 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6226 for (unsigned i = 4; i != 8; ++i) {
6227 int idx = MaskVals[i];
6230 } else if ((idx / 4) == BestHiQuad) {
6231 MaskV[i] = (idx & 3) + 4;
6235 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6238 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6239 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6240 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6242 getShufflePSHUFHWImmediate(SVOp), DAG);
6246 // In case BestHi & BestLo were both -1, which means each quadword has a word
6247 // from each of the four input quadwords, calculate the InOrder bitvector now
6248 // before falling through to the insert/extract cleanup.
6249 if (BestLoQuad == -1 && BestHiQuad == -1) {
6251 for (int i = 0; i != 8; ++i)
6252 if (MaskVals[i] < 0 || MaskVals[i] == i)
6256 // The other elements are put in the right place using pextrw and pinsrw.
6257 for (unsigned i = 0; i != 8; ++i) {
6260 int EltIdx = MaskVals[i];
6263 SDValue ExtOp = (EltIdx < 8) ?
6264 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6265 DAG.getIntPtrConstant(EltIdx)) :
6266 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6267 DAG.getIntPtrConstant(EltIdx - 8));
6268 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6269 DAG.getIntPtrConstant(i));
6274 // v16i8 shuffles - Prefer shuffles in the following order:
6275 // 1. [ssse3] 1 x pshufb
6276 // 2. [ssse3] 2 x pshufb + 1 x por
6277 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6279 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6281 const X86TargetLowering &TLI) {
6282 SDValue V1 = SVOp->getOperand(0);
6283 SDValue V2 = SVOp->getOperand(1);
6285 ArrayRef<int> MaskVals = SVOp->getMask();
6287 // Promote splats to a larger type which usually leads to more efficient code.
6288 // FIXME: Is this true if pshufb is available?
6289 if (SVOp->isSplat())
6290 return PromoteSplat(SVOp, DAG);
6292 // If we have SSSE3, case 1 is generated when all result bytes come from
6293 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6294 // present, fall back to case 3.
6296 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6297 if (TLI.getSubtarget()->hasSSSE3()) {
6298 SmallVector<SDValue,16> pshufbMask;
6300 // If all result elements are from one input vector, then only translate
6301 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6303 // Otherwise, we have elements from both input vectors, and must zero out
6304 // elements that come from V2 in the first mask, and V1 in the second mask
6305 // so that we can OR them together.
6306 for (unsigned i = 0; i != 16; ++i) {
6307 int EltIdx = MaskVals[i];
6308 if (EltIdx < 0 || EltIdx >= 16)
6310 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6312 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6313 DAG.getNode(ISD::BUILD_VECTOR, dl,
6314 MVT::v16i8, &pshufbMask[0], 16));
6316 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6317 // the 2nd operand if it's undefined or zero.
6318 if (V2.getOpcode() == ISD::UNDEF ||
6319 ISD::isBuildVectorAllZeros(V2.getNode()))
6322 // Calculate the shuffle mask for the second input, shuffle it, and
6323 // OR it with the first shuffled input.
6325 for (unsigned i = 0; i != 16; ++i) {
6326 int EltIdx = MaskVals[i];
6327 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6328 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6330 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6331 DAG.getNode(ISD::BUILD_VECTOR, dl,
6332 MVT::v16i8, &pshufbMask[0], 16));
6333 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6336 // No SSSE3 - Calculate in place words and then fix all out of place words
6337 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6338 // the 16 different words that comprise the two doublequadword input vectors.
6339 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6340 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6342 for (int i = 0; i != 8; ++i) {
6343 int Elt0 = MaskVals[i*2];
6344 int Elt1 = MaskVals[i*2+1];
6346 // This word of the result is all undef, skip it.
6347 if (Elt0 < 0 && Elt1 < 0)
6350 // This word of the result is already in the correct place, skip it.
6351 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6354 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6355 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6358 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6359 // using a single extract together, load it and store it.
6360 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6361 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6362 DAG.getIntPtrConstant(Elt1 / 2));
6363 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6364 DAG.getIntPtrConstant(i));
6368 // If Elt1 is defined, extract it from the appropriate source. If the
6369 // source byte is not also odd, shift the extracted word left 8 bits
6370 // otherwise clear the bottom 8 bits if we need to do an or.
6372 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6373 DAG.getIntPtrConstant(Elt1 / 2));
6374 if ((Elt1 & 1) == 0)
6375 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6377 TLI.getShiftAmountTy(InsElt.getValueType())));
6379 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6380 DAG.getConstant(0xFF00, MVT::i16));
6382 // If Elt0 is defined, extract it from the appropriate source. If the
6383 // source byte is not also even, shift the extracted word right 8 bits. If
6384 // Elt1 was also defined, OR the extracted values together before
6385 // inserting them in the result.
6387 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6388 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6389 if ((Elt0 & 1) != 0)
6390 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6392 TLI.getShiftAmountTy(InsElt0.getValueType())));
6394 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6395 DAG.getConstant(0x00FF, MVT::i16));
6396 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6399 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6400 DAG.getIntPtrConstant(i));
6402 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6405 // v32i8 shuffles - Translate to VPSHUFB if possible.
6407 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6408 const X86Subtarget *Subtarget,
6409 SelectionDAG &DAG) {
6410 MVT VT = SVOp->getValueType(0).getSimpleVT();
6411 SDValue V1 = SVOp->getOperand(0);
6412 SDValue V2 = SVOp->getOperand(1);
6414 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6416 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6417 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6418 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6420 // VPSHUFB may be generated if
6421 // (1) one of input vector is undefined or zeroinitializer.
6422 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6423 // And (2) the mask indexes don't cross the 128-bit lane.
6424 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6425 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6428 if (V1IsAllZero && !V2IsAllZero) {
6429 CommuteVectorShuffleMask(MaskVals, 32);
6432 SmallVector<SDValue, 32> pshufbMask;
6433 for (unsigned i = 0; i != 32; i++) {
6434 int EltIdx = MaskVals[i];
6435 if (EltIdx < 0 || EltIdx >= 32)
6438 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6439 // Cross lane is not allowed.
6443 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6445 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6446 DAG.getNode(ISD::BUILD_VECTOR, dl,
6447 MVT::v32i8, &pshufbMask[0], 32));
6450 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6451 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6452 /// done when every pair / quad of shuffle mask elements point to elements in
6453 /// the right sequence. e.g.
6454 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6456 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6457 SelectionDAG &DAG) {
6458 MVT VT = SVOp->getValueType(0).getSimpleVT();
6460 unsigned NumElems = VT.getVectorNumElements();
6463 switch (VT.SimpleTy) {
6464 default: llvm_unreachable("Unexpected!");
6465 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6466 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6467 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6468 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6469 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6470 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6473 SmallVector<int, 8> MaskVec;
6474 for (unsigned i = 0; i != NumElems; i += Scale) {
6476 for (unsigned j = 0; j != Scale; ++j) {
6477 int EltIdx = SVOp->getMaskElt(i+j);
6481 StartIdx = (EltIdx / Scale);
6482 if (EltIdx != (int)(StartIdx*Scale + j))
6485 MaskVec.push_back(StartIdx);
6488 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6489 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6490 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6493 /// getVZextMovL - Return a zero-extending vector move low node.
6495 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6496 SDValue SrcOp, SelectionDAG &DAG,
6497 const X86Subtarget *Subtarget, SDLoc dl) {
6498 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6499 LoadSDNode *LD = NULL;
6500 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6501 LD = dyn_cast<LoadSDNode>(SrcOp);
6503 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6505 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6506 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6507 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6508 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6509 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6511 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6512 return DAG.getNode(ISD::BITCAST, dl, VT,
6513 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6514 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6522 return DAG.getNode(ISD::BITCAST, dl, VT,
6523 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6524 DAG.getNode(ISD::BITCAST, dl,
6528 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6529 /// which could not be matched by any known target speficic shuffle
6531 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6533 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6534 if (NewOp.getNode())
6537 MVT VT = SVOp->getValueType(0).getSimpleVT();
6539 unsigned NumElems = VT.getVectorNumElements();
6540 unsigned NumLaneElems = NumElems / 2;
6543 MVT EltVT = VT.getVectorElementType();
6544 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6547 SmallVector<int, 16> Mask;
6548 for (unsigned l = 0; l < 2; ++l) {
6549 // Build a shuffle mask for the output, discovering on the fly which
6550 // input vectors to use as shuffle operands (recorded in InputUsed).
6551 // If building a suitable shuffle vector proves too hard, then bail
6552 // out with UseBuildVector set.
6553 bool UseBuildVector = false;
6554 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6555 unsigned LaneStart = l * NumLaneElems;
6556 for (unsigned i = 0; i != NumLaneElems; ++i) {
6557 // The mask element. This indexes into the input.
6558 int Idx = SVOp->getMaskElt(i+LaneStart);
6560 // the mask element does not index into any input vector.
6565 // The input vector this mask element indexes into.
6566 int Input = Idx / NumLaneElems;
6568 // Turn the index into an offset from the start of the input vector.
6569 Idx -= Input * NumLaneElems;
6571 // Find or create a shuffle vector operand to hold this input.
6573 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6574 if (InputUsed[OpNo] == Input)
6575 // This input vector is already an operand.
6577 if (InputUsed[OpNo] < 0) {
6578 // Create a new operand for this input vector.
6579 InputUsed[OpNo] = Input;
6584 if (OpNo >= array_lengthof(InputUsed)) {
6585 // More than two input vectors used! Give up on trying to create a
6586 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6587 UseBuildVector = true;
6591 // Add the mask index for the new shuffle vector.
6592 Mask.push_back(Idx + OpNo * NumLaneElems);
6595 if (UseBuildVector) {
6596 SmallVector<SDValue, 16> SVOps;
6597 for (unsigned i = 0; i != NumLaneElems; ++i) {
6598 // The mask element. This indexes into the input.
6599 int Idx = SVOp->getMaskElt(i+LaneStart);
6601 SVOps.push_back(DAG.getUNDEF(EltVT));
6605 // The input vector this mask element indexes into.
6606 int Input = Idx / NumElems;
6608 // Turn the index into an offset from the start of the input vector.
6609 Idx -= Input * NumElems;
6611 // Extract the vector element by hand.
6612 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6613 SVOp->getOperand(Input),
6614 DAG.getIntPtrConstant(Idx)));
6617 // Construct the output using a BUILD_VECTOR.
6618 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6620 } else if (InputUsed[0] < 0) {
6621 // No input vectors were used! The result is undefined.
6622 Output[l] = DAG.getUNDEF(NVT);
6624 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6625 (InputUsed[0] % 2) * NumLaneElems,
6627 // If only one input was used, use an undefined vector for the other.
6628 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6629 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6630 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6631 // At least one input vector was used. Create a new shuffle vector.
6632 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6638 // Concatenate the result back
6639 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6642 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6643 /// 4 elements, and match them with several different shuffle types.
6645 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6646 SDValue V1 = SVOp->getOperand(0);
6647 SDValue V2 = SVOp->getOperand(1);
6649 MVT VT = SVOp->getValueType(0).getSimpleVT();
6651 assert(VT.is128BitVector() && "Unsupported vector size");
6653 std::pair<int, int> Locs[4];
6654 int Mask1[] = { -1, -1, -1, -1 };
6655 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6659 for (unsigned i = 0; i != 4; ++i) {
6660 int Idx = PermMask[i];
6662 Locs[i] = std::make_pair(-1, -1);
6664 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6666 Locs[i] = std::make_pair(0, NumLo);
6670 Locs[i] = std::make_pair(1, NumHi);
6672 Mask1[2+NumHi] = Idx;
6678 if (NumLo <= 2 && NumHi <= 2) {
6679 // If no more than two elements come from either vector. This can be
6680 // implemented with two shuffles. First shuffle gather the elements.
6681 // The second shuffle, which takes the first shuffle as both of its
6682 // vector operands, put the elements into the right order.
6683 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6685 int Mask2[] = { -1, -1, -1, -1 };
6687 for (unsigned i = 0; i != 4; ++i)
6688 if (Locs[i].first != -1) {
6689 unsigned Idx = (i < 2) ? 0 : 4;
6690 Idx += Locs[i].first * 2 + Locs[i].second;
6694 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6697 if (NumLo == 3 || NumHi == 3) {
6698 // Otherwise, we must have three elements from one vector, call it X, and
6699 // one element from the other, call it Y. First, use a shufps to build an
6700 // intermediate vector with the one element from Y and the element from X
6701 // that will be in the same half in the final destination (the indexes don't
6702 // matter). Then, use a shufps to build the final vector, taking the half
6703 // containing the element from Y from the intermediate, and the other half
6706 // Normalize it so the 3 elements come from V1.
6707 CommuteVectorShuffleMask(PermMask, 4);
6711 // Find the element from V2.
6713 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6714 int Val = PermMask[HiIndex];
6721 Mask1[0] = PermMask[HiIndex];
6723 Mask1[2] = PermMask[HiIndex^1];
6725 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6728 Mask1[0] = PermMask[0];
6729 Mask1[1] = PermMask[1];
6730 Mask1[2] = HiIndex & 1 ? 6 : 4;
6731 Mask1[3] = HiIndex & 1 ? 4 : 6;
6732 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6735 Mask1[0] = HiIndex & 1 ? 2 : 0;
6736 Mask1[1] = HiIndex & 1 ? 0 : 2;
6737 Mask1[2] = PermMask[2];
6738 Mask1[3] = PermMask[3];
6743 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6746 // Break it into (shuffle shuffle_hi, shuffle_lo).
6747 int LoMask[] = { -1, -1, -1, -1 };
6748 int HiMask[] = { -1, -1, -1, -1 };
6750 int *MaskPtr = LoMask;
6751 unsigned MaskIdx = 0;
6754 for (unsigned i = 0; i != 4; ++i) {
6761 int Idx = PermMask[i];
6763 Locs[i] = std::make_pair(-1, -1);
6764 } else if (Idx < 4) {
6765 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6766 MaskPtr[LoIdx] = Idx;
6769 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6770 MaskPtr[HiIdx] = Idx;
6775 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6776 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6777 int MaskOps[] = { -1, -1, -1, -1 };
6778 for (unsigned i = 0; i != 4; ++i)
6779 if (Locs[i].first != -1)
6780 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6781 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6784 static bool MayFoldVectorLoad(SDValue V) {
6785 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6786 V = V.getOperand(0);
6788 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6789 V = V.getOperand(0);
6790 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6791 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6792 // BUILD_VECTOR (load), undef
6793 V = V.getOperand(0);
6795 return MayFoldLoad(V);
6799 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6800 EVT VT = Op.getValueType();
6802 // Canonizalize to v2f64.
6803 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6804 return DAG.getNode(ISD::BITCAST, dl, VT,
6805 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6810 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6812 SDValue V1 = Op.getOperand(0);
6813 SDValue V2 = Op.getOperand(1);
6814 EVT VT = Op.getValueType();
6816 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6818 if (HasSSE2 && VT == MVT::v2f64)
6819 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6821 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6822 return DAG.getNode(ISD::BITCAST, dl, VT,
6823 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6824 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6825 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6829 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6830 SDValue V1 = Op.getOperand(0);
6831 SDValue V2 = Op.getOperand(1);
6832 EVT VT = Op.getValueType();
6834 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6835 "unsupported shuffle type");
6837 if (V2.getOpcode() == ISD::UNDEF)
6841 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6845 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6846 SDValue V1 = Op.getOperand(0);
6847 SDValue V2 = Op.getOperand(1);
6848 EVT VT = Op.getValueType();
6849 unsigned NumElems = VT.getVectorNumElements();
6851 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6852 // operand of these instructions is only memory, so check if there's a
6853 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6855 bool CanFoldLoad = false;
6857 // Trivial case, when V2 comes from a load.
6858 if (MayFoldVectorLoad(V2))
6861 // When V1 is a load, it can be folded later into a store in isel, example:
6862 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6864 // (MOVLPSmr addr:$src1, VR128:$src2)
6865 // So, recognize this potential and also use MOVLPS or MOVLPD
6866 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6869 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6871 if (HasSSE2 && NumElems == 2)
6872 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6875 // If we don't care about the second element, proceed to use movss.
6876 if (SVOp->getMaskElt(1) != -1)
6877 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6880 // movl and movlp will both match v2i64, but v2i64 is never matched by
6881 // movl earlier because we make it strict to avoid messing with the movlp load
6882 // folding logic (see the code above getMOVLP call). Match it here then,
6883 // this is horrible, but will stay like this until we move all shuffle
6884 // matching to x86 specific nodes. Note that for the 1st condition all
6885 // types are matched with movsd.
6887 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6888 // as to remove this logic from here, as much as possible
6889 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6890 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6891 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6894 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6896 // Invert the operand order and use SHUFPS to match it.
6897 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6898 getShuffleSHUFImmediate(SVOp), DAG);
6901 // Reduce a vector shuffle to zext.
6903 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6904 // PMOVZX is only available from SSE41.
6905 if (!Subtarget->hasSSE41())
6908 EVT VT = Op.getValueType();
6910 // Only AVX2 support 256-bit vector integer extending.
6911 if (!Subtarget->hasInt256() && VT.is256BitVector())
6914 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6916 SDValue V1 = Op.getOperand(0);
6917 SDValue V2 = Op.getOperand(1);
6918 unsigned NumElems = VT.getVectorNumElements();
6920 // Extending is an unary operation and the element type of the source vector
6921 // won't be equal to or larger than i64.
6922 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6923 VT.getVectorElementType() == MVT::i64)
6926 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6927 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6928 while ((1U << Shift) < NumElems) {
6929 if (SVOp->getMaskElt(1U << Shift) == 1)
6932 // The maximal ratio is 8, i.e. from i8 to i64.
6937 // Check the shuffle mask.
6938 unsigned Mask = (1U << Shift) - 1;
6939 for (unsigned i = 0; i != NumElems; ++i) {
6940 int EltIdx = SVOp->getMaskElt(i);
6941 if ((i & Mask) != 0 && EltIdx != -1)
6943 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6947 LLVMContext *Context = DAG.getContext();
6948 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6949 EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6950 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6952 if (!isTypeLegal(NVT))
6955 // Simplify the operand as it's prepared to be fed into shuffle.
6956 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6957 if (V1.getOpcode() == ISD::BITCAST &&
6958 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6959 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6961 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6962 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6963 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6964 ConstantSDNode *CIdx =
6965 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6966 // If it's foldable, i.e. normal load with single use, we will let code
6967 // selection to fold it. Otherwise, we will short the conversion sequence.
6968 if (CIdx && CIdx->getZExtValue() == 0 &&
6969 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6970 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6971 // The "ext_vec_elt" node is wider than the result node.
6972 // In this case we should extract subvector from V.
6973 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6974 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6975 EVT FullVT = V.getValueType();
6976 EVT SubVecVT = EVT::getVectorVT(*Context,
6977 FullVT.getVectorElementType(),
6978 FullVT.getVectorNumElements()/Ratio);
6979 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6980 DAG.getIntPtrConstant(0));
6982 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6986 return DAG.getNode(ISD::BITCAST, DL, VT,
6987 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6991 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6992 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6993 MVT VT = Op.getValueType().getSimpleVT();
6995 SDValue V1 = Op.getOperand(0);
6996 SDValue V2 = Op.getOperand(1);
6998 if (isZeroShuffle(SVOp))
6999 return getZeroVector(VT, Subtarget, DAG, dl);
7001 // Handle splat operations
7002 if (SVOp->isSplat()) {
7003 // Use vbroadcast whenever the splat comes from a foldable load
7004 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7005 if (Broadcast.getNode())
7009 // Check integer expanding shuffles.
7010 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7011 if (NewOp.getNode())
7014 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7016 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7017 VT == MVT::v16i16 || VT == MVT::v32i8) {
7018 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7019 if (NewOp.getNode())
7020 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7021 } else if ((VT == MVT::v4i32 ||
7022 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7023 // FIXME: Figure out a cleaner way to do this.
7024 // Try to make use of movq to zero out the top part.
7025 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7026 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7027 if (NewOp.getNode()) {
7028 MVT NewVT = NewOp.getValueType().getSimpleVT();
7029 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7030 NewVT, true, false))
7031 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7032 DAG, Subtarget, dl);
7034 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7035 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7036 if (NewOp.getNode()) {
7037 MVT NewVT = NewOp.getValueType().getSimpleVT();
7038 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7039 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7040 DAG, Subtarget, dl);
7048 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7049 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7050 SDValue V1 = Op.getOperand(0);
7051 SDValue V2 = Op.getOperand(1);
7052 MVT VT = Op.getValueType().getSimpleVT();
7054 unsigned NumElems = VT.getVectorNumElements();
7055 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7056 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7057 bool V1IsSplat = false;
7058 bool V2IsSplat = false;
7059 bool HasSSE2 = Subtarget->hasSSE2();
7060 bool HasFp256 = Subtarget->hasFp256();
7061 bool HasInt256 = Subtarget->hasInt256();
7062 MachineFunction &MF = DAG.getMachineFunction();
7063 bool OptForSize = MF.getFunction()->getAttributes().
7064 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7066 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7068 if (V1IsUndef && V2IsUndef)
7069 return DAG.getUNDEF(VT);
7071 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7073 // Vector shuffle lowering takes 3 steps:
7075 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7076 // narrowing and commutation of operands should be handled.
7077 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7079 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7080 // so the shuffle can be broken into other shuffles and the legalizer can
7081 // try the lowering again.
7083 // The general idea is that no vector_shuffle operation should be left to
7084 // be matched during isel, all of them must be converted to a target specific
7087 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7088 // narrowing and commutation of operands should be handled. The actual code
7089 // doesn't include all of those, work in progress...
7090 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7091 if (NewOp.getNode())
7094 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7096 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7097 // unpckh_undef). Only use pshufd if speed is more important than size.
7098 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7099 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7100 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7101 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7103 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7104 V2IsUndef && MayFoldVectorLoad(V1))
7105 return getMOVDDup(Op, dl, V1, DAG);
7107 if (isMOVHLPS_v_undef_Mask(M, VT))
7108 return getMOVHighToLow(Op, dl, DAG);
7110 // Use to match splats
7111 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7112 (VT == MVT::v2f64 || VT == MVT::v2i64))
7113 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7115 if (isPSHUFDMask(M, VT)) {
7116 // The actual implementation will match the mask in the if above and then
7117 // during isel it can match several different instructions, not only pshufd
7118 // as its name says, sad but true, emulate the behavior for now...
7119 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7120 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7122 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7124 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7125 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7127 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7128 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7131 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7135 if (isPALIGNRMask(M, VT, Subtarget))
7136 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7137 getShufflePALIGNRImmediate(SVOp),
7140 // Check if this can be converted into a logical shift.
7141 bool isLeft = false;
7144 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7145 if (isShift && ShVal.hasOneUse()) {
7146 // If the shifted value has multiple uses, it may be cheaper to use
7147 // v_set0 + movlhps or movhlps, etc.
7148 MVT EltVT = VT.getVectorElementType();
7149 ShAmt *= EltVT.getSizeInBits();
7150 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7153 if (isMOVLMask(M, VT)) {
7154 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7155 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7156 if (!isMOVLPMask(M, VT)) {
7157 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7158 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7160 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7161 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7165 // FIXME: fold these into legal mask.
7166 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7167 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7169 if (isMOVHLPSMask(M, VT))
7170 return getMOVHighToLow(Op, dl, DAG);
7172 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7173 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7175 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7176 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7178 if (isMOVLPMask(M, VT))
7179 return getMOVLP(Op, dl, DAG, HasSSE2);
7181 if (ShouldXformToMOVHLPS(M, VT) ||
7182 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7183 return CommuteVectorShuffle(SVOp, DAG);
7186 // No better options. Use a vshldq / vsrldq.
7187 MVT EltVT = VT.getVectorElementType();
7188 ShAmt *= EltVT.getSizeInBits();
7189 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7192 bool Commuted = false;
7193 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7194 // 1,1,1,1 -> v8i16 though.
7195 V1IsSplat = isSplatVector(V1.getNode());
7196 V2IsSplat = isSplatVector(V2.getNode());
7198 // Canonicalize the splat or undef, if present, to be on the RHS.
7199 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7200 CommuteVectorShuffleMask(M, NumElems);
7202 std::swap(V1IsSplat, V2IsSplat);
7206 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7207 // Shuffling low element of v1 into undef, just return v1.
7210 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7211 // the instruction selector will not match, so get a canonical MOVL with
7212 // swapped operands to undo the commute.
7213 return getMOVL(DAG, dl, VT, V2, V1);
7216 if (isUNPCKLMask(M, VT, HasInt256))
7217 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7219 if (isUNPCKHMask(M, VT, HasInt256))
7220 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7223 // Normalize mask so all entries that point to V2 points to its first
7224 // element then try to match unpck{h|l} again. If match, return a
7225 // new vector_shuffle with the corrected mask.p
7226 SmallVector<int, 8> NewMask(M.begin(), M.end());
7227 NormalizeMask(NewMask, NumElems);
7228 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7229 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7230 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7231 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7235 // Commute is back and try unpck* again.
7236 // FIXME: this seems wrong.
7237 CommuteVectorShuffleMask(M, NumElems);
7239 std::swap(V1IsSplat, V2IsSplat);
7242 if (isUNPCKLMask(M, VT, HasInt256))
7243 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7245 if (isUNPCKHMask(M, VT, HasInt256))
7246 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7249 // Normalize the node to match x86 shuffle ops if needed
7250 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7251 return CommuteVectorShuffle(SVOp, DAG);
7253 // The checks below are all present in isShuffleMaskLegal, but they are
7254 // inlined here right now to enable us to directly emit target specific
7255 // nodes, and remove one by one until they don't return Op anymore.
7257 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7258 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7259 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7260 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7263 if (isPSHUFHWMask(M, VT, HasInt256))
7264 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7265 getShufflePSHUFHWImmediate(SVOp),
7268 if (isPSHUFLWMask(M, VT, HasInt256))
7269 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7270 getShufflePSHUFLWImmediate(SVOp),
7273 if (isSHUFPMask(M, VT, HasFp256))
7274 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7275 getShuffleSHUFImmediate(SVOp), DAG);
7277 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7278 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7279 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7280 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7282 //===--------------------------------------------------------------------===//
7283 // Generate target specific nodes for 128 or 256-bit shuffles only
7284 // supported in the AVX instruction set.
7287 // Handle VMOVDDUPY permutations
7288 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7289 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7291 // Handle VPERMILPS/D* permutations
7292 if (isVPERMILPMask(M, VT, HasFp256)) {
7293 if (HasInt256 && VT == MVT::v8i32)
7294 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7295 getShuffleSHUFImmediate(SVOp), DAG);
7296 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7297 getShuffleSHUFImmediate(SVOp), DAG);
7300 // Handle VPERM2F128/VPERM2I128 permutations
7301 if (isVPERM2X128Mask(M, VT, HasFp256))
7302 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7303 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7305 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7306 if (BlendOp.getNode())
7309 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7310 SmallVector<SDValue, 8> permclMask;
7311 for (unsigned i = 0; i != 8; ++i) {
7312 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7314 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7316 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7317 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7318 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7321 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7322 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7323 getShuffleCLImmediate(SVOp), DAG);
7325 //===--------------------------------------------------------------------===//
7326 // Since no target specific shuffle was selected for this generic one,
7327 // lower it into other known shuffles. FIXME: this isn't true yet, but
7328 // this is the plan.
7331 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7332 if (VT == MVT::v8i16) {
7333 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7334 if (NewOp.getNode())
7338 if (VT == MVT::v16i8) {
7339 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7340 if (NewOp.getNode())
7344 if (VT == MVT::v32i8) {
7345 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7346 if (NewOp.getNode())
7350 // Handle all 128-bit wide vectors with 4 elements, and match them with
7351 // several different shuffle types.
7352 if (NumElems == 4 && VT.is128BitVector())
7353 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7355 // Handle general 256-bit shuffles
7356 if (VT.is256BitVector())
7357 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7362 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7363 MVT VT = Op.getValueType().getSimpleVT();
7366 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7369 if (VT.getSizeInBits() == 8) {
7370 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7371 Op.getOperand(0), Op.getOperand(1));
7372 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7373 DAG.getValueType(VT));
7374 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7377 if (VT.getSizeInBits() == 16) {
7378 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7379 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7381 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7382 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7383 DAG.getNode(ISD::BITCAST, dl,
7387 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7388 Op.getOperand(0), Op.getOperand(1));
7389 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7390 DAG.getValueType(VT));
7391 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7394 if (VT == MVT::f32) {
7395 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7396 // the result back to FR32 register. It's only worth matching if the
7397 // result has a single use which is a store or a bitcast to i32. And in
7398 // the case of a store, it's not worth it if the index is a constant 0,
7399 // because a MOVSSmr can be used instead, which is smaller and faster.
7400 if (!Op.hasOneUse())
7402 SDNode *User = *Op.getNode()->use_begin();
7403 if ((User->getOpcode() != ISD::STORE ||
7404 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7405 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7406 (User->getOpcode() != ISD::BITCAST ||
7407 User->getValueType(0) != MVT::i32))
7409 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7410 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7413 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7416 if (VT == MVT::i32 || VT == MVT::i64) {
7417 // ExtractPS/pextrq works with constant index.
7418 if (isa<ConstantSDNode>(Op.getOperand(1)))
7425 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7426 SelectionDAG &DAG) const {
7428 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7431 SDValue Vec = Op.getOperand(0);
7432 MVT VecVT = Vec.getValueType().getSimpleVT();
7434 // If this is a 256-bit vector result, first extract the 128-bit vector and
7435 // then extract the element from the 128-bit vector.
7436 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7437 SDValue Idx = Op.getOperand(1);
7438 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7440 // Get the 128-bit vector.
7441 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7442 EVT EltVT = VecVT.getVectorElementType();
7444 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7446 //if (IdxVal >= NumElems/2)
7447 // IdxVal -= NumElems/2;
7448 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7449 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7450 DAG.getConstant(IdxVal, MVT::i32));
7453 assert(VecVT.is128BitVector() && "Unexpected vector length");
7455 if (Subtarget->hasSSE41()) {
7456 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7461 MVT VT = Op.getValueType().getSimpleVT();
7462 // TODO: handle v16i8.
7463 if (VT.getSizeInBits() == 16) {
7464 SDValue Vec = Op.getOperand(0);
7465 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7467 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7468 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7469 DAG.getNode(ISD::BITCAST, dl,
7472 // Transform it so it match pextrw which produces a 32-bit result.
7473 MVT EltVT = MVT::i32;
7474 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7475 Op.getOperand(0), Op.getOperand(1));
7476 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7477 DAG.getValueType(VT));
7478 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7481 if (VT.getSizeInBits() == 32) {
7482 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7486 // SHUFPS the element to the lowest double word, then movss.
7487 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7488 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7489 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7490 DAG.getUNDEF(VVT), Mask);
7491 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7492 DAG.getIntPtrConstant(0));
7495 if (VT.getSizeInBits() == 64) {
7496 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7497 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7498 // to match extract_elt for f64.
7499 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7503 // UNPCKHPD the element to the lowest double word, then movsd.
7504 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7505 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7506 int Mask[2] = { 1, -1 };
7507 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7508 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7509 DAG.getUNDEF(VVT), Mask);
7510 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7511 DAG.getIntPtrConstant(0));
7517 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7518 MVT VT = Op.getValueType().getSimpleVT();
7519 MVT EltVT = VT.getVectorElementType();
7522 SDValue N0 = Op.getOperand(0);
7523 SDValue N1 = Op.getOperand(1);
7524 SDValue N2 = Op.getOperand(2);
7526 if (!VT.is128BitVector())
7529 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7530 isa<ConstantSDNode>(N2)) {
7532 if (VT == MVT::v8i16)
7533 Opc = X86ISD::PINSRW;
7534 else if (VT == MVT::v16i8)
7535 Opc = X86ISD::PINSRB;
7537 Opc = X86ISD::PINSRB;
7539 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7541 if (N1.getValueType() != MVT::i32)
7542 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7543 if (N2.getValueType() != MVT::i32)
7544 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7545 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7548 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7549 // Bits [7:6] of the constant are the source select. This will always be
7550 // zero here. The DAG Combiner may combine an extract_elt index into these
7551 // bits. For example (insert (extract, 3), 2) could be matched by putting
7552 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7553 // Bits [5:4] of the constant are the destination select. This is the
7554 // value of the incoming immediate.
7555 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7556 // combine either bitwise AND or insert of float 0.0 to set these bits.
7557 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7558 // Create this as a scalar to vector..
7559 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7560 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7563 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7564 // PINSR* works with constant index.
7571 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7572 MVT VT = Op.getValueType().getSimpleVT();
7573 MVT EltVT = VT.getVectorElementType();
7576 SDValue N0 = Op.getOperand(0);
7577 SDValue N1 = Op.getOperand(1);
7578 SDValue N2 = Op.getOperand(2);
7580 // If this is a 256-bit vector result, first extract the 128-bit vector,
7581 // insert the element into the extracted half and then place it back.
7582 if (VT.is256BitVector() || VT.is512BitVector()) {
7583 if (!isa<ConstantSDNode>(N2))
7586 // Get the desired 128-bit vector half.
7587 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7588 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7590 // Insert the element into the desired half.
7591 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7592 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7594 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7595 DAG.getConstant(IdxIn128, MVT::i32));
7597 // Insert the changed part back to the 256-bit vector
7598 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7601 if (Subtarget->hasSSE41())
7602 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7604 if (EltVT == MVT::i8)
7607 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7608 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7609 // as its second argument.
7610 if (N1.getValueType() != MVT::i32)
7611 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7612 if (N2.getValueType() != MVT::i32)
7613 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7614 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7619 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7620 LLVMContext *Context = DAG.getContext();
7622 MVT OpVT = Op.getValueType().getSimpleVT();
7624 // If this is a 256-bit vector result, first insert into a 128-bit
7625 // vector and then insert into the 256-bit vector.
7626 if (!OpVT.is128BitVector()) {
7627 // Insert into a 128-bit vector.
7628 unsigned SizeFactor = OpVT.getSizeInBits()/128;
7629 EVT VT128 = EVT::getVectorVT(*Context,
7630 OpVT.getVectorElementType(),
7631 OpVT.getVectorNumElements() / SizeFactor);
7633 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7635 // Insert the 128-bit vector.
7636 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7639 if (OpVT == MVT::v1i64 &&
7640 Op.getOperand(0).getValueType() == MVT::i64)
7641 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7643 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7644 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7645 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7646 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7649 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7650 // a simple subregister reference or explicit instructions to grab
7651 // upper bits of a vector.
7652 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7653 SelectionDAG &DAG) {
7655 SDValue In = Op.getOperand(0);
7656 SDValue Idx = Op.getOperand(1);
7657 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7658 EVT ResVT = Op.getValueType();
7659 EVT InVT = In.getValueType();
7661 if (Subtarget->hasFp256()) {
7662 if (ResVT.is128BitVector() &&
7663 (InVT.is256BitVector() || InVT.is512BitVector()) &&
7664 isa<ConstantSDNode>(Idx)) {
7665 return Extract128BitVector(In, IdxVal, DAG, dl);
7667 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7668 isa<ConstantSDNode>(Idx)) {
7669 return Extract256BitVector(In, IdxVal, DAG, dl);
7675 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7676 // simple superregister reference or explicit instructions to insert
7677 // the upper bits of a vector.
7678 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7679 SelectionDAG &DAG) {
7680 if (Subtarget->hasFp256()) {
7681 SDLoc dl(Op.getNode());
7682 SDValue Vec = Op.getNode()->getOperand(0);
7683 SDValue SubVec = Op.getNode()->getOperand(1);
7684 SDValue Idx = Op.getNode()->getOperand(2);
7686 if ((Op.getNode()->getValueType(0).is256BitVector() ||
7687 Op.getNode()->getValueType(0).is512BitVector()) &&
7688 SubVec.getNode()->getValueType(0).is128BitVector() &&
7689 isa<ConstantSDNode>(Idx)) {
7690 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7691 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7694 if (Op.getNode()->getValueType(0).is512BitVector() &&
7695 SubVec.getNode()->getValueType(0).is256BitVector() &&
7696 isa<ConstantSDNode>(Idx)) {
7697 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7698 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7704 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7705 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7706 // one of the above mentioned nodes. It has to be wrapped because otherwise
7707 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7708 // be used to form addressing mode. These wrapped nodes will be selected
7711 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7712 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7714 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7716 unsigned char OpFlag = 0;
7717 unsigned WrapperKind = X86ISD::Wrapper;
7718 CodeModel::Model M = getTargetMachine().getCodeModel();
7720 if (Subtarget->isPICStyleRIPRel() &&
7721 (M == CodeModel::Small || M == CodeModel::Kernel))
7722 WrapperKind = X86ISD::WrapperRIP;
7723 else if (Subtarget->isPICStyleGOT())
7724 OpFlag = X86II::MO_GOTOFF;
7725 else if (Subtarget->isPICStyleStubPIC())
7726 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7728 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7730 CP->getOffset(), OpFlag);
7732 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7733 // With PIC, the address is actually $g + Offset.
7735 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7736 DAG.getNode(X86ISD::GlobalBaseReg,
7737 SDLoc(), getPointerTy()),
7744 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7745 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7747 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7749 unsigned char OpFlag = 0;
7750 unsigned WrapperKind = X86ISD::Wrapper;
7751 CodeModel::Model M = getTargetMachine().getCodeModel();
7753 if (Subtarget->isPICStyleRIPRel() &&
7754 (M == CodeModel::Small || M == CodeModel::Kernel))
7755 WrapperKind = X86ISD::WrapperRIP;
7756 else if (Subtarget->isPICStyleGOT())
7757 OpFlag = X86II::MO_GOTOFF;
7758 else if (Subtarget->isPICStyleStubPIC())
7759 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7761 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7764 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7766 // With PIC, the address is actually $g + Offset.
7768 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7769 DAG.getNode(X86ISD::GlobalBaseReg,
7770 SDLoc(), getPointerTy()),
7777 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7778 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7780 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7782 unsigned char OpFlag = 0;
7783 unsigned WrapperKind = X86ISD::Wrapper;
7784 CodeModel::Model M = getTargetMachine().getCodeModel();
7786 if (Subtarget->isPICStyleRIPRel() &&
7787 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7788 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7789 OpFlag = X86II::MO_GOTPCREL;
7790 WrapperKind = X86ISD::WrapperRIP;
7791 } else if (Subtarget->isPICStyleGOT()) {
7792 OpFlag = X86II::MO_GOT;
7793 } else if (Subtarget->isPICStyleStubPIC()) {
7794 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7795 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7796 OpFlag = X86II::MO_DARWIN_NONLAZY;
7799 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7802 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7804 // With PIC, the address is actually $g + Offset.
7805 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7806 !Subtarget->is64Bit()) {
7807 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7808 DAG.getNode(X86ISD::GlobalBaseReg,
7809 SDLoc(), getPointerTy()),
7813 // For symbols that require a load from a stub to get the address, emit the
7815 if (isGlobalStubReference(OpFlag))
7816 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7817 MachinePointerInfo::getGOT(), false, false, false, 0);
7823 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7824 // Create the TargetBlockAddressAddress node.
7825 unsigned char OpFlags =
7826 Subtarget->ClassifyBlockAddressReference();
7827 CodeModel::Model M = getTargetMachine().getCodeModel();
7828 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7829 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7831 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7834 if (Subtarget->isPICStyleRIPRel() &&
7835 (M == CodeModel::Small || M == CodeModel::Kernel))
7836 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7838 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7840 // With PIC, the address is actually $g + Offset.
7841 if (isGlobalRelativeToPICBase(OpFlags)) {
7842 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7843 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7851 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7852 int64_t Offset, SelectionDAG &DAG) const {
7853 // Create the TargetGlobalAddress node, folding in the constant
7854 // offset if it is legal.
7855 unsigned char OpFlags =
7856 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7857 CodeModel::Model M = getTargetMachine().getCodeModel();
7859 if (OpFlags == X86II::MO_NO_FLAG &&
7860 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7861 // A direct static reference to a global.
7862 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7865 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7868 if (Subtarget->isPICStyleRIPRel() &&
7869 (M == CodeModel::Small || M == CodeModel::Kernel))
7870 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7872 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7874 // With PIC, the address is actually $g + Offset.
7875 if (isGlobalRelativeToPICBase(OpFlags)) {
7876 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7877 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7881 // For globals that require a load from a stub to get the address, emit the
7883 if (isGlobalStubReference(OpFlags))
7884 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7885 MachinePointerInfo::getGOT(), false, false, false, 0);
7887 // If there was a non-zero offset that we didn't fold, create an explicit
7890 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7891 DAG.getConstant(Offset, getPointerTy()));
7897 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7898 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7899 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7900 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7904 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7905 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7906 unsigned char OperandFlags, bool LocalDynamic = false) {
7907 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7908 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7910 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7911 GA->getValueType(0),
7915 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7919 SDValue Ops[] = { Chain, TGA, *InFlag };
7920 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7922 SDValue Ops[] = { Chain, TGA };
7923 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7926 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7927 MFI->setAdjustsStack(true);
7929 SDValue Flag = Chain.getValue(1);
7930 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7933 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7935 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7938 SDLoc dl(GA); // ? function entry point might be better
7939 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7940 DAG.getNode(X86ISD::GlobalBaseReg,
7941 SDLoc(), PtrVT), InFlag);
7942 InFlag = Chain.getValue(1);
7944 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7947 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7949 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7951 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7952 X86::RAX, X86II::MO_TLSGD);
7955 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7961 // Get the start address of the TLS block for this module.
7962 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7963 .getInfo<X86MachineFunctionInfo>();
7964 MFI->incNumLocalDynamicTLSAccesses();
7968 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7969 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7972 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7973 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7974 InFlag = Chain.getValue(1);
7975 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7976 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7979 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7983 unsigned char OperandFlags = X86II::MO_DTPOFF;
7984 unsigned WrapperKind = X86ISD::Wrapper;
7985 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7986 GA->getValueType(0),
7987 GA->getOffset(), OperandFlags);
7988 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7990 // Add x@dtpoff with the base.
7991 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7994 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7995 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7996 const EVT PtrVT, TLSModel::Model model,
7997 bool is64Bit, bool isPIC) {
8000 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8001 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8002 is64Bit ? 257 : 256));
8004 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8005 DAG.getIntPtrConstant(0),
8006 MachinePointerInfo(Ptr),
8007 false, false, false, 0);
8009 unsigned char OperandFlags = 0;
8010 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8012 unsigned WrapperKind = X86ISD::Wrapper;
8013 if (model == TLSModel::LocalExec) {
8014 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8015 } else if (model == TLSModel::InitialExec) {
8017 OperandFlags = X86II::MO_GOTTPOFF;
8018 WrapperKind = X86ISD::WrapperRIP;
8020 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8023 llvm_unreachable("Unexpected model");
8026 // emit "addl x@ntpoff,%eax" (local exec)
8027 // or "addl x@indntpoff,%eax" (initial exec)
8028 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8029 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8030 GA->getValueType(0),
8031 GA->getOffset(), OperandFlags);
8032 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8034 if (model == TLSModel::InitialExec) {
8035 if (isPIC && !is64Bit) {
8036 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8037 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8041 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8042 MachinePointerInfo::getGOT(), false, false, false,
8046 // The address of the thread local variable is the add of the thread
8047 // pointer with the offset of the variable.
8048 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8052 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8054 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8055 const GlobalValue *GV = GA->getGlobal();
8057 if (Subtarget->isTargetELF()) {
8058 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8061 case TLSModel::GeneralDynamic:
8062 if (Subtarget->is64Bit())
8063 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8064 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8065 case TLSModel::LocalDynamic:
8066 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8067 Subtarget->is64Bit());
8068 case TLSModel::InitialExec:
8069 case TLSModel::LocalExec:
8070 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8071 Subtarget->is64Bit(),
8072 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8074 llvm_unreachable("Unknown TLS model.");
8077 if (Subtarget->isTargetDarwin()) {
8078 // Darwin only has one model of TLS. Lower to that.
8079 unsigned char OpFlag = 0;
8080 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8081 X86ISD::WrapperRIP : X86ISD::Wrapper;
8083 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8085 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8086 !Subtarget->is64Bit();
8088 OpFlag = X86II::MO_TLVP_PIC_BASE;
8090 OpFlag = X86II::MO_TLVP;
8092 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8093 GA->getValueType(0),
8094 GA->getOffset(), OpFlag);
8095 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8097 // With PIC32, the address is actually $g + Offset.
8099 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8100 DAG.getNode(X86ISD::GlobalBaseReg,
8101 SDLoc(), getPointerTy()),
8104 // Lowering the machine isd will make sure everything is in the right
8106 SDValue Chain = DAG.getEntryNode();
8107 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8108 SDValue Args[] = { Chain, Offset };
8109 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8111 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8112 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8113 MFI->setAdjustsStack(true);
8115 // And our return value (tls address) is in the standard call return value
8117 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8118 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8122 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8123 // Just use the implicit TLS architecture
8124 // Need to generate someting similar to:
8125 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8127 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8128 // mov rcx, qword [rdx+rcx*8]
8129 // mov eax, .tls$:tlsvar
8130 // [rax+rcx] contains the address
8131 // Windows 64bit: gs:0x58
8132 // Windows 32bit: fs:__tls_array
8134 // If GV is an alias then use the aliasee for determining
8135 // thread-localness.
8136 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8137 GV = GA->resolveAliasedGlobal(false);
8139 SDValue Chain = DAG.getEntryNode();
8141 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8142 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8143 // use its literal value of 0x2C.
8144 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8145 ? Type::getInt8PtrTy(*DAG.getContext(),
8147 : Type::getInt32PtrTy(*DAG.getContext(),
8150 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8151 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8152 DAG.getExternalSymbol("_tls_array", getPointerTy()));
8154 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8155 MachinePointerInfo(Ptr),
8156 false, false, false, 0);
8158 // Load the _tls_index variable
8159 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8160 if (Subtarget->is64Bit())
8161 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8162 IDX, MachinePointerInfo(), MVT::i32,
8165 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8166 false, false, false, 0);
8168 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8170 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8172 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8173 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8174 false, false, false, 0);
8176 // Get the offset of start of .tls section
8177 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8178 GA->getValueType(0),
8179 GA->getOffset(), X86II::MO_SECREL);
8180 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8182 // The address of the thread local variable is the add of the thread
8183 // pointer with the offset of the variable.
8184 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8187 llvm_unreachable("TLS not implemented for this target.");
8190 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8191 /// and take a 2 x i32 value to shift plus a shift amount.
8192 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8193 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8194 EVT VT = Op.getValueType();
8195 unsigned VTBits = VT.getSizeInBits();
8197 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8198 SDValue ShOpLo = Op.getOperand(0);
8199 SDValue ShOpHi = Op.getOperand(1);
8200 SDValue ShAmt = Op.getOperand(2);
8201 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8202 DAG.getConstant(VTBits - 1, MVT::i8))
8203 : DAG.getConstant(0, VT);
8206 if (Op.getOpcode() == ISD::SHL_PARTS) {
8207 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8208 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8210 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8211 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8214 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8215 DAG.getConstant(VTBits, MVT::i8));
8216 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8217 AndNode, DAG.getConstant(0, MVT::i8));
8220 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8221 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8222 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8224 if (Op.getOpcode() == ISD::SHL_PARTS) {
8225 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8226 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8228 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8229 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8232 SDValue Ops[2] = { Lo, Hi };
8233 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8236 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8237 SelectionDAG &DAG) const {
8238 EVT SrcVT = Op.getOperand(0).getValueType();
8240 if (SrcVT.isVector())
8243 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8244 "Unknown SINT_TO_FP to lower!");
8246 // These are really Legal; return the operand so the caller accepts it as
8248 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8250 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8251 Subtarget->is64Bit()) {
8256 unsigned Size = SrcVT.getSizeInBits()/8;
8257 MachineFunction &MF = DAG.getMachineFunction();
8258 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8259 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8260 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8262 MachinePointerInfo::getFixedStack(SSFI),
8264 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8267 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8269 SelectionDAG &DAG) const {
8273 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8275 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8277 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8279 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8281 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8282 MachineMemOperand *MMO;
8284 int SSFI = FI->getIndex();
8286 DAG.getMachineFunction()
8287 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8288 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8290 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8291 StackSlot = StackSlot.getOperand(1);
8293 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8294 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8296 Tys, Ops, array_lengthof(Ops),
8300 Chain = Result.getValue(1);
8301 SDValue InFlag = Result.getValue(2);
8303 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8304 // shouldn't be necessary except that RFP cannot be live across
8305 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8306 MachineFunction &MF = DAG.getMachineFunction();
8307 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8308 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8309 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8310 Tys = DAG.getVTList(MVT::Other);
8312 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8314 MachineMemOperand *MMO =
8315 DAG.getMachineFunction()
8316 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8317 MachineMemOperand::MOStore, SSFISize, SSFISize);
8319 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8320 Ops, array_lengthof(Ops),
8321 Op.getValueType(), MMO);
8322 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8323 MachinePointerInfo::getFixedStack(SSFI),
8324 false, false, false, 0);
8330 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8331 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8332 SelectionDAG &DAG) const {
8333 // This algorithm is not obvious. Here it is what we're trying to output:
8336 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8337 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8341 pshufd $0x4e, %xmm0, %xmm1
8347 LLVMContext *Context = DAG.getContext();
8349 // Build some magic constants.
8350 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8351 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8352 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8354 SmallVector<Constant*,2> CV1;
8356 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8357 APInt(64, 0x4330000000000000ULL))));
8359 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8360 APInt(64, 0x4530000000000000ULL))));
8361 Constant *C1 = ConstantVector::get(CV1);
8362 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8364 // Load the 64-bit value into an XMM register.
8365 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8367 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8368 MachinePointerInfo::getConstantPool(),
8369 false, false, false, 16);
8370 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8371 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8374 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8375 MachinePointerInfo::getConstantPool(),
8376 false, false, false, 16);
8377 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8378 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8381 if (Subtarget->hasSSE3()) {
8382 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8383 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8385 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8386 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8388 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8389 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8393 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8394 DAG.getIntPtrConstant(0));
8397 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8398 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8399 SelectionDAG &DAG) const {
8401 // FP constant to bias correct the final result.
8402 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8405 // Load the 32-bit value into an XMM register.
8406 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8409 // Zero out the upper parts of the register.
8410 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8412 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8413 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8414 DAG.getIntPtrConstant(0));
8416 // Or the load with the bias.
8417 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8418 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8419 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8421 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8422 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8423 MVT::v2f64, Bias)));
8424 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8425 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8426 DAG.getIntPtrConstant(0));
8428 // Subtract the bias.
8429 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8431 // Handle final rounding.
8432 EVT DestVT = Op.getValueType();
8434 if (DestVT.bitsLT(MVT::f64))
8435 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8436 DAG.getIntPtrConstant(0));
8437 if (DestVT.bitsGT(MVT::f64))
8438 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8440 // Handle final rounding.
8444 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8445 SelectionDAG &DAG) const {
8446 SDValue N0 = Op.getOperand(0);
8447 EVT SVT = N0.getValueType();
8450 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8451 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8452 "Custom UINT_TO_FP is not supported!");
8454 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8455 SVT.getVectorNumElements());
8456 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8457 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8460 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8461 SelectionDAG &DAG) const {
8462 SDValue N0 = Op.getOperand(0);
8465 if (Op.getValueType().isVector())
8466 return lowerUINT_TO_FP_vec(Op, DAG);
8468 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8469 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8470 // the optimization here.
8471 if (DAG.SignBitIsZero(N0))
8472 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8474 EVT SrcVT = N0.getValueType();
8475 EVT DstVT = Op.getValueType();
8476 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8477 return LowerUINT_TO_FP_i64(Op, DAG);
8478 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8479 return LowerUINT_TO_FP_i32(Op, DAG);
8480 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8483 // Make a 64-bit buffer, and use it to build an FILD.
8484 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8485 if (SrcVT == MVT::i32) {
8486 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8487 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8488 getPointerTy(), StackSlot, WordOff);
8489 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8490 StackSlot, MachinePointerInfo(),
8492 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8493 OffsetSlot, MachinePointerInfo(),
8495 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8499 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8500 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8501 StackSlot, MachinePointerInfo(),
8503 // For i64 source, we need to add the appropriate power of 2 if the input
8504 // was negative. This is the same as the optimization in
8505 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8506 // we must be careful to do the computation in x87 extended precision, not
8507 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8508 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8509 MachineMemOperand *MMO =
8510 DAG.getMachineFunction()
8511 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8512 MachineMemOperand::MOLoad, 8, 8);
8514 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8515 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8516 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8517 array_lengthof(Ops), MVT::i64, MMO);
8519 APInt FF(32, 0x5F800000ULL);
8521 // Check whether the sign bit is set.
8522 SDValue SignSet = DAG.getSetCC(dl,
8523 getSetCCResultType(*DAG.getContext(), MVT::i64),
8524 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8527 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8528 SDValue FudgePtr = DAG.getConstantPool(
8529 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8532 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8533 SDValue Zero = DAG.getIntPtrConstant(0);
8534 SDValue Four = DAG.getIntPtrConstant(4);
8535 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8537 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8539 // Load the value out, extending it from f32 to f80.
8540 // FIXME: Avoid the extend by constructing the right constant pool?
8541 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8542 FudgePtr, MachinePointerInfo::getConstantPool(),
8543 MVT::f32, false, false, 4);
8544 // Extend everything to 80 bits to force it to be done on x87.
8545 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8546 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8549 std::pair<SDValue,SDValue>
8550 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8551 bool IsSigned, bool IsReplace) const {
8554 EVT DstTy = Op.getValueType();
8556 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8557 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8561 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8562 DstTy.getSimpleVT() >= MVT::i16 &&
8563 "Unknown FP_TO_INT to lower!");
8565 // These are really Legal.
8566 if (DstTy == MVT::i32 &&
8567 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8568 return std::make_pair(SDValue(), SDValue());
8569 if (Subtarget->is64Bit() &&
8570 DstTy == MVT::i64 &&
8571 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8572 return std::make_pair(SDValue(), SDValue());
8574 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8575 // stack slot, or into the FTOL runtime function.
8576 MachineFunction &MF = DAG.getMachineFunction();
8577 unsigned MemSize = DstTy.getSizeInBits()/8;
8578 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8579 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8582 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8583 Opc = X86ISD::WIN_FTOL;
8585 switch (DstTy.getSimpleVT().SimpleTy) {
8586 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8587 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8588 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8589 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8592 SDValue Chain = DAG.getEntryNode();
8593 SDValue Value = Op.getOperand(0);
8594 EVT TheVT = Op.getOperand(0).getValueType();
8595 // FIXME This causes a redundant load/store if the SSE-class value is already
8596 // in memory, such as if it is on the callstack.
8597 if (isScalarFPTypeInSSEReg(TheVT)) {
8598 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8599 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8600 MachinePointerInfo::getFixedStack(SSFI),
8602 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8604 Chain, StackSlot, DAG.getValueType(TheVT)
8607 MachineMemOperand *MMO =
8608 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8609 MachineMemOperand::MOLoad, MemSize, MemSize);
8610 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8611 array_lengthof(Ops), DstTy, MMO);
8612 Chain = Value.getValue(1);
8613 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8614 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8617 MachineMemOperand *MMO =
8618 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8619 MachineMemOperand::MOStore, MemSize, MemSize);
8621 if (Opc != X86ISD::WIN_FTOL) {
8622 // Build the FP_TO_INT*_IN_MEM
8623 SDValue Ops[] = { Chain, Value, StackSlot };
8624 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8625 Ops, array_lengthof(Ops), DstTy,
8627 return std::make_pair(FIST, StackSlot);
8629 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8630 DAG.getVTList(MVT::Other, MVT::Glue),
8632 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8633 MVT::i32, ftol.getValue(1));
8634 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8635 MVT::i32, eax.getValue(2));
8636 SDValue Ops[] = { eax, edx };
8637 SDValue pair = IsReplace
8638 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8639 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8640 return std::make_pair(pair, SDValue());
8644 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8645 const X86Subtarget *Subtarget) {
8646 MVT VT = Op->getValueType(0).getSimpleVT();
8647 SDValue In = Op->getOperand(0);
8648 MVT InVT = In.getValueType().getSimpleVT();
8651 // Optimize vectors in AVX mode:
8654 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8655 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8656 // Concat upper and lower parts.
8659 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8660 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8661 // Concat upper and lower parts.
8664 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8665 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8668 if (Subtarget->hasInt256())
8669 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8671 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8672 SDValue Undef = DAG.getUNDEF(InVT);
8673 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8674 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8675 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8677 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8678 VT.getVectorNumElements()/2);
8680 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8681 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8683 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8686 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8687 SelectionDAG &DAG) const {
8688 if (Subtarget->hasFp256()) {
8689 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8696 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8697 SelectionDAG &DAG) const {
8699 MVT VT = Op.getValueType().getSimpleVT();
8700 SDValue In = Op.getOperand(0);
8701 MVT SVT = In.getValueType().getSimpleVT();
8703 if (Subtarget->hasFp256()) {
8704 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8709 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8710 VT.getVectorNumElements() != SVT.getVectorNumElements())
8713 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8715 // AVX2 has better support of integer extending.
8716 if (Subtarget->hasInt256())
8717 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8719 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8720 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8721 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8722 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8723 DAG.getUNDEF(MVT::v8i16),
8726 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8729 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8731 MVT VT = Op.getValueType().getSimpleVT();
8732 SDValue In = Op.getOperand(0);
8733 MVT SVT = In.getValueType().getSimpleVT();
8735 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8736 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8737 if (Subtarget->hasInt256()) {
8738 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8739 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8740 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8742 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8743 DAG.getIntPtrConstant(0));
8746 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8747 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8748 DAG.getIntPtrConstant(0));
8749 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8750 DAG.getIntPtrConstant(2));
8752 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8753 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8756 static const int ShufMask1[] = {0, 2, 0, 0};
8757 SDValue Undef = DAG.getUNDEF(VT);
8758 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8759 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8761 // The MOVLHPS mask:
8762 static const int ShufMask2[] = {0, 1, 4, 5};
8763 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8766 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8767 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8768 if (Subtarget->hasInt256()) {
8769 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8771 SmallVector<SDValue,32> pshufbMask;
8772 for (unsigned i = 0; i < 2; ++i) {
8773 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8774 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8775 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8776 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8777 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8778 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8779 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8780 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8781 for (unsigned j = 0; j < 8; ++j)
8782 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8784 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8785 &pshufbMask[0], 32);
8786 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8787 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8789 static const int ShufMask[] = {0, 2, -1, -1};
8790 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8792 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8793 DAG.getIntPtrConstant(0));
8794 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8797 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8798 DAG.getIntPtrConstant(0));
8800 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8801 DAG.getIntPtrConstant(4));
8803 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8804 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8807 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8808 -1, -1, -1, -1, -1, -1, -1, -1};
8810 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8811 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8812 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8814 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8815 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8817 // The MOVLHPS Mask:
8818 static const int ShufMask2[] = {0, 1, 4, 5};
8819 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8820 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8823 // Handle truncation of V256 to V128 using shuffles.
8824 if (!VT.is128BitVector() || !SVT.is256BitVector())
8827 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8829 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8831 unsigned NumElems = VT.getVectorNumElements();
8832 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8835 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8836 // Prepare truncation shuffle mask
8837 for (unsigned i = 0; i != NumElems; ++i)
8839 SDValue V = DAG.getVectorShuffle(NVT, DL,
8840 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8841 DAG.getUNDEF(NVT), &MaskVec[0]);
8842 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8843 DAG.getIntPtrConstant(0));
8846 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8847 SelectionDAG &DAG) const {
8848 MVT VT = Op.getValueType().getSimpleVT();
8849 if (VT.isVector()) {
8850 if (VT == MVT::v8i16)
8851 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8852 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8853 MVT::v8i32, Op.getOperand(0)));
8857 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8858 /*IsSigned=*/ true, /*IsReplace=*/ false);
8859 SDValue FIST = Vals.first, StackSlot = Vals.second;
8860 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8861 if (FIST.getNode() == 0) return Op;
8863 if (StackSlot.getNode())
8865 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8866 FIST, StackSlot, MachinePointerInfo(),
8867 false, false, false, 0);
8869 // The node is the result.
8873 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8874 SelectionDAG &DAG) const {
8875 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8876 /*IsSigned=*/ false, /*IsReplace=*/ false);
8877 SDValue FIST = Vals.first, StackSlot = Vals.second;
8878 assert(FIST.getNode() && "Unexpected failure");
8880 if (StackSlot.getNode())
8882 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8883 FIST, StackSlot, MachinePointerInfo(),
8884 false, false, false, 0);
8886 // The node is the result.
8890 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8892 MVT VT = Op.getValueType().getSimpleVT();
8893 SDValue In = Op.getOperand(0);
8894 MVT SVT = In.getValueType().getSimpleVT();
8896 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8898 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8899 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8900 In, DAG.getUNDEF(SVT)));
8903 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8904 LLVMContext *Context = DAG.getContext();
8906 MVT VT = Op.getValueType().getSimpleVT();
8908 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8909 if (VT.isVector()) {
8910 EltVT = VT.getVectorElementType();
8911 NumElts = VT.getVectorNumElements();
8914 if (EltVT == MVT::f64)
8915 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8916 APInt(64, ~(1ULL << 63))));
8918 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8919 APInt(32, ~(1U << 31))));
8920 C = ConstantVector::getSplat(NumElts, C);
8921 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8922 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8923 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8924 MachinePointerInfo::getConstantPool(),
8925 false, false, false, Alignment);
8926 if (VT.isVector()) {
8927 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8928 return DAG.getNode(ISD::BITCAST, dl, VT,
8929 DAG.getNode(ISD::AND, dl, ANDVT,
8930 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8932 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8934 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8937 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8938 LLVMContext *Context = DAG.getContext();
8940 MVT VT = Op.getValueType().getSimpleVT();
8942 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8943 if (VT.isVector()) {
8944 EltVT = VT.getVectorElementType();
8945 NumElts = VT.getVectorNumElements();
8948 if (EltVT == MVT::f64)
8949 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8950 APInt(64, 1ULL << 63)));
8952 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8953 APInt(32, 1U << 31)));
8954 C = ConstantVector::getSplat(NumElts, C);
8955 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8956 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8957 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8958 MachinePointerInfo::getConstantPool(),
8959 false, false, false, Alignment);
8960 if (VT.isVector()) {
8961 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8962 return DAG.getNode(ISD::BITCAST, dl, VT,
8963 DAG.getNode(ISD::XOR, dl, XORVT,
8964 DAG.getNode(ISD::BITCAST, dl, XORVT,
8966 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8969 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8972 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8973 LLVMContext *Context = DAG.getContext();
8974 SDValue Op0 = Op.getOperand(0);
8975 SDValue Op1 = Op.getOperand(1);
8977 MVT VT = Op.getValueType().getSimpleVT();
8978 MVT SrcVT = Op1.getValueType().getSimpleVT();
8980 // If second operand is smaller, extend it first.
8981 if (SrcVT.bitsLT(VT)) {
8982 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8985 // And if it is bigger, shrink it first.
8986 if (SrcVT.bitsGT(VT)) {
8987 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8991 // At this point the operands and the result should have the same
8992 // type, and that won't be f80 since that is not custom lowered.
8994 // First get the sign bit of second operand.
8995 SmallVector<Constant*,4> CV;
8996 if (SrcVT == MVT::f64) {
8997 const fltSemantics &Sem = APFloat::IEEEdouble;
8998 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8999 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9001 const fltSemantics &Sem = APFloat::IEEEsingle;
9002 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9003 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9004 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9005 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9007 Constant *C = ConstantVector::get(CV);
9008 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9009 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9010 MachinePointerInfo::getConstantPool(),
9011 false, false, false, 16);
9012 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9014 // Shift sign bit right or left if the two operands have different types.
9015 if (SrcVT.bitsGT(VT)) {
9016 // Op0 is MVT::f32, Op1 is MVT::f64.
9017 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9018 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9019 DAG.getConstant(32, MVT::i32));
9020 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9021 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9022 DAG.getIntPtrConstant(0));
9025 // Clear first operand sign bit.
9027 if (VT == MVT::f64) {
9028 const fltSemantics &Sem = APFloat::IEEEdouble;
9029 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9030 APInt(64, ~(1ULL << 63)))));
9031 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9033 const fltSemantics &Sem = APFloat::IEEEsingle;
9034 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9035 APInt(32, ~(1U << 31)))));
9036 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9037 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9038 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9040 C = ConstantVector::get(CV);
9041 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9042 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9043 MachinePointerInfo::getConstantPool(),
9044 false, false, false, 16);
9045 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9047 // Or the value with the sign bit.
9048 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9051 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9052 SDValue N0 = Op.getOperand(0);
9054 MVT VT = Op.getValueType().getSimpleVT();
9056 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9057 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9058 DAG.getConstant(1, VT));
9059 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9062 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9064 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9065 SelectionDAG &DAG) const {
9066 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9068 if (!Subtarget->hasSSE41())
9071 if (!Op->hasOneUse())
9074 SDNode *N = Op.getNode();
9077 SmallVector<SDValue, 8> Opnds;
9078 DenseMap<SDValue, unsigned> VecInMap;
9079 EVT VT = MVT::Other;
9081 // Recognize a special case where a vector is casted into wide integer to
9083 Opnds.push_back(N->getOperand(0));
9084 Opnds.push_back(N->getOperand(1));
9086 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9087 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9088 // BFS traverse all OR'd operands.
9089 if (I->getOpcode() == ISD::OR) {
9090 Opnds.push_back(I->getOperand(0));
9091 Opnds.push_back(I->getOperand(1));
9092 // Re-evaluate the number of nodes to be traversed.
9093 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9097 // Quit if a non-EXTRACT_VECTOR_ELT
9098 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9101 // Quit if without a constant index.
9102 SDValue Idx = I->getOperand(1);
9103 if (!isa<ConstantSDNode>(Idx))
9106 SDValue ExtractedFromVec = I->getOperand(0);
9107 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9108 if (M == VecInMap.end()) {
9109 VT = ExtractedFromVec.getValueType();
9110 // Quit if not 128/256-bit vector.
9111 if (!VT.is128BitVector() && !VT.is256BitVector())
9113 // Quit if not the same type.
9114 if (VecInMap.begin() != VecInMap.end() &&
9115 VT != VecInMap.begin()->first.getValueType())
9117 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9119 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9122 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9123 "Not extracted from 128-/256-bit vector.");
9125 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9126 SmallVector<SDValue, 8> VecIns;
9128 for (DenseMap<SDValue, unsigned>::const_iterator
9129 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9130 // Quit if not all elements are used.
9131 if (I->second != FullMask)
9133 VecIns.push_back(I->first);
9136 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9138 // Cast all vectors into TestVT for PTEST.
9139 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9140 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9142 // If more than one full vectors are evaluated, OR them first before PTEST.
9143 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9144 // Each iteration will OR 2 nodes and append the result until there is only
9145 // 1 node left, i.e. the final OR'd value of all vectors.
9146 SDValue LHS = VecIns[Slot];
9147 SDValue RHS = VecIns[Slot + 1];
9148 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9151 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9152 VecIns.back(), VecIns.back());
9155 /// Emit nodes that will be selected as "test Op0,Op0", or something
9157 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9158 SelectionDAG &DAG) const {
9161 // CF and OF aren't always set the way we want. Determine which
9162 // of these we need.
9163 bool NeedCF = false;
9164 bool NeedOF = false;
9167 case X86::COND_A: case X86::COND_AE:
9168 case X86::COND_B: case X86::COND_BE:
9171 case X86::COND_G: case X86::COND_GE:
9172 case X86::COND_L: case X86::COND_LE:
9173 case X86::COND_O: case X86::COND_NO:
9178 // See if we can use the EFLAGS value from the operand instead of
9179 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9180 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9181 if (Op.getResNo() != 0 || NeedOF || NeedCF)
9182 // Emit a CMP with 0, which is the TEST pattern.
9183 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9184 DAG.getConstant(0, Op.getValueType()));
9186 unsigned Opcode = 0;
9187 unsigned NumOperands = 0;
9189 // Truncate operations may prevent the merge of the SETCC instruction
9190 // and the arithmetic intruction before it. Attempt to truncate the operands
9191 // of the arithmetic instruction and use a reduced bit-width instruction.
9192 bool NeedTruncation = false;
9193 SDValue ArithOp = Op;
9194 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9195 SDValue Arith = Op->getOperand(0);
9196 // Both the trunc and the arithmetic op need to have one user each.
9197 if (Arith->hasOneUse())
9198 switch (Arith.getOpcode()) {
9205 NeedTruncation = true;
9211 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9212 // which may be the result of a CAST. We use the variable 'Op', which is the
9213 // non-casted variable when we check for possible users.
9214 switch (ArithOp.getOpcode()) {
9216 // Due to an isel shortcoming, be conservative if this add is likely to be
9217 // selected as part of a load-modify-store instruction. When the root node
9218 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9219 // uses of other nodes in the match, such as the ADD in this case. This
9220 // leads to the ADD being left around and reselected, with the result being
9221 // two adds in the output. Alas, even if none our users are stores, that
9222 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9223 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9224 // climbing the DAG back to the root, and it doesn't seem to be worth the
9226 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9227 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9228 if (UI->getOpcode() != ISD::CopyToReg &&
9229 UI->getOpcode() != ISD::SETCC &&
9230 UI->getOpcode() != ISD::STORE)
9233 if (ConstantSDNode *C =
9234 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9235 // An add of one will be selected as an INC.
9236 if (C->getAPIntValue() == 1) {
9237 Opcode = X86ISD::INC;
9242 // An add of negative one (subtract of one) will be selected as a DEC.
9243 if (C->getAPIntValue().isAllOnesValue()) {
9244 Opcode = X86ISD::DEC;
9250 // Otherwise use a regular EFLAGS-setting add.
9251 Opcode = X86ISD::ADD;
9255 // If the primary and result isn't used, don't bother using X86ISD::AND,
9256 // because a TEST instruction will be better.
9257 bool NonFlagUse = false;
9258 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9259 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9261 unsigned UOpNo = UI.getOperandNo();
9262 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9263 // Look pass truncate.
9264 UOpNo = User->use_begin().getOperandNo();
9265 User = *User->use_begin();
9268 if (User->getOpcode() != ISD::BRCOND &&
9269 User->getOpcode() != ISD::SETCC &&
9270 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9283 // Due to the ISEL shortcoming noted above, be conservative if this op is
9284 // likely to be selected as part of a load-modify-store instruction.
9285 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9286 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9287 if (UI->getOpcode() == ISD::STORE)
9290 // Otherwise use a regular EFLAGS-setting instruction.
9291 switch (ArithOp.getOpcode()) {
9292 default: llvm_unreachable("unexpected operator!");
9293 case ISD::SUB: Opcode = X86ISD::SUB; break;
9294 case ISD::XOR: Opcode = X86ISD::XOR; break;
9295 case ISD::AND: Opcode = X86ISD::AND; break;
9297 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9298 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9299 if (EFLAGS.getNode())
9302 Opcode = X86ISD::OR;
9316 return SDValue(Op.getNode(), 1);
9322 // If we found that truncation is beneficial, perform the truncation and
9324 if (NeedTruncation) {
9325 EVT VT = Op.getValueType();
9326 SDValue WideVal = Op->getOperand(0);
9327 EVT WideVT = WideVal.getValueType();
9328 unsigned ConvertedOp = 0;
9329 // Use a target machine opcode to prevent further DAGCombine
9330 // optimizations that may separate the arithmetic operations
9331 // from the setcc node.
9332 switch (WideVal.getOpcode()) {
9334 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9335 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9336 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9337 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9338 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9342 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9343 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9344 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9345 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9346 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9352 // Emit a CMP with 0, which is the TEST pattern.
9353 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9354 DAG.getConstant(0, Op.getValueType()));
9356 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9357 SmallVector<SDValue, 4> Ops;
9358 for (unsigned i = 0; i != NumOperands; ++i)
9359 Ops.push_back(Op.getOperand(i));
9361 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9362 DAG.ReplaceAllUsesWith(Op, New);
9363 return SDValue(New.getNode(), 1);
9366 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9368 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9369 SelectionDAG &DAG) const {
9370 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9371 if (C->getAPIntValue() == 0)
9372 return EmitTest(Op0, X86CC, DAG);
9375 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9376 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9377 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9378 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9379 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9381 return SDValue(Sub.getNode(), 1);
9383 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9386 /// Convert a comparison if required by the subtarget.
9387 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9388 SelectionDAG &DAG) const {
9389 // If the subtarget does not support the FUCOMI instruction, floating-point
9390 // comparisons have to be converted.
9391 if (Subtarget->hasCMov() ||
9392 Cmp.getOpcode() != X86ISD::CMP ||
9393 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9394 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9397 // The instruction selector will select an FUCOM instruction instead of
9398 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9399 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9400 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9402 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9403 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9404 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9405 DAG.getConstant(8, MVT::i8));
9406 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9407 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9410 static bool isAllOnes(SDValue V) {
9411 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9412 return C && C->isAllOnesValue();
9415 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9416 /// if it's possible.
9417 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9418 SDLoc dl, SelectionDAG &DAG) const {
9419 SDValue Op0 = And.getOperand(0);
9420 SDValue Op1 = And.getOperand(1);
9421 if (Op0.getOpcode() == ISD::TRUNCATE)
9422 Op0 = Op0.getOperand(0);
9423 if (Op1.getOpcode() == ISD::TRUNCATE)
9424 Op1 = Op1.getOperand(0);
9427 if (Op1.getOpcode() == ISD::SHL)
9428 std::swap(Op0, Op1);
9429 if (Op0.getOpcode() == ISD::SHL) {
9430 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9431 if (And00C->getZExtValue() == 1) {
9432 // If we looked past a truncate, check that it's only truncating away
9434 unsigned BitWidth = Op0.getValueSizeInBits();
9435 unsigned AndBitWidth = And.getValueSizeInBits();
9436 if (BitWidth > AndBitWidth) {
9438 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9439 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9443 RHS = Op0.getOperand(1);
9445 } else if (Op1.getOpcode() == ISD::Constant) {
9446 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9447 uint64_t AndRHSVal = AndRHS->getZExtValue();
9448 SDValue AndLHS = Op0;
9450 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9451 LHS = AndLHS.getOperand(0);
9452 RHS = AndLHS.getOperand(1);
9455 // Use BT if the immediate can't be encoded in a TEST instruction.
9456 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9458 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9462 if (LHS.getNode()) {
9463 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9464 // instruction. Since the shift amount is in-range-or-undefined, we know
9465 // that doing a bittest on the i32 value is ok. We extend to i32 because
9466 // the encoding for the i16 version is larger than the i32 version.
9467 // Also promote i16 to i32 for performance / code size reason.
9468 if (LHS.getValueType() == MVT::i8 ||
9469 LHS.getValueType() == MVT::i16)
9470 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9472 // If the operand types disagree, extend the shift amount to match. Since
9473 // BT ignores high bits (like shifts) we can use anyextend.
9474 if (LHS.getValueType() != RHS.getValueType())
9475 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9477 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9478 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9479 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9480 DAG.getConstant(Cond, MVT::i8), BT);
9486 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9487 // ones, and then concatenate the result back.
9488 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9489 MVT VT = Op.getValueType().getSimpleVT();
9491 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9492 "Unsupported value type for operation");
9494 unsigned NumElems = VT.getVectorNumElements();
9496 SDValue CC = Op.getOperand(2);
9498 // Extract the LHS vectors
9499 SDValue LHS = Op.getOperand(0);
9500 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9501 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9503 // Extract the RHS vectors
9504 SDValue RHS = Op.getOperand(1);
9505 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9506 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9508 // Issue the operation on the smaller types and concatenate the result back
9509 MVT EltVT = VT.getVectorElementType();
9510 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9511 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9512 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9513 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9516 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9517 SelectionDAG &DAG) {
9519 SDValue Op0 = Op.getOperand(0);
9520 SDValue Op1 = Op.getOperand(1);
9521 SDValue CC = Op.getOperand(2);
9522 MVT VT = Op.getValueType().getSimpleVT();
9523 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9524 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9529 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9530 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9536 // SSE Condition code mapping:
9545 switch (SetCCOpcode) {
9546 default: llvm_unreachable("Unexpected SETCC condition");
9548 case ISD::SETEQ: SSECC = 0; break;
9550 case ISD::SETGT: Swap = true; // Fallthrough
9552 case ISD::SETOLT: SSECC = 1; break;
9554 case ISD::SETGE: Swap = true; // Fallthrough
9556 case ISD::SETOLE: SSECC = 2; break;
9557 case ISD::SETUO: SSECC = 3; break;
9559 case ISD::SETNE: SSECC = 4; break;
9560 case ISD::SETULE: Swap = true; // Fallthrough
9561 case ISD::SETUGE: SSECC = 5; break;
9562 case ISD::SETULT: Swap = true; // Fallthrough
9563 case ISD::SETUGT: SSECC = 6; break;
9564 case ISD::SETO: SSECC = 7; break;
9566 case ISD::SETONE: SSECC = 8; break;
9569 std::swap(Op0, Op1);
9571 // In the two special cases we can't handle, emit two comparisons.
9574 unsigned CombineOpc;
9575 if (SetCCOpcode == ISD::SETUEQ) {
9576 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9578 assert(SetCCOpcode == ISD::SETONE);
9579 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9582 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9583 DAG.getConstant(CC0, MVT::i8));
9584 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9585 DAG.getConstant(CC1, MVT::i8));
9586 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9588 // Handle all other FP comparisons here.
9589 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9590 DAG.getConstant(SSECC, MVT::i8));
9593 // Break 256-bit integer vector compare into smaller ones.
9594 if (VT.is256BitVector() && !Subtarget->hasInt256())
9595 return Lower256IntVSETCC(Op, DAG);
9597 // We are handling one of the integer comparisons here. Since SSE only has
9598 // GT and EQ comparisons for integer, swapping operands and multiple
9599 // operations may be required for some comparisons.
9601 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9603 switch (SetCCOpcode) {
9604 default: llvm_unreachable("Unexpected SETCC condition");
9605 case ISD::SETNE: Invert = true;
9606 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9607 case ISD::SETLT: Swap = true;
9608 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9609 case ISD::SETGE: Swap = true;
9610 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9611 case ISD::SETULT: Swap = true;
9612 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9613 case ISD::SETUGE: Swap = true;
9614 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9617 // Special case: Use min/max operations for SETULE/SETUGE
9618 MVT VET = VT.getVectorElementType();
9620 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9621 || (Subtarget->hasSSE2() && (VET == MVT::i8));
9624 switch (SetCCOpcode) {
9626 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9627 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9630 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9634 std::swap(Op0, Op1);
9636 // Check that the operation in question is available (most are plain SSE2,
9637 // but PCMPGTQ and PCMPEQQ have different requirements).
9638 if (VT == MVT::v2i64) {
9639 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9640 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9642 // First cast everything to the right type.
9643 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9644 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9646 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9647 // bits of the inputs before performing those operations. The lower
9648 // compare is always unsigned.
9651 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9653 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9654 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9655 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9656 Sign, Zero, Sign, Zero);
9658 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9659 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9661 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9662 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9663 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9665 // Create masks for only the low parts/high parts of the 64 bit integers.
9666 static const int MaskHi[] = { 1, 1, 3, 3 };
9667 static const int MaskLo[] = { 0, 0, 2, 2 };
9668 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9669 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9670 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9672 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9673 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9676 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9678 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9681 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9682 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9683 // pcmpeqd + pshufd + pand.
9684 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9686 // First cast everything to the right type.
9687 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9688 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9691 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9693 // Make sure the lower and upper halves are both all-ones.
9694 static const int Mask[] = { 1, 0, 3, 2 };
9695 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9696 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9699 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9701 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9705 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9706 // bits of the inputs before performing those operations.
9708 EVT EltVT = VT.getVectorElementType();
9709 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9710 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9711 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9714 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9716 // If the logical-not of the result is required, perform that now.
9718 Result = DAG.getNOT(dl, Result, VT);
9721 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9726 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9728 MVT VT = Op.getValueType().getSimpleVT();
9730 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9732 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9733 SDValue Op0 = Op.getOperand(0);
9734 SDValue Op1 = Op.getOperand(1);
9736 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9738 // Optimize to BT if possible.
9739 // Lower (X & (1 << N)) == 0 to BT(X, N).
9740 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9741 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9742 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9743 Op1.getOpcode() == ISD::Constant &&
9744 cast<ConstantSDNode>(Op1)->isNullValue() &&
9745 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9746 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9747 if (NewSetCC.getNode())
9751 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9753 if (Op1.getOpcode() == ISD::Constant &&
9754 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9755 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9756 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9758 // If the input is a setcc, then reuse the input setcc or use a new one with
9759 // the inverted condition.
9760 if (Op0.getOpcode() == X86ISD::SETCC) {
9761 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9762 bool Invert = (CC == ISD::SETNE) ^
9763 cast<ConstantSDNode>(Op1)->isNullValue();
9764 if (!Invert) return Op0;
9766 CCode = X86::GetOppositeBranchCondition(CCode);
9767 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9768 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9772 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9773 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9774 if (X86CC == X86::COND_INVALID)
9777 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9778 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9779 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9780 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9783 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9784 static bool isX86LogicalCmp(SDValue Op) {
9785 unsigned Opc = Op.getNode()->getOpcode();
9786 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9787 Opc == X86ISD::SAHF)
9789 if (Op.getResNo() == 1 &&
9790 (Opc == X86ISD::ADD ||
9791 Opc == X86ISD::SUB ||
9792 Opc == X86ISD::ADC ||
9793 Opc == X86ISD::SBB ||
9794 Opc == X86ISD::SMUL ||
9795 Opc == X86ISD::UMUL ||
9796 Opc == X86ISD::INC ||
9797 Opc == X86ISD::DEC ||
9798 Opc == X86ISD::OR ||
9799 Opc == X86ISD::XOR ||
9800 Opc == X86ISD::AND))
9803 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9809 static bool isZero(SDValue V) {
9810 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9811 return C && C->isNullValue();
9814 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9815 if (V.getOpcode() != ISD::TRUNCATE)
9818 SDValue VOp0 = V.getOperand(0);
9819 unsigned InBits = VOp0.getValueSizeInBits();
9820 unsigned Bits = V.getValueSizeInBits();
9821 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9824 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9825 bool addTest = true;
9826 SDValue Cond = Op.getOperand(0);
9827 SDValue Op1 = Op.getOperand(1);
9828 SDValue Op2 = Op.getOperand(2);
9832 if (Cond.getOpcode() == ISD::SETCC) {
9833 SDValue NewCond = LowerSETCC(Cond, DAG);
9834 if (NewCond.getNode())
9838 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9839 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9840 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9841 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9842 if (Cond.getOpcode() == X86ISD::SETCC &&
9843 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9844 isZero(Cond.getOperand(1).getOperand(1))) {
9845 SDValue Cmp = Cond.getOperand(1);
9847 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9849 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9850 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9851 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9853 SDValue CmpOp0 = Cmp.getOperand(0);
9854 // Apply further optimizations for special cases
9855 // (select (x != 0), -1, 0) -> neg & sbb
9856 // (select (x == 0), 0, -1) -> neg & sbb
9857 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9858 if (YC->isNullValue() &&
9859 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9860 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9861 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9862 DAG.getConstant(0, CmpOp0.getValueType()),
9864 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9865 DAG.getConstant(X86::COND_B, MVT::i8),
9866 SDValue(Neg.getNode(), 1));
9870 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9871 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9872 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9874 SDValue Res = // Res = 0 or -1.
9875 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9876 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9878 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9879 Res = DAG.getNOT(DL, Res, Res.getValueType());
9881 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9882 if (N2C == 0 || !N2C->isNullValue())
9883 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9888 // Look past (and (setcc_carry (cmp ...)), 1).
9889 if (Cond.getOpcode() == ISD::AND &&
9890 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9891 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9892 if (C && C->getAPIntValue() == 1)
9893 Cond = Cond.getOperand(0);
9896 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9897 // setting operand in place of the X86ISD::SETCC.
9898 unsigned CondOpcode = Cond.getOpcode();
9899 if (CondOpcode == X86ISD::SETCC ||
9900 CondOpcode == X86ISD::SETCC_CARRY) {
9901 CC = Cond.getOperand(0);
9903 SDValue Cmp = Cond.getOperand(1);
9904 unsigned Opc = Cmp.getOpcode();
9905 MVT VT = Op.getValueType().getSimpleVT();
9907 bool IllegalFPCMov = false;
9908 if (VT.isFloatingPoint() && !VT.isVector() &&
9909 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9910 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9912 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9913 Opc == X86ISD::BT) { // FIXME
9917 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9918 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9919 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9920 Cond.getOperand(0).getValueType() != MVT::i8)) {
9921 SDValue LHS = Cond.getOperand(0);
9922 SDValue RHS = Cond.getOperand(1);
9926 switch (CondOpcode) {
9927 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9928 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9929 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9930 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9931 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9932 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9933 default: llvm_unreachable("unexpected overflowing operator");
9935 if (CondOpcode == ISD::UMULO)
9936 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9939 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9941 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9943 if (CondOpcode == ISD::UMULO)
9944 Cond = X86Op.getValue(2);
9946 Cond = X86Op.getValue(1);
9948 CC = DAG.getConstant(X86Cond, MVT::i8);
9953 // Look pass the truncate if the high bits are known zero.
9954 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9955 Cond = Cond.getOperand(0);
9957 // We know the result of AND is compared against zero. Try to match
9959 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9960 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9961 if (NewSetCC.getNode()) {
9962 CC = NewSetCC.getOperand(0);
9963 Cond = NewSetCC.getOperand(1);
9970 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9971 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9974 // a < b ? -1 : 0 -> RES = ~setcc_carry
9975 // a < b ? 0 : -1 -> RES = setcc_carry
9976 // a >= b ? -1 : 0 -> RES = setcc_carry
9977 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9978 if (Cond.getOpcode() == X86ISD::SUB) {
9979 Cond = ConvertCmpIfNecessary(Cond, DAG);
9980 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9982 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9983 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9984 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9985 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9986 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9987 return DAG.getNOT(DL, Res, Res.getValueType());
9992 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9993 // widen the cmov and push the truncate through. This avoids introducing a new
9994 // branch during isel and doesn't add any extensions.
9995 if (Op.getValueType() == MVT::i8 &&
9996 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9997 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9998 if (T1.getValueType() == T2.getValueType() &&
9999 // Blacklist CopyFromReg to avoid partial register stalls.
10000 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10001 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10002 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10003 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10007 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10008 // condition is true.
10009 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10010 SDValue Ops[] = { Op2, Op1, CC, Cond };
10011 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10014 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10015 SelectionDAG &DAG) const {
10016 MVT VT = Op->getValueType(0).getSimpleVT();
10017 SDValue In = Op->getOperand(0);
10018 MVT InVT = In.getValueType().getSimpleVT();
10021 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10022 (VT != MVT::v8i32 || InVT != MVT::v8i16))
10025 if (Subtarget->hasInt256())
10026 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10028 // Optimize vectors in AVX mode
10029 // Sign extend v8i16 to v8i32 and
10032 // Divide input vector into two parts
10033 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10034 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10035 // concat the vectors to original VT
10037 unsigned NumElems = InVT.getVectorNumElements();
10038 SDValue Undef = DAG.getUNDEF(InVT);
10040 SmallVector<int,8> ShufMask1(NumElems, -1);
10041 for (unsigned i = 0; i != NumElems/2; ++i)
10044 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10046 SmallVector<int,8> ShufMask2(NumElems, -1);
10047 for (unsigned i = 0; i != NumElems/2; ++i)
10048 ShufMask2[i] = i + NumElems/2;
10050 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10052 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10053 VT.getVectorNumElements()/2);
10055 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10056 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10058 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10061 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10062 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10063 // from the AND / OR.
10064 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10065 Opc = Op.getOpcode();
10066 if (Opc != ISD::OR && Opc != ISD::AND)
10068 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10069 Op.getOperand(0).hasOneUse() &&
10070 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10071 Op.getOperand(1).hasOneUse());
10074 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10075 // 1 and that the SETCC node has a single use.
10076 static bool isXor1OfSetCC(SDValue Op) {
10077 if (Op.getOpcode() != ISD::XOR)
10079 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10080 if (N1C && N1C->getAPIntValue() == 1) {
10081 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10082 Op.getOperand(0).hasOneUse();
10087 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10088 bool addTest = true;
10089 SDValue Chain = Op.getOperand(0);
10090 SDValue Cond = Op.getOperand(1);
10091 SDValue Dest = Op.getOperand(2);
10094 bool Inverted = false;
10096 if (Cond.getOpcode() == ISD::SETCC) {
10097 // Check for setcc([su]{add,sub,mul}o == 0).
10098 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10099 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10100 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10101 Cond.getOperand(0).getResNo() == 1 &&
10102 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10103 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10104 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10105 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10106 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10107 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10109 Cond = Cond.getOperand(0);
10111 SDValue NewCond = LowerSETCC(Cond, DAG);
10112 if (NewCond.getNode())
10117 // FIXME: LowerXALUO doesn't handle these!!
10118 else if (Cond.getOpcode() == X86ISD::ADD ||
10119 Cond.getOpcode() == X86ISD::SUB ||
10120 Cond.getOpcode() == X86ISD::SMUL ||
10121 Cond.getOpcode() == X86ISD::UMUL)
10122 Cond = LowerXALUO(Cond, DAG);
10125 // Look pass (and (setcc_carry (cmp ...)), 1).
10126 if (Cond.getOpcode() == ISD::AND &&
10127 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10128 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10129 if (C && C->getAPIntValue() == 1)
10130 Cond = Cond.getOperand(0);
10133 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10134 // setting operand in place of the X86ISD::SETCC.
10135 unsigned CondOpcode = Cond.getOpcode();
10136 if (CondOpcode == X86ISD::SETCC ||
10137 CondOpcode == X86ISD::SETCC_CARRY) {
10138 CC = Cond.getOperand(0);
10140 SDValue Cmp = Cond.getOperand(1);
10141 unsigned Opc = Cmp.getOpcode();
10142 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10143 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10147 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10151 // These can only come from an arithmetic instruction with overflow,
10152 // e.g. SADDO, UADDO.
10153 Cond = Cond.getNode()->getOperand(1);
10159 CondOpcode = Cond.getOpcode();
10160 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10161 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10162 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10163 Cond.getOperand(0).getValueType() != MVT::i8)) {
10164 SDValue LHS = Cond.getOperand(0);
10165 SDValue RHS = Cond.getOperand(1);
10166 unsigned X86Opcode;
10169 switch (CondOpcode) {
10170 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10171 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10172 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10173 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10174 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10175 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10176 default: llvm_unreachable("unexpected overflowing operator");
10179 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10180 if (CondOpcode == ISD::UMULO)
10181 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10184 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10186 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10188 if (CondOpcode == ISD::UMULO)
10189 Cond = X86Op.getValue(2);
10191 Cond = X86Op.getValue(1);
10193 CC = DAG.getConstant(X86Cond, MVT::i8);
10197 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10198 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10199 if (CondOpc == ISD::OR) {
10200 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10201 // two branches instead of an explicit OR instruction with a
10203 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10204 isX86LogicalCmp(Cmp)) {
10205 CC = Cond.getOperand(0).getOperand(0);
10206 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10207 Chain, Dest, CC, Cmp);
10208 CC = Cond.getOperand(1).getOperand(0);
10212 } else { // ISD::AND
10213 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10214 // two branches instead of an explicit AND instruction with a
10215 // separate test. However, we only do this if this block doesn't
10216 // have a fall-through edge, because this requires an explicit
10217 // jmp when the condition is false.
10218 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10219 isX86LogicalCmp(Cmp) &&
10220 Op.getNode()->hasOneUse()) {
10221 X86::CondCode CCode =
10222 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10223 CCode = X86::GetOppositeBranchCondition(CCode);
10224 CC = DAG.getConstant(CCode, MVT::i8);
10225 SDNode *User = *Op.getNode()->use_begin();
10226 // Look for an unconditional branch following this conditional branch.
10227 // We need this because we need to reverse the successors in order
10228 // to implement FCMP_OEQ.
10229 if (User->getOpcode() == ISD::BR) {
10230 SDValue FalseBB = User->getOperand(1);
10232 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10233 assert(NewBR == User);
10237 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10238 Chain, Dest, CC, Cmp);
10239 X86::CondCode CCode =
10240 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10241 CCode = X86::GetOppositeBranchCondition(CCode);
10242 CC = DAG.getConstant(CCode, MVT::i8);
10248 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10249 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10250 // It should be transformed during dag combiner except when the condition
10251 // is set by a arithmetics with overflow node.
10252 X86::CondCode CCode =
10253 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10254 CCode = X86::GetOppositeBranchCondition(CCode);
10255 CC = DAG.getConstant(CCode, MVT::i8);
10256 Cond = Cond.getOperand(0).getOperand(1);
10258 } else if (Cond.getOpcode() == ISD::SETCC &&
10259 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10260 // For FCMP_OEQ, we can emit
10261 // two branches instead of an explicit AND instruction with a
10262 // separate test. However, we only do this if this block doesn't
10263 // have a fall-through edge, because this requires an explicit
10264 // jmp when the condition is false.
10265 if (Op.getNode()->hasOneUse()) {
10266 SDNode *User = *Op.getNode()->use_begin();
10267 // Look for an unconditional branch following this conditional branch.
10268 // We need this because we need to reverse the successors in order
10269 // to implement FCMP_OEQ.
10270 if (User->getOpcode() == ISD::BR) {
10271 SDValue FalseBB = User->getOperand(1);
10273 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10274 assert(NewBR == User);
10278 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10279 Cond.getOperand(0), Cond.getOperand(1));
10280 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10281 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10282 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10283 Chain, Dest, CC, Cmp);
10284 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10289 } else if (Cond.getOpcode() == ISD::SETCC &&
10290 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10291 // For FCMP_UNE, we can emit
10292 // two branches instead of an explicit AND instruction with a
10293 // separate test. However, we only do this if this block doesn't
10294 // have a fall-through edge, because this requires an explicit
10295 // jmp when the condition is false.
10296 if (Op.getNode()->hasOneUse()) {
10297 SDNode *User = *Op.getNode()->use_begin();
10298 // Look for an unconditional branch following this conditional branch.
10299 // We need this because we need to reverse the successors in order
10300 // to implement FCMP_UNE.
10301 if (User->getOpcode() == ISD::BR) {
10302 SDValue FalseBB = User->getOperand(1);
10304 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10305 assert(NewBR == User);
10308 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10309 Cond.getOperand(0), Cond.getOperand(1));
10310 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10311 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10312 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10313 Chain, Dest, CC, Cmp);
10314 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10324 // Look pass the truncate if the high bits are known zero.
10325 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10326 Cond = Cond.getOperand(0);
10328 // We know the result of AND is compared against zero. Try to match
10330 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10331 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10332 if (NewSetCC.getNode()) {
10333 CC = NewSetCC.getOperand(0);
10334 Cond = NewSetCC.getOperand(1);
10341 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10342 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10344 Cond = ConvertCmpIfNecessary(Cond, DAG);
10345 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10346 Chain, Dest, CC, Cond);
10349 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10350 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10351 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10352 // that the guard pages used by the OS virtual memory manager are allocated in
10353 // correct sequence.
10355 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10356 SelectionDAG &DAG) const {
10357 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10358 getTargetMachine().Options.EnableSegmentedStacks) &&
10359 "This should be used only on Windows targets or when segmented stacks "
10361 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10365 SDValue Chain = Op.getOperand(0);
10366 SDValue Size = Op.getOperand(1);
10367 // FIXME: Ensure alignment here
10369 bool Is64Bit = Subtarget->is64Bit();
10370 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10372 if (getTargetMachine().Options.EnableSegmentedStacks) {
10373 MachineFunction &MF = DAG.getMachineFunction();
10374 MachineRegisterInfo &MRI = MF.getRegInfo();
10377 // The 64 bit implementation of segmented stacks needs to clobber both r10
10378 // r11. This makes it impossible to use it along with nested parameters.
10379 const Function *F = MF.getFunction();
10381 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10383 if (I->hasNestAttr())
10384 report_fatal_error("Cannot use segmented stacks with functions that "
10385 "have nested arguments.");
10388 const TargetRegisterClass *AddrRegClass =
10389 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10390 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10391 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10392 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10393 DAG.getRegister(Vreg, SPTy));
10394 SDValue Ops1[2] = { Value, Chain };
10395 return DAG.getMergeValues(Ops1, 2, dl);
10398 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10400 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10401 Flag = Chain.getValue(1);
10402 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10404 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10405 Flag = Chain.getValue(1);
10407 const X86RegisterInfo *RegInfo =
10408 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10409 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10412 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10413 return DAG.getMergeValues(Ops1, 2, dl);
10417 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10418 MachineFunction &MF = DAG.getMachineFunction();
10419 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10421 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10424 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10425 // vastart just stores the address of the VarArgsFrameIndex slot into the
10426 // memory location argument.
10427 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10429 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10430 MachinePointerInfo(SV), false, false, 0);
10434 // gp_offset (0 - 6 * 8)
10435 // fp_offset (48 - 48 + 8 * 16)
10436 // overflow_arg_area (point to parameters coming in memory).
10438 SmallVector<SDValue, 8> MemOps;
10439 SDValue FIN = Op.getOperand(1);
10441 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10442 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10444 FIN, MachinePointerInfo(SV), false, false, 0);
10445 MemOps.push_back(Store);
10448 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10449 FIN, DAG.getIntPtrConstant(4));
10450 Store = DAG.getStore(Op.getOperand(0), DL,
10451 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10453 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10454 MemOps.push_back(Store);
10456 // Store ptr to overflow_arg_area
10457 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10458 FIN, DAG.getIntPtrConstant(4));
10459 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10461 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10462 MachinePointerInfo(SV, 8),
10464 MemOps.push_back(Store);
10466 // Store ptr to reg_save_area.
10467 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10468 FIN, DAG.getIntPtrConstant(8));
10469 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10471 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10472 MachinePointerInfo(SV, 16), false, false, 0);
10473 MemOps.push_back(Store);
10474 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10475 &MemOps[0], MemOps.size());
10478 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10479 assert(Subtarget->is64Bit() &&
10480 "LowerVAARG only handles 64-bit va_arg!");
10481 assert((Subtarget->isTargetLinux() ||
10482 Subtarget->isTargetDarwin()) &&
10483 "Unhandled target in LowerVAARG");
10484 assert(Op.getNode()->getNumOperands() == 4);
10485 SDValue Chain = Op.getOperand(0);
10486 SDValue SrcPtr = Op.getOperand(1);
10487 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10488 unsigned Align = Op.getConstantOperandVal(3);
10491 EVT ArgVT = Op.getNode()->getValueType(0);
10492 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10493 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10496 // Decide which area this value should be read from.
10497 // TODO: Implement the AMD64 ABI in its entirety. This simple
10498 // selection mechanism works only for the basic types.
10499 if (ArgVT == MVT::f80) {
10500 llvm_unreachable("va_arg for f80 not yet implemented");
10501 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10502 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10503 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10504 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10506 llvm_unreachable("Unhandled argument type in LowerVAARG");
10509 if (ArgMode == 2) {
10510 // Sanity Check: Make sure using fp_offset makes sense.
10511 assert(!getTargetMachine().Options.UseSoftFloat &&
10512 !(DAG.getMachineFunction()
10513 .getFunction()->getAttributes()
10514 .hasAttribute(AttributeSet::FunctionIndex,
10515 Attribute::NoImplicitFloat)) &&
10516 Subtarget->hasSSE1());
10519 // Insert VAARG_64 node into the DAG
10520 // VAARG_64 returns two values: Variable Argument Address, Chain
10521 SmallVector<SDValue, 11> InstOps;
10522 InstOps.push_back(Chain);
10523 InstOps.push_back(SrcPtr);
10524 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10525 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10526 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10527 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10528 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10529 VTs, &InstOps[0], InstOps.size(),
10531 MachinePointerInfo(SV),
10533 /*Volatile=*/false,
10535 /*WriteMem=*/true);
10536 Chain = VAARG.getValue(1);
10538 // Load the next argument and return it
10539 return DAG.getLoad(ArgVT, dl,
10542 MachinePointerInfo(),
10543 false, false, false, 0);
10546 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10547 SelectionDAG &DAG) {
10548 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10549 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10550 SDValue Chain = Op.getOperand(0);
10551 SDValue DstPtr = Op.getOperand(1);
10552 SDValue SrcPtr = Op.getOperand(2);
10553 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10554 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10557 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10558 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10560 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10563 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10564 // may or may not be a constant. Takes immediate version of shift as input.
10565 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10566 SDValue SrcOp, SDValue ShAmt,
10567 SelectionDAG &DAG) {
10568 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10570 if (isa<ConstantSDNode>(ShAmt)) {
10571 // Constant may be a TargetConstant. Use a regular constant.
10572 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10574 default: llvm_unreachable("Unknown target vector shift node");
10575 case X86ISD::VSHLI:
10576 case X86ISD::VSRLI:
10577 case X86ISD::VSRAI:
10578 return DAG.getNode(Opc, dl, VT, SrcOp,
10579 DAG.getConstant(ShiftAmt, MVT::i32));
10583 // Change opcode to non-immediate version
10585 default: llvm_unreachable("Unknown target vector shift node");
10586 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10587 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10588 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10591 // Need to build a vector containing shift amount
10592 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10595 ShOps[1] = DAG.getConstant(0, MVT::i32);
10596 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10597 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10599 // The return type has to be a 128-bit type with the same element
10600 // type as the input type.
10601 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10602 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10604 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10605 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10608 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10610 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10612 default: return SDValue(); // Don't custom lower most intrinsics.
10613 // Comparison intrinsics.
10614 case Intrinsic::x86_sse_comieq_ss:
10615 case Intrinsic::x86_sse_comilt_ss:
10616 case Intrinsic::x86_sse_comile_ss:
10617 case Intrinsic::x86_sse_comigt_ss:
10618 case Intrinsic::x86_sse_comige_ss:
10619 case Intrinsic::x86_sse_comineq_ss:
10620 case Intrinsic::x86_sse_ucomieq_ss:
10621 case Intrinsic::x86_sse_ucomilt_ss:
10622 case Intrinsic::x86_sse_ucomile_ss:
10623 case Intrinsic::x86_sse_ucomigt_ss:
10624 case Intrinsic::x86_sse_ucomige_ss:
10625 case Intrinsic::x86_sse_ucomineq_ss:
10626 case Intrinsic::x86_sse2_comieq_sd:
10627 case Intrinsic::x86_sse2_comilt_sd:
10628 case Intrinsic::x86_sse2_comile_sd:
10629 case Intrinsic::x86_sse2_comigt_sd:
10630 case Intrinsic::x86_sse2_comige_sd:
10631 case Intrinsic::x86_sse2_comineq_sd:
10632 case Intrinsic::x86_sse2_ucomieq_sd:
10633 case Intrinsic::x86_sse2_ucomilt_sd:
10634 case Intrinsic::x86_sse2_ucomile_sd:
10635 case Intrinsic::x86_sse2_ucomigt_sd:
10636 case Intrinsic::x86_sse2_ucomige_sd:
10637 case Intrinsic::x86_sse2_ucomineq_sd: {
10641 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10642 case Intrinsic::x86_sse_comieq_ss:
10643 case Intrinsic::x86_sse2_comieq_sd:
10644 Opc = X86ISD::COMI;
10647 case Intrinsic::x86_sse_comilt_ss:
10648 case Intrinsic::x86_sse2_comilt_sd:
10649 Opc = X86ISD::COMI;
10652 case Intrinsic::x86_sse_comile_ss:
10653 case Intrinsic::x86_sse2_comile_sd:
10654 Opc = X86ISD::COMI;
10657 case Intrinsic::x86_sse_comigt_ss:
10658 case Intrinsic::x86_sse2_comigt_sd:
10659 Opc = X86ISD::COMI;
10662 case Intrinsic::x86_sse_comige_ss:
10663 case Intrinsic::x86_sse2_comige_sd:
10664 Opc = X86ISD::COMI;
10667 case Intrinsic::x86_sse_comineq_ss:
10668 case Intrinsic::x86_sse2_comineq_sd:
10669 Opc = X86ISD::COMI;
10672 case Intrinsic::x86_sse_ucomieq_ss:
10673 case Intrinsic::x86_sse2_ucomieq_sd:
10674 Opc = X86ISD::UCOMI;
10677 case Intrinsic::x86_sse_ucomilt_ss:
10678 case Intrinsic::x86_sse2_ucomilt_sd:
10679 Opc = X86ISD::UCOMI;
10682 case Intrinsic::x86_sse_ucomile_ss:
10683 case Intrinsic::x86_sse2_ucomile_sd:
10684 Opc = X86ISD::UCOMI;
10687 case Intrinsic::x86_sse_ucomigt_ss:
10688 case Intrinsic::x86_sse2_ucomigt_sd:
10689 Opc = X86ISD::UCOMI;
10692 case Intrinsic::x86_sse_ucomige_ss:
10693 case Intrinsic::x86_sse2_ucomige_sd:
10694 Opc = X86ISD::UCOMI;
10697 case Intrinsic::x86_sse_ucomineq_ss:
10698 case Intrinsic::x86_sse2_ucomineq_sd:
10699 Opc = X86ISD::UCOMI;
10704 SDValue LHS = Op.getOperand(1);
10705 SDValue RHS = Op.getOperand(2);
10706 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10707 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10708 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10709 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10710 DAG.getConstant(X86CC, MVT::i8), Cond);
10711 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10714 // Arithmetic intrinsics.
10715 case Intrinsic::x86_sse2_pmulu_dq:
10716 case Intrinsic::x86_avx2_pmulu_dq:
10717 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10718 Op.getOperand(1), Op.getOperand(2));
10720 // SSE2/AVX2 sub with unsigned saturation intrinsics
10721 case Intrinsic::x86_sse2_psubus_b:
10722 case Intrinsic::x86_sse2_psubus_w:
10723 case Intrinsic::x86_avx2_psubus_b:
10724 case Intrinsic::x86_avx2_psubus_w:
10725 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10726 Op.getOperand(1), Op.getOperand(2));
10728 // SSE3/AVX horizontal add/sub intrinsics
10729 case Intrinsic::x86_sse3_hadd_ps:
10730 case Intrinsic::x86_sse3_hadd_pd:
10731 case Intrinsic::x86_avx_hadd_ps_256:
10732 case Intrinsic::x86_avx_hadd_pd_256:
10733 case Intrinsic::x86_sse3_hsub_ps:
10734 case Intrinsic::x86_sse3_hsub_pd:
10735 case Intrinsic::x86_avx_hsub_ps_256:
10736 case Intrinsic::x86_avx_hsub_pd_256:
10737 case Intrinsic::x86_ssse3_phadd_w_128:
10738 case Intrinsic::x86_ssse3_phadd_d_128:
10739 case Intrinsic::x86_avx2_phadd_w:
10740 case Intrinsic::x86_avx2_phadd_d:
10741 case Intrinsic::x86_ssse3_phsub_w_128:
10742 case Intrinsic::x86_ssse3_phsub_d_128:
10743 case Intrinsic::x86_avx2_phsub_w:
10744 case Intrinsic::x86_avx2_phsub_d: {
10747 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10748 case Intrinsic::x86_sse3_hadd_ps:
10749 case Intrinsic::x86_sse3_hadd_pd:
10750 case Intrinsic::x86_avx_hadd_ps_256:
10751 case Intrinsic::x86_avx_hadd_pd_256:
10752 Opcode = X86ISD::FHADD;
10754 case Intrinsic::x86_sse3_hsub_ps:
10755 case Intrinsic::x86_sse3_hsub_pd:
10756 case Intrinsic::x86_avx_hsub_ps_256:
10757 case Intrinsic::x86_avx_hsub_pd_256:
10758 Opcode = X86ISD::FHSUB;
10760 case Intrinsic::x86_ssse3_phadd_w_128:
10761 case Intrinsic::x86_ssse3_phadd_d_128:
10762 case Intrinsic::x86_avx2_phadd_w:
10763 case Intrinsic::x86_avx2_phadd_d:
10764 Opcode = X86ISD::HADD;
10766 case Intrinsic::x86_ssse3_phsub_w_128:
10767 case Intrinsic::x86_ssse3_phsub_d_128:
10768 case Intrinsic::x86_avx2_phsub_w:
10769 case Intrinsic::x86_avx2_phsub_d:
10770 Opcode = X86ISD::HSUB;
10773 return DAG.getNode(Opcode, dl, Op.getValueType(),
10774 Op.getOperand(1), Op.getOperand(2));
10777 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10778 case Intrinsic::x86_sse2_pmaxu_b:
10779 case Intrinsic::x86_sse41_pmaxuw:
10780 case Intrinsic::x86_sse41_pmaxud:
10781 case Intrinsic::x86_avx2_pmaxu_b:
10782 case Intrinsic::x86_avx2_pmaxu_w:
10783 case Intrinsic::x86_avx2_pmaxu_d:
10784 case Intrinsic::x86_sse2_pminu_b:
10785 case Intrinsic::x86_sse41_pminuw:
10786 case Intrinsic::x86_sse41_pminud:
10787 case Intrinsic::x86_avx2_pminu_b:
10788 case Intrinsic::x86_avx2_pminu_w:
10789 case Intrinsic::x86_avx2_pminu_d:
10790 case Intrinsic::x86_sse41_pmaxsb:
10791 case Intrinsic::x86_sse2_pmaxs_w:
10792 case Intrinsic::x86_sse41_pmaxsd:
10793 case Intrinsic::x86_avx2_pmaxs_b:
10794 case Intrinsic::x86_avx2_pmaxs_w:
10795 case Intrinsic::x86_avx2_pmaxs_d:
10796 case Intrinsic::x86_sse41_pminsb:
10797 case Intrinsic::x86_sse2_pmins_w:
10798 case Intrinsic::x86_sse41_pminsd:
10799 case Intrinsic::x86_avx2_pmins_b:
10800 case Intrinsic::x86_avx2_pmins_w:
10801 case Intrinsic::x86_avx2_pmins_d: {
10804 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10805 case Intrinsic::x86_sse2_pmaxu_b:
10806 case Intrinsic::x86_sse41_pmaxuw:
10807 case Intrinsic::x86_sse41_pmaxud:
10808 case Intrinsic::x86_avx2_pmaxu_b:
10809 case Intrinsic::x86_avx2_pmaxu_w:
10810 case Intrinsic::x86_avx2_pmaxu_d:
10811 Opcode = X86ISD::UMAX;
10813 case Intrinsic::x86_sse2_pminu_b:
10814 case Intrinsic::x86_sse41_pminuw:
10815 case Intrinsic::x86_sse41_pminud:
10816 case Intrinsic::x86_avx2_pminu_b:
10817 case Intrinsic::x86_avx2_pminu_w:
10818 case Intrinsic::x86_avx2_pminu_d:
10819 Opcode = X86ISD::UMIN;
10821 case Intrinsic::x86_sse41_pmaxsb:
10822 case Intrinsic::x86_sse2_pmaxs_w:
10823 case Intrinsic::x86_sse41_pmaxsd:
10824 case Intrinsic::x86_avx2_pmaxs_b:
10825 case Intrinsic::x86_avx2_pmaxs_w:
10826 case Intrinsic::x86_avx2_pmaxs_d:
10827 Opcode = X86ISD::SMAX;
10829 case Intrinsic::x86_sse41_pminsb:
10830 case Intrinsic::x86_sse2_pmins_w:
10831 case Intrinsic::x86_sse41_pminsd:
10832 case Intrinsic::x86_avx2_pmins_b:
10833 case Intrinsic::x86_avx2_pmins_w:
10834 case Intrinsic::x86_avx2_pmins_d:
10835 Opcode = X86ISD::SMIN;
10838 return DAG.getNode(Opcode, dl, Op.getValueType(),
10839 Op.getOperand(1), Op.getOperand(2));
10842 // SSE/SSE2/AVX floating point max/min intrinsics.
10843 case Intrinsic::x86_sse_max_ps:
10844 case Intrinsic::x86_sse2_max_pd:
10845 case Intrinsic::x86_avx_max_ps_256:
10846 case Intrinsic::x86_avx_max_pd_256:
10847 case Intrinsic::x86_sse_min_ps:
10848 case Intrinsic::x86_sse2_min_pd:
10849 case Intrinsic::x86_avx_min_ps_256:
10850 case Intrinsic::x86_avx_min_pd_256: {
10853 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10854 case Intrinsic::x86_sse_max_ps:
10855 case Intrinsic::x86_sse2_max_pd:
10856 case Intrinsic::x86_avx_max_ps_256:
10857 case Intrinsic::x86_avx_max_pd_256:
10858 Opcode = X86ISD::FMAX;
10860 case Intrinsic::x86_sse_min_ps:
10861 case Intrinsic::x86_sse2_min_pd:
10862 case Intrinsic::x86_avx_min_ps_256:
10863 case Intrinsic::x86_avx_min_pd_256:
10864 Opcode = X86ISD::FMIN;
10867 return DAG.getNode(Opcode, dl, Op.getValueType(),
10868 Op.getOperand(1), Op.getOperand(2));
10871 // AVX2 variable shift intrinsics
10872 case Intrinsic::x86_avx2_psllv_d:
10873 case Intrinsic::x86_avx2_psllv_q:
10874 case Intrinsic::x86_avx2_psllv_d_256:
10875 case Intrinsic::x86_avx2_psllv_q_256:
10876 case Intrinsic::x86_avx2_psrlv_d:
10877 case Intrinsic::x86_avx2_psrlv_q:
10878 case Intrinsic::x86_avx2_psrlv_d_256:
10879 case Intrinsic::x86_avx2_psrlv_q_256:
10880 case Intrinsic::x86_avx2_psrav_d:
10881 case Intrinsic::x86_avx2_psrav_d_256: {
10884 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10885 case Intrinsic::x86_avx2_psllv_d:
10886 case Intrinsic::x86_avx2_psllv_q:
10887 case Intrinsic::x86_avx2_psllv_d_256:
10888 case Intrinsic::x86_avx2_psllv_q_256:
10891 case Intrinsic::x86_avx2_psrlv_d:
10892 case Intrinsic::x86_avx2_psrlv_q:
10893 case Intrinsic::x86_avx2_psrlv_d_256:
10894 case Intrinsic::x86_avx2_psrlv_q_256:
10897 case Intrinsic::x86_avx2_psrav_d:
10898 case Intrinsic::x86_avx2_psrav_d_256:
10902 return DAG.getNode(Opcode, dl, Op.getValueType(),
10903 Op.getOperand(1), Op.getOperand(2));
10906 case Intrinsic::x86_ssse3_pshuf_b_128:
10907 case Intrinsic::x86_avx2_pshuf_b:
10908 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10909 Op.getOperand(1), Op.getOperand(2));
10911 case Intrinsic::x86_ssse3_psign_b_128:
10912 case Intrinsic::x86_ssse3_psign_w_128:
10913 case Intrinsic::x86_ssse3_psign_d_128:
10914 case Intrinsic::x86_avx2_psign_b:
10915 case Intrinsic::x86_avx2_psign_w:
10916 case Intrinsic::x86_avx2_psign_d:
10917 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10918 Op.getOperand(1), Op.getOperand(2));
10920 case Intrinsic::x86_sse41_insertps:
10921 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10922 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10924 case Intrinsic::x86_avx_vperm2f128_ps_256:
10925 case Intrinsic::x86_avx_vperm2f128_pd_256:
10926 case Intrinsic::x86_avx_vperm2f128_si_256:
10927 case Intrinsic::x86_avx2_vperm2i128:
10928 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10929 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10931 case Intrinsic::x86_avx2_permd:
10932 case Intrinsic::x86_avx2_permps:
10933 // Operands intentionally swapped. Mask is last operand to intrinsic,
10934 // but second operand for node/intruction.
10935 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10936 Op.getOperand(2), Op.getOperand(1));
10938 case Intrinsic::x86_sse_sqrt_ps:
10939 case Intrinsic::x86_sse2_sqrt_pd:
10940 case Intrinsic::x86_avx_sqrt_ps_256:
10941 case Intrinsic::x86_avx_sqrt_pd_256:
10942 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10944 // ptest and testp intrinsics. The intrinsic these come from are designed to
10945 // return an integer value, not just an instruction so lower it to the ptest
10946 // or testp pattern and a setcc for the result.
10947 case Intrinsic::x86_sse41_ptestz:
10948 case Intrinsic::x86_sse41_ptestc:
10949 case Intrinsic::x86_sse41_ptestnzc:
10950 case Intrinsic::x86_avx_ptestz_256:
10951 case Intrinsic::x86_avx_ptestc_256:
10952 case Intrinsic::x86_avx_ptestnzc_256:
10953 case Intrinsic::x86_avx_vtestz_ps:
10954 case Intrinsic::x86_avx_vtestc_ps:
10955 case Intrinsic::x86_avx_vtestnzc_ps:
10956 case Intrinsic::x86_avx_vtestz_pd:
10957 case Intrinsic::x86_avx_vtestc_pd:
10958 case Intrinsic::x86_avx_vtestnzc_pd:
10959 case Intrinsic::x86_avx_vtestz_ps_256:
10960 case Intrinsic::x86_avx_vtestc_ps_256:
10961 case Intrinsic::x86_avx_vtestnzc_ps_256:
10962 case Intrinsic::x86_avx_vtestz_pd_256:
10963 case Intrinsic::x86_avx_vtestc_pd_256:
10964 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10965 bool IsTestPacked = false;
10968 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10969 case Intrinsic::x86_avx_vtestz_ps:
10970 case Intrinsic::x86_avx_vtestz_pd:
10971 case Intrinsic::x86_avx_vtestz_ps_256:
10972 case Intrinsic::x86_avx_vtestz_pd_256:
10973 IsTestPacked = true; // Fallthrough
10974 case Intrinsic::x86_sse41_ptestz:
10975 case Intrinsic::x86_avx_ptestz_256:
10977 X86CC = X86::COND_E;
10979 case Intrinsic::x86_avx_vtestc_ps:
10980 case Intrinsic::x86_avx_vtestc_pd:
10981 case Intrinsic::x86_avx_vtestc_ps_256:
10982 case Intrinsic::x86_avx_vtestc_pd_256:
10983 IsTestPacked = true; // Fallthrough
10984 case Intrinsic::x86_sse41_ptestc:
10985 case Intrinsic::x86_avx_ptestc_256:
10987 X86CC = X86::COND_B;
10989 case Intrinsic::x86_avx_vtestnzc_ps:
10990 case Intrinsic::x86_avx_vtestnzc_pd:
10991 case Intrinsic::x86_avx_vtestnzc_ps_256:
10992 case Intrinsic::x86_avx_vtestnzc_pd_256:
10993 IsTestPacked = true; // Fallthrough
10994 case Intrinsic::x86_sse41_ptestnzc:
10995 case Intrinsic::x86_avx_ptestnzc_256:
10997 X86CC = X86::COND_A;
11001 SDValue LHS = Op.getOperand(1);
11002 SDValue RHS = Op.getOperand(2);
11003 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11004 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11005 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11006 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11007 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11010 // SSE/AVX shift intrinsics
11011 case Intrinsic::x86_sse2_psll_w:
11012 case Intrinsic::x86_sse2_psll_d:
11013 case Intrinsic::x86_sse2_psll_q:
11014 case Intrinsic::x86_avx2_psll_w:
11015 case Intrinsic::x86_avx2_psll_d:
11016 case Intrinsic::x86_avx2_psll_q:
11017 case Intrinsic::x86_sse2_psrl_w:
11018 case Intrinsic::x86_sse2_psrl_d:
11019 case Intrinsic::x86_sse2_psrl_q:
11020 case Intrinsic::x86_avx2_psrl_w:
11021 case Intrinsic::x86_avx2_psrl_d:
11022 case Intrinsic::x86_avx2_psrl_q:
11023 case Intrinsic::x86_sse2_psra_w:
11024 case Intrinsic::x86_sse2_psra_d:
11025 case Intrinsic::x86_avx2_psra_w:
11026 case Intrinsic::x86_avx2_psra_d: {
11029 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11030 case Intrinsic::x86_sse2_psll_w:
11031 case Intrinsic::x86_sse2_psll_d:
11032 case Intrinsic::x86_sse2_psll_q:
11033 case Intrinsic::x86_avx2_psll_w:
11034 case Intrinsic::x86_avx2_psll_d:
11035 case Intrinsic::x86_avx2_psll_q:
11036 Opcode = X86ISD::VSHL;
11038 case Intrinsic::x86_sse2_psrl_w:
11039 case Intrinsic::x86_sse2_psrl_d:
11040 case Intrinsic::x86_sse2_psrl_q:
11041 case Intrinsic::x86_avx2_psrl_w:
11042 case Intrinsic::x86_avx2_psrl_d:
11043 case Intrinsic::x86_avx2_psrl_q:
11044 Opcode = X86ISD::VSRL;
11046 case Intrinsic::x86_sse2_psra_w:
11047 case Intrinsic::x86_sse2_psra_d:
11048 case Intrinsic::x86_avx2_psra_w:
11049 case Intrinsic::x86_avx2_psra_d:
11050 Opcode = X86ISD::VSRA;
11053 return DAG.getNode(Opcode, dl, Op.getValueType(),
11054 Op.getOperand(1), Op.getOperand(2));
11057 // SSE/AVX immediate shift intrinsics
11058 case Intrinsic::x86_sse2_pslli_w:
11059 case Intrinsic::x86_sse2_pslli_d:
11060 case Intrinsic::x86_sse2_pslli_q:
11061 case Intrinsic::x86_avx2_pslli_w:
11062 case Intrinsic::x86_avx2_pslli_d:
11063 case Intrinsic::x86_avx2_pslli_q:
11064 case Intrinsic::x86_sse2_psrli_w:
11065 case Intrinsic::x86_sse2_psrli_d:
11066 case Intrinsic::x86_sse2_psrli_q:
11067 case Intrinsic::x86_avx2_psrli_w:
11068 case Intrinsic::x86_avx2_psrli_d:
11069 case Intrinsic::x86_avx2_psrli_q:
11070 case Intrinsic::x86_sse2_psrai_w:
11071 case Intrinsic::x86_sse2_psrai_d:
11072 case Intrinsic::x86_avx2_psrai_w:
11073 case Intrinsic::x86_avx2_psrai_d: {
11076 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11077 case Intrinsic::x86_sse2_pslli_w:
11078 case Intrinsic::x86_sse2_pslli_d:
11079 case Intrinsic::x86_sse2_pslli_q:
11080 case Intrinsic::x86_avx2_pslli_w:
11081 case Intrinsic::x86_avx2_pslli_d:
11082 case Intrinsic::x86_avx2_pslli_q:
11083 Opcode = X86ISD::VSHLI;
11085 case Intrinsic::x86_sse2_psrli_w:
11086 case Intrinsic::x86_sse2_psrli_d:
11087 case Intrinsic::x86_sse2_psrli_q:
11088 case Intrinsic::x86_avx2_psrli_w:
11089 case Intrinsic::x86_avx2_psrli_d:
11090 case Intrinsic::x86_avx2_psrli_q:
11091 Opcode = X86ISD::VSRLI;
11093 case Intrinsic::x86_sse2_psrai_w:
11094 case Intrinsic::x86_sse2_psrai_d:
11095 case Intrinsic::x86_avx2_psrai_w:
11096 case Intrinsic::x86_avx2_psrai_d:
11097 Opcode = X86ISD::VSRAI;
11100 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11101 Op.getOperand(1), Op.getOperand(2), DAG);
11104 case Intrinsic::x86_sse42_pcmpistria128:
11105 case Intrinsic::x86_sse42_pcmpestria128:
11106 case Intrinsic::x86_sse42_pcmpistric128:
11107 case Intrinsic::x86_sse42_pcmpestric128:
11108 case Intrinsic::x86_sse42_pcmpistrio128:
11109 case Intrinsic::x86_sse42_pcmpestrio128:
11110 case Intrinsic::x86_sse42_pcmpistris128:
11111 case Intrinsic::x86_sse42_pcmpestris128:
11112 case Intrinsic::x86_sse42_pcmpistriz128:
11113 case Intrinsic::x86_sse42_pcmpestriz128: {
11117 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11118 case Intrinsic::x86_sse42_pcmpistria128:
11119 Opcode = X86ISD::PCMPISTRI;
11120 X86CC = X86::COND_A;
11122 case Intrinsic::x86_sse42_pcmpestria128:
11123 Opcode = X86ISD::PCMPESTRI;
11124 X86CC = X86::COND_A;
11126 case Intrinsic::x86_sse42_pcmpistric128:
11127 Opcode = X86ISD::PCMPISTRI;
11128 X86CC = X86::COND_B;
11130 case Intrinsic::x86_sse42_pcmpestric128:
11131 Opcode = X86ISD::PCMPESTRI;
11132 X86CC = X86::COND_B;
11134 case Intrinsic::x86_sse42_pcmpistrio128:
11135 Opcode = X86ISD::PCMPISTRI;
11136 X86CC = X86::COND_O;
11138 case Intrinsic::x86_sse42_pcmpestrio128:
11139 Opcode = X86ISD::PCMPESTRI;
11140 X86CC = X86::COND_O;
11142 case Intrinsic::x86_sse42_pcmpistris128:
11143 Opcode = X86ISD::PCMPISTRI;
11144 X86CC = X86::COND_S;
11146 case Intrinsic::x86_sse42_pcmpestris128:
11147 Opcode = X86ISD::PCMPESTRI;
11148 X86CC = X86::COND_S;
11150 case Intrinsic::x86_sse42_pcmpistriz128:
11151 Opcode = X86ISD::PCMPISTRI;
11152 X86CC = X86::COND_E;
11154 case Intrinsic::x86_sse42_pcmpestriz128:
11155 Opcode = X86ISD::PCMPESTRI;
11156 X86CC = X86::COND_E;
11159 SmallVector<SDValue, 5> NewOps;
11160 NewOps.append(Op->op_begin()+1, Op->op_end());
11161 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11162 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11163 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11164 DAG.getConstant(X86CC, MVT::i8),
11165 SDValue(PCMP.getNode(), 1));
11166 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11169 case Intrinsic::x86_sse42_pcmpistri128:
11170 case Intrinsic::x86_sse42_pcmpestri128: {
11172 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11173 Opcode = X86ISD::PCMPISTRI;
11175 Opcode = X86ISD::PCMPESTRI;
11177 SmallVector<SDValue, 5> NewOps;
11178 NewOps.append(Op->op_begin()+1, Op->op_end());
11179 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11180 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11182 case Intrinsic::x86_fma_vfmadd_ps:
11183 case Intrinsic::x86_fma_vfmadd_pd:
11184 case Intrinsic::x86_fma_vfmsub_ps:
11185 case Intrinsic::x86_fma_vfmsub_pd:
11186 case Intrinsic::x86_fma_vfnmadd_ps:
11187 case Intrinsic::x86_fma_vfnmadd_pd:
11188 case Intrinsic::x86_fma_vfnmsub_ps:
11189 case Intrinsic::x86_fma_vfnmsub_pd:
11190 case Intrinsic::x86_fma_vfmaddsub_ps:
11191 case Intrinsic::x86_fma_vfmaddsub_pd:
11192 case Intrinsic::x86_fma_vfmsubadd_ps:
11193 case Intrinsic::x86_fma_vfmsubadd_pd:
11194 case Intrinsic::x86_fma_vfmadd_ps_256:
11195 case Intrinsic::x86_fma_vfmadd_pd_256:
11196 case Intrinsic::x86_fma_vfmsub_ps_256:
11197 case Intrinsic::x86_fma_vfmsub_pd_256:
11198 case Intrinsic::x86_fma_vfnmadd_ps_256:
11199 case Intrinsic::x86_fma_vfnmadd_pd_256:
11200 case Intrinsic::x86_fma_vfnmsub_ps_256:
11201 case Intrinsic::x86_fma_vfnmsub_pd_256:
11202 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11203 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11204 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11205 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11208 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11209 case Intrinsic::x86_fma_vfmadd_ps:
11210 case Intrinsic::x86_fma_vfmadd_pd:
11211 case Intrinsic::x86_fma_vfmadd_ps_256:
11212 case Intrinsic::x86_fma_vfmadd_pd_256:
11213 Opc = X86ISD::FMADD;
11215 case Intrinsic::x86_fma_vfmsub_ps:
11216 case Intrinsic::x86_fma_vfmsub_pd:
11217 case Intrinsic::x86_fma_vfmsub_ps_256:
11218 case Intrinsic::x86_fma_vfmsub_pd_256:
11219 Opc = X86ISD::FMSUB;
11221 case Intrinsic::x86_fma_vfnmadd_ps:
11222 case Intrinsic::x86_fma_vfnmadd_pd:
11223 case Intrinsic::x86_fma_vfnmadd_ps_256:
11224 case Intrinsic::x86_fma_vfnmadd_pd_256:
11225 Opc = X86ISD::FNMADD;
11227 case Intrinsic::x86_fma_vfnmsub_ps:
11228 case Intrinsic::x86_fma_vfnmsub_pd:
11229 case Intrinsic::x86_fma_vfnmsub_ps_256:
11230 case Intrinsic::x86_fma_vfnmsub_pd_256:
11231 Opc = X86ISD::FNMSUB;
11233 case Intrinsic::x86_fma_vfmaddsub_ps:
11234 case Intrinsic::x86_fma_vfmaddsub_pd:
11235 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11236 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11237 Opc = X86ISD::FMADDSUB;
11239 case Intrinsic::x86_fma_vfmsubadd_ps:
11240 case Intrinsic::x86_fma_vfmsubadd_pd:
11241 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11242 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11243 Opc = X86ISD::FMSUBADD;
11247 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11248 Op.getOperand(2), Op.getOperand(3));
11253 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11255 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11257 default: return SDValue(); // Don't custom lower most intrinsics.
11259 // RDRAND/RDSEED intrinsics.
11260 case Intrinsic::x86_rdrand_16:
11261 case Intrinsic::x86_rdrand_32:
11262 case Intrinsic::x86_rdrand_64:
11263 case Intrinsic::x86_rdseed_16:
11264 case Intrinsic::x86_rdseed_32:
11265 case Intrinsic::x86_rdseed_64: {
11266 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11267 IntNo == Intrinsic::x86_rdseed_32 ||
11268 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11270 // Emit the node with the right value type.
11271 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11272 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11274 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11275 // Otherwise return the value from Rand, which is always 0, casted to i32.
11276 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11277 DAG.getConstant(1, Op->getValueType(1)),
11278 DAG.getConstant(X86::COND_B, MVT::i32),
11279 SDValue(Result.getNode(), 1) };
11280 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11281 DAG.getVTList(Op->getValueType(1), MVT::Glue),
11282 Ops, array_lengthof(Ops));
11284 // Return { result, isValid, chain }.
11285 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11286 SDValue(Result.getNode(), 2));
11289 // XTEST intrinsics.
11290 case Intrinsic::x86_xtest: {
11291 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11292 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11293 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11294 DAG.getConstant(X86::COND_NE, MVT::i8),
11296 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11297 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11298 Ret, SDValue(InTrans.getNode(), 1));
11303 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11304 SelectionDAG &DAG) const {
11305 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11306 MFI->setReturnAddressIsTaken(true);
11308 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11310 EVT PtrVT = getPointerTy();
11313 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11314 const X86RegisterInfo *RegInfo =
11315 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11316 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11317 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11318 DAG.getNode(ISD::ADD, dl, PtrVT,
11319 FrameAddr, Offset),
11320 MachinePointerInfo(), false, false, false, 0);
11323 // Just load the return address.
11324 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11325 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11326 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11329 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11330 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11331 MFI->setFrameAddressIsTaken(true);
11333 EVT VT = Op.getValueType();
11334 SDLoc dl(Op); // FIXME probably not meaningful
11335 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11336 const X86RegisterInfo *RegInfo =
11337 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11338 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11339 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11340 (FrameReg == X86::EBP && VT == MVT::i32)) &&
11341 "Invalid Frame Register!");
11342 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11344 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11345 MachinePointerInfo(),
11346 false, false, false, 0);
11350 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11351 SelectionDAG &DAG) const {
11352 const X86RegisterInfo *RegInfo =
11353 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11354 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11357 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11358 SDValue Chain = Op.getOperand(0);
11359 SDValue Offset = Op.getOperand(1);
11360 SDValue Handler = Op.getOperand(2);
11363 EVT PtrVT = getPointerTy();
11364 const X86RegisterInfo *RegInfo =
11365 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11366 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11367 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11368 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11369 "Invalid Frame Register!");
11370 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11371 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11373 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11374 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11375 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11376 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11378 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11380 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11381 DAG.getRegister(StoreAddrReg, PtrVT));
11384 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11385 SelectionDAG &DAG) const {
11387 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11388 DAG.getVTList(MVT::i32, MVT::Other),
11389 Op.getOperand(0), Op.getOperand(1));
11392 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11393 SelectionDAG &DAG) const {
11395 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11396 Op.getOperand(0), Op.getOperand(1));
11399 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11400 return Op.getOperand(0);
11403 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11404 SelectionDAG &DAG) const {
11405 SDValue Root = Op.getOperand(0);
11406 SDValue Trmp = Op.getOperand(1); // trampoline
11407 SDValue FPtr = Op.getOperand(2); // nested function
11408 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11411 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11412 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11414 if (Subtarget->is64Bit()) {
11415 SDValue OutChains[6];
11417 // Large code-model.
11418 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11419 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11421 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11422 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11424 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11426 // Load the pointer to the nested function into R11.
11427 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11428 SDValue Addr = Trmp;
11429 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11430 Addr, MachinePointerInfo(TrmpAddr),
11433 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11434 DAG.getConstant(2, MVT::i64));
11435 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11436 MachinePointerInfo(TrmpAddr, 2),
11439 // Load the 'nest' parameter value into R10.
11440 // R10 is specified in X86CallingConv.td
11441 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11442 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11443 DAG.getConstant(10, MVT::i64));
11444 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11445 Addr, MachinePointerInfo(TrmpAddr, 10),
11448 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11449 DAG.getConstant(12, MVT::i64));
11450 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11451 MachinePointerInfo(TrmpAddr, 12),
11454 // Jump to the nested function.
11455 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11456 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11457 DAG.getConstant(20, MVT::i64));
11458 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11459 Addr, MachinePointerInfo(TrmpAddr, 20),
11462 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11463 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11464 DAG.getConstant(22, MVT::i64));
11465 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11466 MachinePointerInfo(TrmpAddr, 22),
11469 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11471 const Function *Func =
11472 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11473 CallingConv::ID CC = Func->getCallingConv();
11478 llvm_unreachable("Unsupported calling convention");
11479 case CallingConv::C:
11480 case CallingConv::X86_StdCall: {
11481 // Pass 'nest' parameter in ECX.
11482 // Must be kept in sync with X86CallingConv.td
11483 NestReg = X86::ECX;
11485 // Check that ECX wasn't needed by an 'inreg' parameter.
11486 FunctionType *FTy = Func->getFunctionType();
11487 const AttributeSet &Attrs = Func->getAttributes();
11489 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11490 unsigned InRegCount = 0;
11493 for (FunctionType::param_iterator I = FTy->param_begin(),
11494 E = FTy->param_end(); I != E; ++I, ++Idx)
11495 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11496 // FIXME: should only count parameters that are lowered to integers.
11497 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11499 if (InRegCount > 2) {
11500 report_fatal_error("Nest register in use - reduce number of inreg"
11506 case CallingConv::X86_FastCall:
11507 case CallingConv::X86_ThisCall:
11508 case CallingConv::Fast:
11509 // Pass 'nest' parameter in EAX.
11510 // Must be kept in sync with X86CallingConv.td
11511 NestReg = X86::EAX;
11515 SDValue OutChains[4];
11516 SDValue Addr, Disp;
11518 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11519 DAG.getConstant(10, MVT::i32));
11520 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11522 // This is storing the opcode for MOV32ri.
11523 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11524 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11525 OutChains[0] = DAG.getStore(Root, dl,
11526 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11527 Trmp, MachinePointerInfo(TrmpAddr),
11530 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11531 DAG.getConstant(1, MVT::i32));
11532 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11533 MachinePointerInfo(TrmpAddr, 1),
11536 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11537 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11538 DAG.getConstant(5, MVT::i32));
11539 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11540 MachinePointerInfo(TrmpAddr, 5),
11543 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11544 DAG.getConstant(6, MVT::i32));
11545 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11546 MachinePointerInfo(TrmpAddr, 6),
11549 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11553 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11554 SelectionDAG &DAG) const {
11556 The rounding mode is in bits 11:10 of FPSR, and has the following
11558 00 Round to nearest
11563 FLT_ROUNDS, on the other hand, expects the following:
11570 To perform the conversion, we do:
11571 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11574 MachineFunction &MF = DAG.getMachineFunction();
11575 const TargetMachine &TM = MF.getTarget();
11576 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11577 unsigned StackAlignment = TFI.getStackAlignment();
11578 EVT VT = Op.getValueType();
11581 // Save FP Control Word to stack slot
11582 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11583 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11585 MachineMemOperand *MMO =
11586 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11587 MachineMemOperand::MOStore, 2, 2);
11589 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11590 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11591 DAG.getVTList(MVT::Other),
11592 Ops, array_lengthof(Ops), MVT::i16,
11595 // Load FP Control Word from stack slot
11596 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11597 MachinePointerInfo(), false, false, false, 0);
11599 // Transform as necessary
11601 DAG.getNode(ISD::SRL, DL, MVT::i16,
11602 DAG.getNode(ISD::AND, DL, MVT::i16,
11603 CWD, DAG.getConstant(0x800, MVT::i16)),
11604 DAG.getConstant(11, MVT::i8));
11606 DAG.getNode(ISD::SRL, DL, MVT::i16,
11607 DAG.getNode(ISD::AND, DL, MVT::i16,
11608 CWD, DAG.getConstant(0x400, MVT::i16)),
11609 DAG.getConstant(9, MVT::i8));
11612 DAG.getNode(ISD::AND, DL, MVT::i16,
11613 DAG.getNode(ISD::ADD, DL, MVT::i16,
11614 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11615 DAG.getConstant(1, MVT::i16)),
11616 DAG.getConstant(3, MVT::i16));
11618 return DAG.getNode((VT.getSizeInBits() < 16 ?
11619 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11622 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11623 EVT VT = Op.getValueType();
11625 unsigned NumBits = VT.getSizeInBits();
11628 Op = Op.getOperand(0);
11629 if (VT == MVT::i8) {
11630 // Zero extend to i32 since there is not an i8 bsr.
11632 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11635 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11636 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11637 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11639 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11642 DAG.getConstant(NumBits+NumBits-1, OpVT),
11643 DAG.getConstant(X86::COND_E, MVT::i8),
11646 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11648 // Finally xor with NumBits-1.
11649 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11652 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11656 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11657 EVT VT = Op.getValueType();
11659 unsigned NumBits = VT.getSizeInBits();
11662 Op = Op.getOperand(0);
11663 if (VT == MVT::i8) {
11664 // Zero extend to i32 since there is not an i8 bsr.
11666 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11669 // Issue a bsr (scan bits in reverse).
11670 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11671 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11673 // And xor with NumBits-1.
11674 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11677 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11681 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11682 EVT VT = Op.getValueType();
11683 unsigned NumBits = VT.getSizeInBits();
11685 Op = Op.getOperand(0);
11687 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11688 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11689 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11691 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11694 DAG.getConstant(NumBits, VT),
11695 DAG.getConstant(X86::COND_E, MVT::i8),
11698 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11701 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11702 // ones, and then concatenate the result back.
11703 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11704 EVT VT = Op.getValueType();
11706 assert(VT.is256BitVector() && VT.isInteger() &&
11707 "Unsupported value type for operation");
11709 unsigned NumElems = VT.getVectorNumElements();
11712 // Extract the LHS vectors
11713 SDValue LHS = Op.getOperand(0);
11714 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11715 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11717 // Extract the RHS vectors
11718 SDValue RHS = Op.getOperand(1);
11719 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11720 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11722 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11723 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11725 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11726 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11727 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11730 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11731 assert(Op.getValueType().is256BitVector() &&
11732 Op.getValueType().isInteger() &&
11733 "Only handle AVX 256-bit vector integer operation");
11734 return Lower256IntArith(Op, DAG);
11737 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11738 assert(Op.getValueType().is256BitVector() &&
11739 Op.getValueType().isInteger() &&
11740 "Only handle AVX 256-bit vector integer operation");
11741 return Lower256IntArith(Op, DAG);
11744 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11745 SelectionDAG &DAG) {
11747 EVT VT = Op.getValueType();
11749 // Decompose 256-bit ops into smaller 128-bit ops.
11750 if (VT.is256BitVector() && !Subtarget->hasInt256())
11751 return Lower256IntArith(Op, DAG);
11753 SDValue A = Op.getOperand(0);
11754 SDValue B = Op.getOperand(1);
11756 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11757 if (VT == MVT::v4i32) {
11758 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11759 "Should not custom lower when pmuldq is available!");
11761 // Extract the odd parts.
11762 static const int UnpackMask[] = { 1, -1, 3, -1 };
11763 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11764 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11766 // Multiply the even parts.
11767 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11768 // Now multiply odd parts.
11769 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11771 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11772 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11774 // Merge the two vectors back together with a shuffle. This expands into 2
11776 static const int ShufMask[] = { 0, 4, 2, 6 };
11777 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11780 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11781 "Only know how to lower V2I64/V4I64 multiply");
11783 // Ahi = psrlqi(a, 32);
11784 // Bhi = psrlqi(b, 32);
11786 // AloBlo = pmuludq(a, b);
11787 // AloBhi = pmuludq(a, Bhi);
11788 // AhiBlo = pmuludq(Ahi, b);
11790 // AloBhi = psllqi(AloBhi, 32);
11791 // AhiBlo = psllqi(AhiBlo, 32);
11792 // return AloBlo + AloBhi + AhiBlo;
11794 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11796 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11797 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11799 // Bit cast to 32-bit vectors for MULUDQ
11800 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11801 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11802 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11803 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11804 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11806 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11807 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11808 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11810 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11811 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11813 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11814 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11817 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11818 EVT VT = Op.getValueType();
11819 EVT EltTy = VT.getVectorElementType();
11820 unsigned NumElts = VT.getVectorNumElements();
11821 SDValue N0 = Op.getOperand(0);
11824 // Lower sdiv X, pow2-const.
11825 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11829 APInt SplatValue, SplatUndef;
11830 unsigned SplatBitSize;
11832 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11834 EltTy.getSizeInBits() < SplatBitSize)
11837 if ((SplatValue != 0) &&
11838 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11839 unsigned lg2 = SplatValue.countTrailingZeros();
11840 // Splat the sign bit.
11841 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11842 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11843 // Add (N0 < 0) ? abs2 - 1 : 0;
11844 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11845 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11846 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11847 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11848 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11850 // If we're dividing by a positive value, we're done. Otherwise, we must
11851 // negate the result.
11852 if (SplatValue.isNonNegative())
11855 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11856 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11857 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11862 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11863 const X86Subtarget *Subtarget) {
11864 EVT VT = Op.getValueType();
11866 SDValue R = Op.getOperand(0);
11867 SDValue Amt = Op.getOperand(1);
11869 // Optimize shl/srl/sra with constant shift amount.
11870 if (isSplatVector(Amt.getNode())) {
11871 SDValue SclrAmt = Amt->getOperand(0);
11872 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11873 uint64_t ShiftAmt = C->getZExtValue();
11875 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11876 (Subtarget->hasInt256() &&
11877 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11878 if (Op.getOpcode() == ISD::SHL)
11879 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11880 DAG.getConstant(ShiftAmt, MVT::i32));
11881 if (Op.getOpcode() == ISD::SRL)
11882 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11883 DAG.getConstant(ShiftAmt, MVT::i32));
11884 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11885 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11886 DAG.getConstant(ShiftAmt, MVT::i32));
11889 if (VT == MVT::v16i8) {
11890 if (Op.getOpcode() == ISD::SHL) {
11891 // Make a large shift.
11892 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11893 DAG.getConstant(ShiftAmt, MVT::i32));
11894 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11895 // Zero out the rightmost bits.
11896 SmallVector<SDValue, 16> V(16,
11897 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11899 return DAG.getNode(ISD::AND, dl, VT, SHL,
11900 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11902 if (Op.getOpcode() == ISD::SRL) {
11903 // Make a large shift.
11904 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11905 DAG.getConstant(ShiftAmt, MVT::i32));
11906 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11907 // Zero out the leftmost bits.
11908 SmallVector<SDValue, 16> V(16,
11909 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11911 return DAG.getNode(ISD::AND, dl, VT, SRL,
11912 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11914 if (Op.getOpcode() == ISD::SRA) {
11915 if (ShiftAmt == 7) {
11916 // R s>> 7 === R s< 0
11917 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11918 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11921 // R s>> a === ((R u>> a) ^ m) - m
11922 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11923 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11925 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11926 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11927 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11930 llvm_unreachable("Unknown shift opcode.");
11933 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11934 if (Op.getOpcode() == ISD::SHL) {
11935 // Make a large shift.
11936 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11937 DAG.getConstant(ShiftAmt, MVT::i32));
11938 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11939 // Zero out the rightmost bits.
11940 SmallVector<SDValue, 32> V(32,
11941 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11943 return DAG.getNode(ISD::AND, dl, VT, SHL,
11944 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11946 if (Op.getOpcode() == ISD::SRL) {
11947 // Make a large shift.
11948 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11949 DAG.getConstant(ShiftAmt, MVT::i32));
11950 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11951 // Zero out the leftmost bits.
11952 SmallVector<SDValue, 32> V(32,
11953 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11955 return DAG.getNode(ISD::AND, dl, VT, SRL,
11956 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11958 if (Op.getOpcode() == ISD::SRA) {
11959 if (ShiftAmt == 7) {
11960 // R s>> 7 === R s< 0
11961 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11962 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11965 // R s>> a === ((R u>> a) ^ m) - m
11966 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11967 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11969 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11970 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11971 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11974 llvm_unreachable("Unknown shift opcode.");
11979 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11980 if (!Subtarget->is64Bit() &&
11981 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11982 Amt.getOpcode() == ISD::BITCAST &&
11983 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11984 Amt = Amt.getOperand(0);
11985 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11986 VT.getVectorNumElements();
11987 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11988 uint64_t ShiftAmt = 0;
11989 for (unsigned i = 0; i != Ratio; ++i) {
11990 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11994 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11996 // Check remaining shift amounts.
11997 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11998 uint64_t ShAmt = 0;
11999 for (unsigned j = 0; j != Ratio; ++j) {
12000 ConstantSDNode *C =
12001 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12005 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12007 if (ShAmt != ShiftAmt)
12010 switch (Op.getOpcode()) {
12012 llvm_unreachable("Unknown shift opcode!");
12014 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12015 DAG.getConstant(ShiftAmt, MVT::i32));
12017 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12018 DAG.getConstant(ShiftAmt, MVT::i32));
12020 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12021 DAG.getConstant(ShiftAmt, MVT::i32));
12028 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12029 const X86Subtarget* Subtarget) {
12030 EVT VT = Op.getValueType();
12032 SDValue R = Op.getOperand(0);
12033 SDValue Amt = Op.getOperand(1);
12035 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12036 VT == MVT::v4i32 || VT == MVT::v8i16 ||
12037 (Subtarget->hasInt256() &&
12038 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12039 VT == MVT::v8i32 || VT == MVT::v16i16))) {
12041 EVT EltVT = VT.getVectorElementType();
12043 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12044 unsigned NumElts = VT.getVectorNumElements();
12046 for (i = 0; i != NumElts; ++i) {
12047 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12051 for (j = i; j != NumElts; ++j) {
12052 SDValue Arg = Amt.getOperand(j);
12053 if (Arg.getOpcode() == ISD::UNDEF) continue;
12054 if (Arg != Amt.getOperand(i))
12057 if (i != NumElts && j == NumElts)
12058 BaseShAmt = Amt.getOperand(i);
12060 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12061 Amt = Amt.getOperand(0);
12062 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12063 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12064 SDValue InVec = Amt.getOperand(0);
12065 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12066 unsigned NumElts = InVec.getValueType().getVectorNumElements();
12068 for (; i != NumElts; ++i) {
12069 SDValue Arg = InVec.getOperand(i);
12070 if (Arg.getOpcode() == ISD::UNDEF) continue;
12074 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12075 if (ConstantSDNode *C =
12076 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12077 unsigned SplatIdx =
12078 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12079 if (C->getZExtValue() == SplatIdx)
12080 BaseShAmt = InVec.getOperand(1);
12083 if (BaseShAmt.getNode() == 0)
12084 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12085 DAG.getIntPtrConstant(0));
12089 if (BaseShAmt.getNode()) {
12090 if (EltVT.bitsGT(MVT::i32))
12091 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12092 else if (EltVT.bitsLT(MVT::i32))
12093 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12095 switch (Op.getOpcode()) {
12097 llvm_unreachable("Unknown shift opcode!");
12099 switch (VT.getSimpleVT().SimpleTy) {
12100 default: return SDValue();
12107 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12110 switch (VT.getSimpleVT().SimpleTy) {
12111 default: return SDValue();
12116 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12119 switch (VT.getSimpleVT().SimpleTy) {
12120 default: return SDValue();
12127 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12133 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12134 if (!Subtarget->is64Bit() &&
12135 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12136 Amt.getOpcode() == ISD::BITCAST &&
12137 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12138 Amt = Amt.getOperand(0);
12139 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12140 VT.getVectorNumElements();
12141 std::vector<SDValue> Vals(Ratio);
12142 for (unsigned i = 0; i != Ratio; ++i)
12143 Vals[i] = Amt.getOperand(i);
12144 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12145 for (unsigned j = 0; j != Ratio; ++j)
12146 if (Vals[j] != Amt.getOperand(i + j))
12149 switch (Op.getOpcode()) {
12151 llvm_unreachable("Unknown shift opcode!");
12153 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12155 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12157 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12164 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12166 EVT VT = Op.getValueType();
12168 SDValue R = Op.getOperand(0);
12169 SDValue Amt = Op.getOperand(1);
12172 if (!Subtarget->hasSSE2())
12175 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12179 V = LowerScalarVariableShift(Op, DAG, Subtarget);
12183 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12184 if (Subtarget->hasInt256()) {
12185 if (Op.getOpcode() == ISD::SRL &&
12186 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12187 VT == MVT::v4i64 || VT == MVT::v8i32))
12189 if (Op.getOpcode() == ISD::SHL &&
12190 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12191 VT == MVT::v4i64 || VT == MVT::v8i32))
12193 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12197 // Lower SHL with variable shift amount.
12198 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12199 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12201 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12202 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12203 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12204 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12206 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12207 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12210 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12211 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12213 // Turn 'a' into a mask suitable for VSELECT
12214 SDValue VSelM = DAG.getConstant(0x80, VT);
12215 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12216 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12218 SDValue CM1 = DAG.getConstant(0x0f, VT);
12219 SDValue CM2 = DAG.getConstant(0x3f, VT);
12221 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12222 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12223 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12224 DAG.getConstant(4, MVT::i32), DAG);
12225 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12226 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12229 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12230 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12231 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12233 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12234 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12235 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12236 DAG.getConstant(2, MVT::i32), DAG);
12237 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12238 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12241 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12242 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12243 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12245 // return VSELECT(r, r+r, a);
12246 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12247 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12251 // Decompose 256-bit shifts into smaller 128-bit shifts.
12252 if (VT.is256BitVector()) {
12253 unsigned NumElems = VT.getVectorNumElements();
12254 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12255 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12257 // Extract the two vectors
12258 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12259 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12261 // Recreate the shift amount vectors
12262 SDValue Amt1, Amt2;
12263 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12264 // Constant shift amount
12265 SmallVector<SDValue, 4> Amt1Csts;
12266 SmallVector<SDValue, 4> Amt2Csts;
12267 for (unsigned i = 0; i != NumElems/2; ++i)
12268 Amt1Csts.push_back(Amt->getOperand(i));
12269 for (unsigned i = NumElems/2; i != NumElems; ++i)
12270 Amt2Csts.push_back(Amt->getOperand(i));
12272 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12273 &Amt1Csts[0], NumElems/2);
12274 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12275 &Amt2Csts[0], NumElems/2);
12277 // Variable shift amount
12278 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12279 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12282 // Issue new vector shifts for the smaller types
12283 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12284 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12286 // Concatenate the result back
12287 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12293 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12294 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12295 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12296 // looks for this combo and may remove the "setcc" instruction if the "setcc"
12297 // has only one use.
12298 SDNode *N = Op.getNode();
12299 SDValue LHS = N->getOperand(0);
12300 SDValue RHS = N->getOperand(1);
12301 unsigned BaseOp = 0;
12304 switch (Op.getOpcode()) {
12305 default: llvm_unreachable("Unknown ovf instruction!");
12307 // A subtract of one will be selected as a INC. Note that INC doesn't
12308 // set CF, so we can't do this for UADDO.
12309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12311 BaseOp = X86ISD::INC;
12312 Cond = X86::COND_O;
12315 BaseOp = X86ISD::ADD;
12316 Cond = X86::COND_O;
12319 BaseOp = X86ISD::ADD;
12320 Cond = X86::COND_B;
12323 // A subtract of one will be selected as a DEC. Note that DEC doesn't
12324 // set CF, so we can't do this for USUBO.
12325 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12327 BaseOp = X86ISD::DEC;
12328 Cond = X86::COND_O;
12331 BaseOp = X86ISD::SUB;
12332 Cond = X86::COND_O;
12335 BaseOp = X86ISD::SUB;
12336 Cond = X86::COND_B;
12339 BaseOp = X86ISD::SMUL;
12340 Cond = X86::COND_O;
12342 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12343 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12345 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12348 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12349 DAG.getConstant(X86::COND_O, MVT::i32),
12350 SDValue(Sum.getNode(), 2));
12352 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12356 // Also sets EFLAGS.
12357 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12358 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12361 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12362 DAG.getConstant(Cond, MVT::i32),
12363 SDValue(Sum.getNode(), 1));
12365 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12368 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12369 SelectionDAG &DAG) const {
12371 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12372 EVT VT = Op.getValueType();
12374 if (!Subtarget->hasSSE2() || !VT.isVector())
12377 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12378 ExtraVT.getScalarType().getSizeInBits();
12379 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12381 switch (VT.getSimpleVT().SimpleTy) {
12382 default: return SDValue();
12385 if (!Subtarget->hasFp256())
12387 if (!Subtarget->hasInt256()) {
12388 // needs to be split
12389 unsigned NumElems = VT.getVectorNumElements();
12391 // Extract the LHS vectors
12392 SDValue LHS = Op.getOperand(0);
12393 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12394 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12396 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12397 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12399 EVT ExtraEltVT = ExtraVT.getVectorElementType();
12400 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12401 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12403 SDValue Extra = DAG.getValueType(ExtraVT);
12405 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12406 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12408 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12413 // (sext (vzext x)) -> (vsext x)
12414 SDValue Op0 = Op.getOperand(0);
12415 SDValue Op00 = Op0.getOperand(0);
12417 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12418 if (Op0.getOpcode() == ISD::BITCAST &&
12419 Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12420 Tmp1 = LowerVectorIntExtend(Op00, DAG);
12421 if (Tmp1.getNode()) {
12422 SDValue Tmp1Op0 = Tmp1.getOperand(0);
12423 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12424 "This optimization is invalid without a VZEXT.");
12425 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12428 // If the above didn't work, then just use Shift-Left + Shift-Right.
12429 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12430 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12435 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12436 SelectionDAG &DAG) {
12438 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12439 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12440 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12441 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12443 // The only fence that needs an instruction is a sequentially-consistent
12444 // cross-thread fence.
12445 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12446 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12447 // no-sse2). There isn't any reason to disable it if the target processor
12449 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12450 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12452 SDValue Chain = Op.getOperand(0);
12453 SDValue Zero = DAG.getConstant(0, MVT::i32);
12455 DAG.getRegister(X86::ESP, MVT::i32), // Base
12456 DAG.getTargetConstant(1, MVT::i8), // Scale
12457 DAG.getRegister(0, MVT::i32), // Index
12458 DAG.getTargetConstant(0, MVT::i32), // Disp
12459 DAG.getRegister(0, MVT::i32), // Segment.
12463 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12464 return SDValue(Res, 0);
12467 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12468 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12471 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12472 SelectionDAG &DAG) {
12473 EVT T = Op.getValueType();
12477 switch(T.getSimpleVT().SimpleTy) {
12478 default: llvm_unreachable("Invalid value type!");
12479 case MVT::i8: Reg = X86::AL; size = 1; break;
12480 case MVT::i16: Reg = X86::AX; size = 2; break;
12481 case MVT::i32: Reg = X86::EAX; size = 4; break;
12483 assert(Subtarget->is64Bit() && "Node not type legal!");
12484 Reg = X86::RAX; size = 8;
12487 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12488 Op.getOperand(2), SDValue());
12489 SDValue Ops[] = { cpIn.getValue(0),
12492 DAG.getTargetConstant(size, MVT::i8),
12493 cpIn.getValue(1) };
12494 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12495 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12496 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12497 Ops, array_lengthof(Ops), T, MMO);
12499 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12503 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12504 SelectionDAG &DAG) {
12505 assert(Subtarget->is64Bit() && "Result not type legalized?");
12506 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12507 SDValue TheChain = Op.getOperand(0);
12509 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12510 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12511 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12513 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12514 DAG.getConstant(32, MVT::i8));
12516 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12519 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12522 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12523 EVT SrcVT = Op.getOperand(0).getValueType();
12524 EVT DstVT = Op.getValueType();
12525 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12526 Subtarget->hasMMX() && "Unexpected custom BITCAST");
12527 assert((DstVT == MVT::i64 ||
12528 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12529 "Unexpected custom BITCAST");
12530 // i64 <=> MMX conversions are Legal.
12531 if (SrcVT==MVT::i64 && DstVT.isVector())
12533 if (DstVT==MVT::i64 && SrcVT.isVector())
12535 // MMX <=> MMX conversions are Legal.
12536 if (SrcVT.isVector() && DstVT.isVector())
12538 // All other conversions need to be expanded.
12542 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12543 SDNode *Node = Op.getNode();
12545 EVT T = Node->getValueType(0);
12546 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12547 DAG.getConstant(0, T), Node->getOperand(2));
12548 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12549 cast<AtomicSDNode>(Node)->getMemoryVT(),
12550 Node->getOperand(0),
12551 Node->getOperand(1), negOp,
12552 cast<AtomicSDNode>(Node)->getSrcValue(),
12553 cast<AtomicSDNode>(Node)->getAlignment(),
12554 cast<AtomicSDNode>(Node)->getOrdering(),
12555 cast<AtomicSDNode>(Node)->getSynchScope());
12558 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12559 SDNode *Node = Op.getNode();
12561 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12563 // Convert seq_cst store -> xchg
12564 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12565 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12566 // (The only way to get a 16-byte store is cmpxchg16b)
12567 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12568 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12569 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12570 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12571 cast<AtomicSDNode>(Node)->getMemoryVT(),
12572 Node->getOperand(0),
12573 Node->getOperand(1), Node->getOperand(2),
12574 cast<AtomicSDNode>(Node)->getMemOperand(),
12575 cast<AtomicSDNode>(Node)->getOrdering(),
12576 cast<AtomicSDNode>(Node)->getSynchScope());
12577 return Swap.getValue(1);
12579 // Other atomic stores have a simple pattern.
12583 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12584 EVT VT = Op.getNode()->getValueType(0);
12586 // Let legalize expand this if it isn't a legal type yet.
12587 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12590 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12593 bool ExtraOp = false;
12594 switch (Op.getOpcode()) {
12595 default: llvm_unreachable("Invalid code");
12596 case ISD::ADDC: Opc = X86ISD::ADD; break;
12597 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12598 case ISD::SUBC: Opc = X86ISD::SUB; break;
12599 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12603 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12605 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12606 Op.getOperand(1), Op.getOperand(2));
12609 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12610 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12612 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12613 // which returns the values as { float, float } (in XMM0) or
12614 // { double, double } (which is returned in XMM0, XMM1).
12616 SDValue Arg = Op.getOperand(0);
12617 EVT ArgVT = Arg.getValueType();
12618 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12621 ArgListEntry Entry;
12625 Entry.isSExt = false;
12626 Entry.isZExt = false;
12627 Args.push_back(Entry);
12629 bool isF64 = ArgVT == MVT::f64;
12630 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12631 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12632 // the results are returned via SRet in memory.
12633 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
12634 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12636 Type *RetTy = isF64
12637 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12638 : (Type*)VectorType::get(ArgTy, 4);
12640 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12641 false, false, false, false, 0,
12642 CallingConv::C, /*isTaillCall=*/false,
12643 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12644 Callee, Args, DAG, dl);
12645 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12648 // Returned in xmm0 and xmm1.
12649 return CallResult.first;
12651 // Returned in bits 0:31 and 32:64 xmm0.
12652 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12653 CallResult.first, DAG.getIntPtrConstant(0));
12654 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12655 CallResult.first, DAG.getIntPtrConstant(1));
12656 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12657 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12660 /// LowerOperation - Provide custom lowering hooks for some operations.
12662 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12663 switch (Op.getOpcode()) {
12664 default: llvm_unreachable("Should not custom lower this!");
12665 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12666 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12667 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12668 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12669 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12670 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12671 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12672 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12673 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12674 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12675 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12676 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12677 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12678 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12679 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12680 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12681 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12682 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12683 case ISD::SHL_PARTS:
12684 case ISD::SRA_PARTS:
12685 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12686 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12687 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12688 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12689 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12690 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12691 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12692 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12693 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12694 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12695 case ISD::FABS: return LowerFABS(Op, DAG);
12696 case ISD::FNEG: return LowerFNEG(Op, DAG);
12697 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12698 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12699 case ISD::SETCC: return LowerSETCC(Op, DAG);
12700 case ISD::SELECT: return LowerSELECT(Op, DAG);
12701 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12702 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12703 case ISD::VASTART: return LowerVASTART(Op, DAG);
12704 case ISD::VAARG: return LowerVAARG(Op, DAG);
12705 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12706 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12707 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12708 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12709 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12710 case ISD::FRAME_TO_ARGS_OFFSET:
12711 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12712 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12713 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12714 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12715 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12716 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12717 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12718 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12719 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12720 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12721 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12722 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12725 case ISD::SHL: return LowerShift(Op, DAG);
12731 case ISD::UMULO: return LowerXALUO(Op, DAG);
12732 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12733 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12737 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12738 case ISD::ADD: return LowerADD(Op, DAG);
12739 case ISD::SUB: return LowerSUB(Op, DAG);
12740 case ISD::SDIV: return LowerSDIV(Op, DAG);
12741 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
12745 static void ReplaceATOMIC_LOAD(SDNode *Node,
12746 SmallVectorImpl<SDValue> &Results,
12747 SelectionDAG &DAG) {
12749 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12751 // Convert wide load -> cmpxchg8b/cmpxchg16b
12752 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12753 // (The only way to get a 16-byte load is cmpxchg16b)
12754 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12755 SDValue Zero = DAG.getConstant(0, VT);
12756 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12757 Node->getOperand(0),
12758 Node->getOperand(1), Zero, Zero,
12759 cast<AtomicSDNode>(Node)->getMemOperand(),
12760 cast<AtomicSDNode>(Node)->getOrdering(),
12761 cast<AtomicSDNode>(Node)->getSynchScope());
12762 Results.push_back(Swap.getValue(0));
12763 Results.push_back(Swap.getValue(1));
12767 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12768 SelectionDAG &DAG, unsigned NewOp) {
12770 assert (Node->getValueType(0) == MVT::i64 &&
12771 "Only know how to expand i64 atomics");
12773 SDValue Chain = Node->getOperand(0);
12774 SDValue In1 = Node->getOperand(1);
12775 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12776 Node->getOperand(2), DAG.getIntPtrConstant(0));
12777 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12778 Node->getOperand(2), DAG.getIntPtrConstant(1));
12779 SDValue Ops[] = { Chain, In1, In2L, In2H };
12780 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12782 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12783 cast<MemSDNode>(Node)->getMemOperand());
12784 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12785 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12786 Results.push_back(Result.getValue(2));
12789 /// ReplaceNodeResults - Replace a node with an illegal result type
12790 /// with a new node built out of custom code.
12791 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12792 SmallVectorImpl<SDValue>&Results,
12793 SelectionDAG &DAG) const {
12795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12796 switch (N->getOpcode()) {
12798 llvm_unreachable("Do not know how to custom type legalize this operation!");
12799 case ISD::SIGN_EXTEND_INREG:
12804 // We don't want to expand or promote these.
12806 case ISD::FP_TO_SINT:
12807 case ISD::FP_TO_UINT: {
12808 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12810 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12813 std::pair<SDValue,SDValue> Vals =
12814 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12815 SDValue FIST = Vals.first, StackSlot = Vals.second;
12816 if (FIST.getNode() != 0) {
12817 EVT VT = N->getValueType(0);
12818 // Return a load from the stack slot.
12819 if (StackSlot.getNode() != 0)
12820 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12821 MachinePointerInfo(),
12822 false, false, false, 0));
12824 Results.push_back(FIST);
12828 case ISD::UINT_TO_FP: {
12829 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12830 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12831 N->getValueType(0) != MVT::v2f32)
12833 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12835 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12837 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12838 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12839 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12840 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12841 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12842 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12845 case ISD::FP_ROUND: {
12846 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12848 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12849 Results.push_back(V);
12852 case ISD::READCYCLECOUNTER: {
12853 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12854 SDValue TheChain = N->getOperand(0);
12855 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12856 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12858 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12860 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12861 SDValue Ops[] = { eax, edx };
12862 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12863 array_lengthof(Ops)));
12864 Results.push_back(edx.getValue(1));
12867 case ISD::ATOMIC_CMP_SWAP: {
12868 EVT T = N->getValueType(0);
12869 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12870 bool Regs64bit = T == MVT::i128;
12871 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12872 SDValue cpInL, cpInH;
12873 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12874 DAG.getConstant(0, HalfT));
12875 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12876 DAG.getConstant(1, HalfT));
12877 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12878 Regs64bit ? X86::RAX : X86::EAX,
12880 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12881 Regs64bit ? X86::RDX : X86::EDX,
12882 cpInH, cpInL.getValue(1));
12883 SDValue swapInL, swapInH;
12884 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12885 DAG.getConstant(0, HalfT));
12886 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12887 DAG.getConstant(1, HalfT));
12888 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12889 Regs64bit ? X86::RBX : X86::EBX,
12890 swapInL, cpInH.getValue(1));
12891 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12892 Regs64bit ? X86::RCX : X86::ECX,
12893 swapInH, swapInL.getValue(1));
12894 SDValue Ops[] = { swapInH.getValue(0),
12896 swapInH.getValue(1) };
12897 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12898 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12899 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12900 X86ISD::LCMPXCHG8_DAG;
12901 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12902 Ops, array_lengthof(Ops), T, MMO);
12903 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12904 Regs64bit ? X86::RAX : X86::EAX,
12905 HalfT, Result.getValue(1));
12906 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12907 Regs64bit ? X86::RDX : X86::EDX,
12908 HalfT, cpOutL.getValue(2));
12909 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12910 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12911 Results.push_back(cpOutH.getValue(1));
12914 case ISD::ATOMIC_LOAD_ADD:
12915 case ISD::ATOMIC_LOAD_AND:
12916 case ISD::ATOMIC_LOAD_NAND:
12917 case ISD::ATOMIC_LOAD_OR:
12918 case ISD::ATOMIC_LOAD_SUB:
12919 case ISD::ATOMIC_LOAD_XOR:
12920 case ISD::ATOMIC_LOAD_MAX:
12921 case ISD::ATOMIC_LOAD_MIN:
12922 case ISD::ATOMIC_LOAD_UMAX:
12923 case ISD::ATOMIC_LOAD_UMIN:
12924 case ISD::ATOMIC_SWAP: {
12926 switch (N->getOpcode()) {
12927 default: llvm_unreachable("Unexpected opcode");
12928 case ISD::ATOMIC_LOAD_ADD:
12929 Opc = X86ISD::ATOMADD64_DAG;
12931 case ISD::ATOMIC_LOAD_AND:
12932 Opc = X86ISD::ATOMAND64_DAG;
12934 case ISD::ATOMIC_LOAD_NAND:
12935 Opc = X86ISD::ATOMNAND64_DAG;
12937 case ISD::ATOMIC_LOAD_OR:
12938 Opc = X86ISD::ATOMOR64_DAG;
12940 case ISD::ATOMIC_LOAD_SUB:
12941 Opc = X86ISD::ATOMSUB64_DAG;
12943 case ISD::ATOMIC_LOAD_XOR:
12944 Opc = X86ISD::ATOMXOR64_DAG;
12946 case ISD::ATOMIC_LOAD_MAX:
12947 Opc = X86ISD::ATOMMAX64_DAG;
12949 case ISD::ATOMIC_LOAD_MIN:
12950 Opc = X86ISD::ATOMMIN64_DAG;
12952 case ISD::ATOMIC_LOAD_UMAX:
12953 Opc = X86ISD::ATOMUMAX64_DAG;
12955 case ISD::ATOMIC_LOAD_UMIN:
12956 Opc = X86ISD::ATOMUMIN64_DAG;
12958 case ISD::ATOMIC_SWAP:
12959 Opc = X86ISD::ATOMSWAP64_DAG;
12962 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12965 case ISD::ATOMIC_LOAD:
12966 ReplaceATOMIC_LOAD(N, Results, DAG);
12970 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12972 default: return NULL;
12973 case X86ISD::BSF: return "X86ISD::BSF";
12974 case X86ISD::BSR: return "X86ISD::BSR";
12975 case X86ISD::SHLD: return "X86ISD::SHLD";
12976 case X86ISD::SHRD: return "X86ISD::SHRD";
12977 case X86ISD::FAND: return "X86ISD::FAND";
12978 case X86ISD::FOR: return "X86ISD::FOR";
12979 case X86ISD::FXOR: return "X86ISD::FXOR";
12980 case X86ISD::FSRL: return "X86ISD::FSRL";
12981 case X86ISD::FILD: return "X86ISD::FILD";
12982 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12983 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12984 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12985 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12986 case X86ISD::FLD: return "X86ISD::FLD";
12987 case X86ISD::FST: return "X86ISD::FST";
12988 case X86ISD::CALL: return "X86ISD::CALL";
12989 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12990 case X86ISD::BT: return "X86ISD::BT";
12991 case X86ISD::CMP: return "X86ISD::CMP";
12992 case X86ISD::COMI: return "X86ISD::COMI";
12993 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12994 case X86ISD::SETCC: return "X86ISD::SETCC";
12995 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12996 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12997 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12998 case X86ISD::CMOV: return "X86ISD::CMOV";
12999 case X86ISD::BRCOND: return "X86ISD::BRCOND";
13000 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
13001 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
13002 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
13003 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
13004 case X86ISD::Wrapper: return "X86ISD::Wrapper";
13005 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
13006 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
13007 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
13008 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
13009 case X86ISD::PINSRB: return "X86ISD::PINSRB";
13010 case X86ISD::PINSRW: return "X86ISD::PINSRW";
13011 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
13012 case X86ISD::ANDNP: return "X86ISD::ANDNP";
13013 case X86ISD::PSIGN: return "X86ISD::PSIGN";
13014 case X86ISD::BLENDV: return "X86ISD::BLENDV";
13015 case X86ISD::BLENDI: return "X86ISD::BLENDI";
13016 case X86ISD::SUBUS: return "X86ISD::SUBUS";
13017 case X86ISD::HADD: return "X86ISD::HADD";
13018 case X86ISD::HSUB: return "X86ISD::HSUB";
13019 case X86ISD::FHADD: return "X86ISD::FHADD";
13020 case X86ISD::FHSUB: return "X86ISD::FHSUB";
13021 case X86ISD::UMAX: return "X86ISD::UMAX";
13022 case X86ISD::UMIN: return "X86ISD::UMIN";
13023 case X86ISD::SMAX: return "X86ISD::SMAX";
13024 case X86ISD::SMIN: return "X86ISD::SMIN";
13025 case X86ISD::FMAX: return "X86ISD::FMAX";
13026 case X86ISD::FMIN: return "X86ISD::FMIN";
13027 case X86ISD::FMAXC: return "X86ISD::FMAXC";
13028 case X86ISD::FMINC: return "X86ISD::FMINC";
13029 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
13030 case X86ISD::FRCP: return "X86ISD::FRCP";
13031 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
13032 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
13033 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
13034 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
13035 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
13036 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
13037 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
13038 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
13039 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
13040 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
13041 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
13042 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
13043 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
13044 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
13045 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
13046 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
13047 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
13048 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
13049 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
13050 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
13051 case X86ISD::VZEXT: return "X86ISD::VZEXT";
13052 case X86ISD::VSEXT: return "X86ISD::VSEXT";
13053 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
13054 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
13055 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
13056 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
13057 case X86ISD::VSHL: return "X86ISD::VSHL";
13058 case X86ISD::VSRL: return "X86ISD::VSRL";
13059 case X86ISD::VSRA: return "X86ISD::VSRA";
13060 case X86ISD::VSHLI: return "X86ISD::VSHLI";
13061 case X86ISD::VSRLI: return "X86ISD::VSRLI";
13062 case X86ISD::VSRAI: return "X86ISD::VSRAI";
13063 case X86ISD::CMPP: return "X86ISD::CMPP";
13064 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
13065 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
13066 case X86ISD::ADD: return "X86ISD::ADD";
13067 case X86ISD::SUB: return "X86ISD::SUB";
13068 case X86ISD::ADC: return "X86ISD::ADC";
13069 case X86ISD::SBB: return "X86ISD::SBB";
13070 case X86ISD::SMUL: return "X86ISD::SMUL";
13071 case X86ISD::UMUL: return "X86ISD::UMUL";
13072 case X86ISD::INC: return "X86ISD::INC";
13073 case X86ISD::DEC: return "X86ISD::DEC";
13074 case X86ISD::OR: return "X86ISD::OR";
13075 case X86ISD::XOR: return "X86ISD::XOR";
13076 case X86ISD::AND: return "X86ISD::AND";
13077 case X86ISD::BLSI: return "X86ISD::BLSI";
13078 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
13079 case X86ISD::BLSR: return "X86ISD::BLSR";
13080 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
13081 case X86ISD::PTEST: return "X86ISD::PTEST";
13082 case X86ISD::TESTP: return "X86ISD::TESTP";
13083 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
13084 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
13085 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
13086 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
13087 case X86ISD::SHUFP: return "X86ISD::SHUFP";
13088 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
13089 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
13090 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
13091 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
13092 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
13093 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
13094 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
13095 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
13096 case X86ISD::MOVSD: return "X86ISD::MOVSD";
13097 case X86ISD::MOVSS: return "X86ISD::MOVSS";
13098 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
13099 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
13100 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
13101 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
13102 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
13103 case X86ISD::VPERMV: return "X86ISD::VPERMV";
13104 case X86ISD::VPERMI: return "X86ISD::VPERMI";
13105 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
13106 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13107 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
13108 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
13109 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
13110 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
13111 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
13112 case X86ISD::SAHF: return "X86ISD::SAHF";
13113 case X86ISD::RDRAND: return "X86ISD::RDRAND";
13114 case X86ISD::RDSEED: return "X86ISD::RDSEED";
13115 case X86ISD::FMADD: return "X86ISD::FMADD";
13116 case X86ISD::FMSUB: return "X86ISD::FMSUB";
13117 case X86ISD::FNMADD: return "X86ISD::FNMADD";
13118 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
13119 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
13120 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
13121 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
13122 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
13123 case X86ISD::XTEST: return "X86ISD::XTEST";
13127 // isLegalAddressingMode - Return true if the addressing mode represented
13128 // by AM is legal for this target, for a load/store of the specified type.
13129 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13131 // X86 supports extremely general addressing modes.
13132 CodeModel::Model M = getTargetMachine().getCodeModel();
13133 Reloc::Model R = getTargetMachine().getRelocationModel();
13135 // X86 allows a sign-extended 32-bit immediate field as a displacement.
13136 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13141 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13143 // If a reference to this global requires an extra load, we can't fold it.
13144 if (isGlobalStubReference(GVFlags))
13147 // If BaseGV requires a register for the PIC base, we cannot also have a
13148 // BaseReg specified.
13149 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13152 // If lower 4G is not available, then we must use rip-relative addressing.
13153 if ((M != CodeModel::Small || R != Reloc::Static) &&
13154 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13158 switch (AM.Scale) {
13164 // These scales always work.
13169 // These scales are formed with basereg+scalereg. Only accept if there is
13174 default: // Other stuff never works.
13181 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13182 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13184 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13185 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13186 return NumBits1 > NumBits2;
13189 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13190 return isInt<32>(Imm);
13193 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13194 // Can also use sub to handle negated immediates.
13195 return isInt<32>(Imm);
13198 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13199 if (!VT1.isInteger() || !VT2.isInteger())
13201 unsigned NumBits1 = VT1.getSizeInBits();
13202 unsigned NumBits2 = VT2.getSizeInBits();
13203 return NumBits1 > NumBits2;
13206 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13207 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13208 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13211 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13212 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13213 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13216 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13217 EVT VT1 = Val.getValueType();
13218 if (isZExtFree(VT1, VT2))
13221 if (Val.getOpcode() != ISD::LOAD)
13224 if (!VT1.isSimple() || !VT1.isInteger() ||
13225 !VT2.isSimple() || !VT2.isInteger())
13228 switch (VT1.getSimpleVT().SimpleTy) {
13233 // X86 has 8, 16, and 32-bit zero-extending loads.
13241 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13242 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13245 VT = VT.getScalarType();
13247 if (!VT.isSimple())
13250 switch (VT.getSimpleVT().SimpleTy) {
13261 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13262 // i16 instructions are longer (0x66 prefix) and potentially slower.
13263 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13266 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13267 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13268 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13269 /// are assumed to be legal.
13271 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13273 // Very little shuffling can be done for 64-bit vectors right now.
13274 if (VT.getSizeInBits() == 64)
13277 // FIXME: pshufb, blends, shifts.
13278 return (VT.getVectorNumElements() == 2 ||
13279 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13280 isMOVLMask(M, VT) ||
13281 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13282 isPSHUFDMask(M, VT) ||
13283 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13284 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13285 isPALIGNRMask(M, VT, Subtarget) ||
13286 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13287 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13288 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13289 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13293 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13295 unsigned NumElts = VT.getVectorNumElements();
13296 // FIXME: This collection of masks seems suspect.
13299 if (NumElts == 4 && VT.is128BitVector()) {
13300 return (isMOVLMask(Mask, VT) ||
13301 isCommutedMOVLMask(Mask, VT, true) ||
13302 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13303 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13308 //===----------------------------------------------------------------------===//
13309 // X86 Scheduler Hooks
13310 //===----------------------------------------------------------------------===//
13312 /// Utility function to emit xbegin specifying the start of an RTM region.
13313 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13314 const TargetInstrInfo *TII) {
13315 DebugLoc DL = MI->getDebugLoc();
13317 const BasicBlock *BB = MBB->getBasicBlock();
13318 MachineFunction::iterator I = MBB;
13321 // For the v = xbegin(), we generate
13332 MachineBasicBlock *thisMBB = MBB;
13333 MachineFunction *MF = MBB->getParent();
13334 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13335 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13336 MF->insert(I, mainMBB);
13337 MF->insert(I, sinkMBB);
13339 // Transfer the remainder of BB and its successor edges to sinkMBB.
13340 sinkMBB->splice(sinkMBB->begin(), MBB,
13341 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13342 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13346 // # fallthrough to mainMBB
13347 // # abortion to sinkMBB
13348 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13349 thisMBB->addSuccessor(mainMBB);
13350 thisMBB->addSuccessor(sinkMBB);
13354 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13355 mainMBB->addSuccessor(sinkMBB);
13358 // EAX is live into the sinkMBB
13359 sinkMBB->addLiveIn(X86::EAX);
13360 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13361 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13364 MI->eraseFromParent();
13368 // Get CMPXCHG opcode for the specified data type.
13369 static unsigned getCmpXChgOpcode(EVT VT) {
13370 switch (VT.getSimpleVT().SimpleTy) {
13371 case MVT::i8: return X86::LCMPXCHG8;
13372 case MVT::i16: return X86::LCMPXCHG16;
13373 case MVT::i32: return X86::LCMPXCHG32;
13374 case MVT::i64: return X86::LCMPXCHG64;
13378 llvm_unreachable("Invalid operand size!");
13381 // Get LOAD opcode for the specified data type.
13382 static unsigned getLoadOpcode(EVT VT) {
13383 switch (VT.getSimpleVT().SimpleTy) {
13384 case MVT::i8: return X86::MOV8rm;
13385 case MVT::i16: return X86::MOV16rm;
13386 case MVT::i32: return X86::MOV32rm;
13387 case MVT::i64: return X86::MOV64rm;
13391 llvm_unreachable("Invalid operand size!");
13394 // Get opcode of the non-atomic one from the specified atomic instruction.
13395 static unsigned getNonAtomicOpcode(unsigned Opc) {
13397 case X86::ATOMAND8: return X86::AND8rr;
13398 case X86::ATOMAND16: return X86::AND16rr;
13399 case X86::ATOMAND32: return X86::AND32rr;
13400 case X86::ATOMAND64: return X86::AND64rr;
13401 case X86::ATOMOR8: return X86::OR8rr;
13402 case X86::ATOMOR16: return X86::OR16rr;
13403 case X86::ATOMOR32: return X86::OR32rr;
13404 case X86::ATOMOR64: return X86::OR64rr;
13405 case X86::ATOMXOR8: return X86::XOR8rr;
13406 case X86::ATOMXOR16: return X86::XOR16rr;
13407 case X86::ATOMXOR32: return X86::XOR32rr;
13408 case X86::ATOMXOR64: return X86::XOR64rr;
13410 llvm_unreachable("Unhandled atomic-load-op opcode!");
13413 // Get opcode of the non-atomic one from the specified atomic instruction with
13415 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13416 unsigned &ExtraOpc) {
13418 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
13419 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
13420 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
13421 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
13422 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
13423 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13424 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13425 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13426 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
13427 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13428 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13429 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13430 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
13431 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13432 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13433 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13434 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
13435 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13436 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13437 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13439 llvm_unreachable("Unhandled atomic-load-op opcode!");
13442 // Get opcode of the non-atomic one from the specified atomic instruction for
13443 // 64-bit data type on 32-bit target.
13444 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13446 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
13447 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
13448 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
13449 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
13450 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
13451 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13452 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
13453 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
13454 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
13455 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
13457 llvm_unreachable("Unhandled atomic-load-op opcode!");
13460 // Get opcode of the non-atomic one from the specified atomic instruction for
13461 // 64-bit data type on 32-bit target with extra opcode.
13462 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13464 unsigned &ExtraOpc) {
13466 case X86::ATOMNAND6432:
13467 ExtraOpc = X86::NOT32r;
13468 HiOpc = X86::AND32rr;
13469 return X86::AND32rr;
13471 llvm_unreachable("Unhandled atomic-load-op opcode!");
13474 // Get pseudo CMOV opcode from the specified data type.
13475 static unsigned getPseudoCMOVOpc(EVT VT) {
13476 switch (VT.getSimpleVT().SimpleTy) {
13477 case MVT::i8: return X86::CMOV_GR8;
13478 case MVT::i16: return X86::CMOV_GR16;
13479 case MVT::i32: return X86::CMOV_GR32;
13483 llvm_unreachable("Unknown CMOV opcode!");
13486 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13487 // They will be translated into a spin-loop or compare-exchange loop from
13490 // dst = atomic-fetch-op MI.addr, MI.val
13496 // t1 = LOAD MI.addr
13498 // t4 = phi(t1, t3 / loop)
13499 // t2 = OP MI.val, t4
13501 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13507 MachineBasicBlock *
13508 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13509 MachineBasicBlock *MBB) const {
13510 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13511 DebugLoc DL = MI->getDebugLoc();
13513 MachineFunction *MF = MBB->getParent();
13514 MachineRegisterInfo &MRI = MF->getRegInfo();
13516 const BasicBlock *BB = MBB->getBasicBlock();
13517 MachineFunction::iterator I = MBB;
13520 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13521 "Unexpected number of operands");
13523 assert(MI->hasOneMemOperand() &&
13524 "Expected atomic-load-op to have one memoperand");
13526 // Memory Reference
13527 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13528 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13530 unsigned DstReg, SrcReg;
13531 unsigned MemOpndSlot;
13533 unsigned CurOp = 0;
13535 DstReg = MI->getOperand(CurOp++).getReg();
13536 MemOpndSlot = CurOp;
13537 CurOp += X86::AddrNumOperands;
13538 SrcReg = MI->getOperand(CurOp++).getReg();
13540 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13541 MVT::SimpleValueType VT = *RC->vt_begin();
13542 unsigned t1 = MRI.createVirtualRegister(RC);
13543 unsigned t2 = MRI.createVirtualRegister(RC);
13544 unsigned t3 = MRI.createVirtualRegister(RC);
13545 unsigned t4 = MRI.createVirtualRegister(RC);
13546 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13548 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13549 unsigned LOADOpc = getLoadOpcode(VT);
13551 // For the atomic load-arith operator, we generate
13554 // t1 = LOAD [MI.addr]
13556 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
13557 // t1 = OP MI.val, EAX
13559 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13565 MachineBasicBlock *thisMBB = MBB;
13566 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13567 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13568 MF->insert(I, mainMBB);
13569 MF->insert(I, sinkMBB);
13571 MachineInstrBuilder MIB;
13573 // Transfer the remainder of BB and its successor edges to sinkMBB.
13574 sinkMBB->splice(sinkMBB->begin(), MBB,
13575 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13576 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13579 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13580 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13581 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13583 NewMO.setIsKill(false);
13584 MIB.addOperand(NewMO);
13586 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13587 unsigned flags = (*MMOI)->getFlags();
13588 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13589 MachineMemOperand *MMO =
13590 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13591 (*MMOI)->getSize(),
13592 (*MMOI)->getBaseAlignment(),
13593 (*MMOI)->getTBAAInfo(),
13594 (*MMOI)->getRanges());
13595 MIB.addMemOperand(MMO);
13598 thisMBB->addSuccessor(mainMBB);
13601 MachineBasicBlock *origMainMBB = mainMBB;
13604 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13605 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13607 unsigned Opc = MI->getOpcode();
13610 llvm_unreachable("Unhandled atomic-load-op opcode!");
13611 case X86::ATOMAND8:
13612 case X86::ATOMAND16:
13613 case X86::ATOMAND32:
13614 case X86::ATOMAND64:
13616 case X86::ATOMOR16:
13617 case X86::ATOMOR32:
13618 case X86::ATOMOR64:
13619 case X86::ATOMXOR8:
13620 case X86::ATOMXOR16:
13621 case X86::ATOMXOR32:
13622 case X86::ATOMXOR64: {
13623 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13624 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13628 case X86::ATOMNAND8:
13629 case X86::ATOMNAND16:
13630 case X86::ATOMNAND32:
13631 case X86::ATOMNAND64: {
13632 unsigned Tmp = MRI.createVirtualRegister(RC);
13634 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13635 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13637 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13640 case X86::ATOMMAX8:
13641 case X86::ATOMMAX16:
13642 case X86::ATOMMAX32:
13643 case X86::ATOMMAX64:
13644 case X86::ATOMMIN8:
13645 case X86::ATOMMIN16:
13646 case X86::ATOMMIN32:
13647 case X86::ATOMMIN64:
13648 case X86::ATOMUMAX8:
13649 case X86::ATOMUMAX16:
13650 case X86::ATOMUMAX32:
13651 case X86::ATOMUMAX64:
13652 case X86::ATOMUMIN8:
13653 case X86::ATOMUMIN16:
13654 case X86::ATOMUMIN32:
13655 case X86::ATOMUMIN64: {
13657 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13659 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13663 if (Subtarget->hasCMov()) {
13664 if (VT != MVT::i8) {
13666 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13670 // Promote i8 to i32 to use CMOV32
13671 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13672 const TargetRegisterClass *RC32 =
13673 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13674 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13675 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13676 unsigned Tmp = MRI.createVirtualRegister(RC32);
13678 unsigned Undef = MRI.createVirtualRegister(RC32);
13679 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13681 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13684 .addImm(X86::sub_8bit);
13685 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13688 .addImm(X86::sub_8bit);
13690 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13694 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13695 .addReg(Tmp, 0, X86::sub_8bit);
13698 // Use pseudo select and lower them.
13699 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13700 "Invalid atomic-load-op transformation!");
13701 unsigned SelOpc = getPseudoCMOVOpc(VT);
13702 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13703 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13704 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13705 .addReg(SrcReg).addReg(t4)
13707 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13708 // Replace the original PHI node as mainMBB is changed after CMOV
13710 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13711 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13712 Phi->eraseFromParent();
13718 // Copy PhyReg back from virtual register.
13719 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13722 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13723 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13724 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13726 NewMO.setIsKill(false);
13727 MIB.addOperand(NewMO);
13730 MIB.setMemRefs(MMOBegin, MMOEnd);
13732 // Copy PhyReg back to virtual register.
13733 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13736 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13738 mainMBB->addSuccessor(origMainMBB);
13739 mainMBB->addSuccessor(sinkMBB);
13742 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13743 TII->get(TargetOpcode::COPY), DstReg)
13746 MI->eraseFromParent();
13750 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13751 // instructions. They will be translated into a spin-loop or compare-exchange
13755 // dst = atomic-fetch-op MI.addr, MI.val
13761 // t1L = LOAD [MI.addr + 0]
13762 // t1H = LOAD [MI.addr + 4]
13764 // t4L = phi(t1L, t3L / loop)
13765 // t4H = phi(t1H, t3H / loop)
13766 // t2L = OP MI.val.lo, t4L
13767 // t2H = OP MI.val.hi, t4H
13772 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13780 MachineBasicBlock *
13781 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13782 MachineBasicBlock *MBB) const {
13783 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13784 DebugLoc DL = MI->getDebugLoc();
13786 MachineFunction *MF = MBB->getParent();
13787 MachineRegisterInfo &MRI = MF->getRegInfo();
13789 const BasicBlock *BB = MBB->getBasicBlock();
13790 MachineFunction::iterator I = MBB;
13793 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13794 "Unexpected number of operands");
13796 assert(MI->hasOneMemOperand() &&
13797 "Expected atomic-load-op32 to have one memoperand");
13799 // Memory Reference
13800 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13801 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13803 unsigned DstLoReg, DstHiReg;
13804 unsigned SrcLoReg, SrcHiReg;
13805 unsigned MemOpndSlot;
13807 unsigned CurOp = 0;
13809 DstLoReg = MI->getOperand(CurOp++).getReg();
13810 DstHiReg = MI->getOperand(CurOp++).getReg();
13811 MemOpndSlot = CurOp;
13812 CurOp += X86::AddrNumOperands;
13813 SrcLoReg = MI->getOperand(CurOp++).getReg();
13814 SrcHiReg = MI->getOperand(CurOp++).getReg();
13816 const TargetRegisterClass *RC = &X86::GR32RegClass;
13817 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13819 unsigned t1L = MRI.createVirtualRegister(RC);
13820 unsigned t1H = MRI.createVirtualRegister(RC);
13821 unsigned t2L = MRI.createVirtualRegister(RC);
13822 unsigned t2H = MRI.createVirtualRegister(RC);
13823 unsigned t3L = MRI.createVirtualRegister(RC);
13824 unsigned t3H = MRI.createVirtualRegister(RC);
13825 unsigned t4L = MRI.createVirtualRegister(RC);
13826 unsigned t4H = MRI.createVirtualRegister(RC);
13828 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13829 unsigned LOADOpc = X86::MOV32rm;
13831 // For the atomic load-arith operator, we generate
13834 // t1L = LOAD [MI.addr + 0]
13835 // t1H = LOAD [MI.addr + 4]
13837 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
13838 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
13839 // t2L = OP MI.val.lo, t4L
13840 // t2H = OP MI.val.hi, t4H
13843 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13851 MachineBasicBlock *thisMBB = MBB;
13852 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13853 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13854 MF->insert(I, mainMBB);
13855 MF->insert(I, sinkMBB);
13857 MachineInstrBuilder MIB;
13859 // Transfer the remainder of BB and its successor edges to sinkMBB.
13860 sinkMBB->splice(sinkMBB->begin(), MBB,
13861 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13862 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13866 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13867 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13868 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13870 NewMO.setIsKill(false);
13871 MIB.addOperand(NewMO);
13873 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13874 unsigned flags = (*MMOI)->getFlags();
13875 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13876 MachineMemOperand *MMO =
13877 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13878 (*MMOI)->getSize(),
13879 (*MMOI)->getBaseAlignment(),
13880 (*MMOI)->getTBAAInfo(),
13881 (*MMOI)->getRanges());
13882 MIB.addMemOperand(MMO);
13884 MachineInstr *LowMI = MIB;
13887 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13888 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13889 if (i == X86::AddrDisp) {
13890 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13892 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13894 NewMO.setIsKill(false);
13895 MIB.addOperand(NewMO);
13898 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13900 thisMBB->addSuccessor(mainMBB);
13903 MachineBasicBlock *origMainMBB = mainMBB;
13906 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13907 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13908 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13909 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13911 unsigned Opc = MI->getOpcode();
13914 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13915 case X86::ATOMAND6432:
13916 case X86::ATOMOR6432:
13917 case X86::ATOMXOR6432:
13918 case X86::ATOMADD6432:
13919 case X86::ATOMSUB6432: {
13921 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13922 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13924 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13928 case X86::ATOMNAND6432: {
13929 unsigned HiOpc, NOTOpc;
13930 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13931 unsigned TmpL = MRI.createVirtualRegister(RC);
13932 unsigned TmpH = MRI.createVirtualRegister(RC);
13933 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13935 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13937 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13938 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13941 case X86::ATOMMAX6432:
13942 case X86::ATOMMIN6432:
13943 case X86::ATOMUMAX6432:
13944 case X86::ATOMUMIN6432: {
13946 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13947 unsigned cL = MRI.createVirtualRegister(RC8);
13948 unsigned cH = MRI.createVirtualRegister(RC8);
13949 unsigned cL32 = MRI.createVirtualRegister(RC);
13950 unsigned cH32 = MRI.createVirtualRegister(RC);
13951 unsigned cc = MRI.createVirtualRegister(RC);
13952 // cl := cmp src_lo, lo
13953 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13954 .addReg(SrcLoReg).addReg(t4L);
13955 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13956 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13957 // ch := cmp src_hi, hi
13958 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13959 .addReg(SrcHiReg).addReg(t4H);
13960 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13961 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13962 // cc := if (src_hi == hi) ? cl : ch;
13963 if (Subtarget->hasCMov()) {
13964 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13965 .addReg(cH32).addReg(cL32);
13967 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13968 .addReg(cH32).addReg(cL32)
13969 .addImm(X86::COND_E);
13970 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13972 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13973 if (Subtarget->hasCMov()) {
13974 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13975 .addReg(SrcLoReg).addReg(t4L);
13976 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13977 .addReg(SrcHiReg).addReg(t4H);
13979 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13980 .addReg(SrcLoReg).addReg(t4L)
13981 .addImm(X86::COND_NE);
13982 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13983 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13984 // 2nd CMOV lowering.
13985 mainMBB->addLiveIn(X86::EFLAGS);
13986 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13987 .addReg(SrcHiReg).addReg(t4H)
13988 .addImm(X86::COND_NE);
13989 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13990 // Replace the original PHI node as mainMBB is changed after CMOV
13992 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13993 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13994 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13995 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13996 PhiL->eraseFromParent();
13997 PhiH->eraseFromParent();
14001 case X86::ATOMSWAP6432: {
14003 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14004 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14005 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14010 // Copy EDX:EAX back from HiReg:LoReg
14011 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14012 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14013 // Copy ECX:EBX from t1H:t1L
14014 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14015 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14017 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14018 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14019 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14021 NewMO.setIsKill(false);
14022 MIB.addOperand(NewMO);
14024 MIB.setMemRefs(MMOBegin, MMOEnd);
14026 // Copy EDX:EAX back to t3H:t3L
14027 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14028 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14030 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14032 mainMBB->addSuccessor(origMainMBB);
14033 mainMBB->addSuccessor(sinkMBB);
14036 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14037 TII->get(TargetOpcode::COPY), DstLoReg)
14039 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14040 TII->get(TargetOpcode::COPY), DstHiReg)
14043 MI->eraseFromParent();
14047 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14048 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14049 // in the .td file.
14050 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14051 const TargetInstrInfo *TII) {
14053 switch (MI->getOpcode()) {
14054 default: llvm_unreachable("illegal opcode!");
14055 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
14056 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14057 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
14058 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14059 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
14060 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14061 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
14062 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14065 DebugLoc dl = MI->getDebugLoc();
14066 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14068 unsigned NumArgs = MI->getNumOperands();
14069 for (unsigned i = 1; i < NumArgs; ++i) {
14070 MachineOperand &Op = MI->getOperand(i);
14071 if (!(Op.isReg() && Op.isImplicit()))
14072 MIB.addOperand(Op);
14074 if (MI->hasOneMemOperand())
14075 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14077 BuildMI(*BB, MI, dl,
14078 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14079 .addReg(X86::XMM0);
14081 MI->eraseFromParent();
14085 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14086 // defs in an instruction pattern
14087 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14088 const TargetInstrInfo *TII) {
14090 switch (MI->getOpcode()) {
14091 default: llvm_unreachable("illegal opcode!");
14092 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
14093 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14094 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
14095 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14096 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
14097 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14098 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
14099 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14102 DebugLoc dl = MI->getDebugLoc();
14103 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14105 unsigned NumArgs = MI->getNumOperands(); // remove the results
14106 for (unsigned i = 1; i < NumArgs; ++i) {
14107 MachineOperand &Op = MI->getOperand(i);
14108 if (!(Op.isReg() && Op.isImplicit()))
14109 MIB.addOperand(Op);
14111 if (MI->hasOneMemOperand())
14112 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14114 BuildMI(*BB, MI, dl,
14115 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14118 MI->eraseFromParent();
14122 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14123 const TargetInstrInfo *TII,
14124 const X86Subtarget* Subtarget) {
14125 DebugLoc dl = MI->getDebugLoc();
14127 // Address into RAX/EAX, other two args into ECX, EDX.
14128 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14129 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14130 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14131 for (int i = 0; i < X86::AddrNumOperands; ++i)
14132 MIB.addOperand(MI->getOperand(i));
14134 unsigned ValOps = X86::AddrNumOperands;
14135 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14136 .addReg(MI->getOperand(ValOps).getReg());
14137 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14138 .addReg(MI->getOperand(ValOps+1).getReg());
14140 // The instruction doesn't actually take any operands though.
14141 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14143 MI->eraseFromParent(); // The pseudo is gone now.
14147 MachineBasicBlock *
14148 X86TargetLowering::EmitVAARG64WithCustomInserter(
14150 MachineBasicBlock *MBB) const {
14151 // Emit va_arg instruction on X86-64.
14153 // Operands to this pseudo-instruction:
14154 // 0 ) Output : destination address (reg)
14155 // 1-5) Input : va_list address (addr, i64mem)
14156 // 6 ) ArgSize : Size (in bytes) of vararg type
14157 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14158 // 8 ) Align : Alignment of type
14159 // 9 ) EFLAGS (implicit-def)
14161 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14162 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14164 unsigned DestReg = MI->getOperand(0).getReg();
14165 MachineOperand &Base = MI->getOperand(1);
14166 MachineOperand &Scale = MI->getOperand(2);
14167 MachineOperand &Index = MI->getOperand(3);
14168 MachineOperand &Disp = MI->getOperand(4);
14169 MachineOperand &Segment = MI->getOperand(5);
14170 unsigned ArgSize = MI->getOperand(6).getImm();
14171 unsigned ArgMode = MI->getOperand(7).getImm();
14172 unsigned Align = MI->getOperand(8).getImm();
14174 // Memory Reference
14175 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14176 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14177 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14179 // Machine Information
14180 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14181 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14182 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14183 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14184 DebugLoc DL = MI->getDebugLoc();
14186 // struct va_list {
14189 // i64 overflow_area (address)
14190 // i64 reg_save_area (address)
14192 // sizeof(va_list) = 24
14193 // alignment(va_list) = 8
14195 unsigned TotalNumIntRegs = 6;
14196 unsigned TotalNumXMMRegs = 8;
14197 bool UseGPOffset = (ArgMode == 1);
14198 bool UseFPOffset = (ArgMode == 2);
14199 unsigned MaxOffset = TotalNumIntRegs * 8 +
14200 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14202 /* Align ArgSize to a multiple of 8 */
14203 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14204 bool NeedsAlign = (Align > 8);
14206 MachineBasicBlock *thisMBB = MBB;
14207 MachineBasicBlock *overflowMBB;
14208 MachineBasicBlock *offsetMBB;
14209 MachineBasicBlock *endMBB;
14211 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
14212 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
14213 unsigned OffsetReg = 0;
14215 if (!UseGPOffset && !UseFPOffset) {
14216 // If we only pull from the overflow region, we don't create a branch.
14217 // We don't need to alter control flow.
14218 OffsetDestReg = 0; // unused
14219 OverflowDestReg = DestReg;
14222 overflowMBB = thisMBB;
14225 // First emit code to check if gp_offset (or fp_offset) is below the bound.
14226 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14227 // If not, pull from overflow_area. (branch to overflowMBB)
14232 // offsetMBB overflowMBB
14237 // Registers for the PHI in endMBB
14238 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14239 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14241 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14242 MachineFunction *MF = MBB->getParent();
14243 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14244 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14245 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14247 MachineFunction::iterator MBBIter = MBB;
14250 // Insert the new basic blocks
14251 MF->insert(MBBIter, offsetMBB);
14252 MF->insert(MBBIter, overflowMBB);
14253 MF->insert(MBBIter, endMBB);
14255 // Transfer the remainder of MBB and its successor edges to endMBB.
14256 endMBB->splice(endMBB->begin(), thisMBB,
14257 llvm::next(MachineBasicBlock::iterator(MI)),
14259 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14261 // Make offsetMBB and overflowMBB successors of thisMBB
14262 thisMBB->addSuccessor(offsetMBB);
14263 thisMBB->addSuccessor(overflowMBB);
14265 // endMBB is a successor of both offsetMBB and overflowMBB
14266 offsetMBB->addSuccessor(endMBB);
14267 overflowMBB->addSuccessor(endMBB);
14269 // Load the offset value into a register
14270 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14271 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14275 .addDisp(Disp, UseFPOffset ? 4 : 0)
14276 .addOperand(Segment)
14277 .setMemRefs(MMOBegin, MMOEnd);
14279 // Check if there is enough room left to pull this argument.
14280 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14282 .addImm(MaxOffset + 8 - ArgSizeA8);
14284 // Branch to "overflowMBB" if offset >= max
14285 // Fall through to "offsetMBB" otherwise
14286 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14287 .addMBB(overflowMBB);
14290 // In offsetMBB, emit code to use the reg_save_area.
14292 assert(OffsetReg != 0);
14294 // Read the reg_save_area address.
14295 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14296 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14301 .addOperand(Segment)
14302 .setMemRefs(MMOBegin, MMOEnd);
14304 // Zero-extend the offset
14305 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14306 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14309 .addImm(X86::sub_32bit);
14311 // Add the offset to the reg_save_area to get the final address.
14312 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14313 .addReg(OffsetReg64)
14314 .addReg(RegSaveReg);
14316 // Compute the offset for the next argument
14317 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14318 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14320 .addImm(UseFPOffset ? 16 : 8);
14322 // Store it back into the va_list.
14323 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14327 .addDisp(Disp, UseFPOffset ? 4 : 0)
14328 .addOperand(Segment)
14329 .addReg(NextOffsetReg)
14330 .setMemRefs(MMOBegin, MMOEnd);
14333 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14338 // Emit code to use overflow area
14341 // Load the overflow_area address into a register.
14342 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14343 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14348 .addOperand(Segment)
14349 .setMemRefs(MMOBegin, MMOEnd);
14351 // If we need to align it, do so. Otherwise, just copy the address
14352 // to OverflowDestReg.
14354 // Align the overflow address
14355 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14356 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14358 // aligned_addr = (addr + (align-1)) & ~(align-1)
14359 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14360 .addReg(OverflowAddrReg)
14363 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14365 .addImm(~(uint64_t)(Align-1));
14367 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14368 .addReg(OverflowAddrReg);
14371 // Compute the next overflow address after this argument.
14372 // (the overflow address should be kept 8-byte aligned)
14373 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14374 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14375 .addReg(OverflowDestReg)
14376 .addImm(ArgSizeA8);
14378 // Store the new overflow address.
14379 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14384 .addOperand(Segment)
14385 .addReg(NextAddrReg)
14386 .setMemRefs(MMOBegin, MMOEnd);
14388 // If we branched, emit the PHI to the front of endMBB.
14390 BuildMI(*endMBB, endMBB->begin(), DL,
14391 TII->get(X86::PHI), DestReg)
14392 .addReg(OffsetDestReg).addMBB(offsetMBB)
14393 .addReg(OverflowDestReg).addMBB(overflowMBB);
14396 // Erase the pseudo instruction
14397 MI->eraseFromParent();
14402 MachineBasicBlock *
14403 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14405 MachineBasicBlock *MBB) const {
14406 // Emit code to save XMM registers to the stack. The ABI says that the
14407 // number of registers to save is given in %al, so it's theoretically
14408 // possible to do an indirect jump trick to avoid saving all of them,
14409 // however this code takes a simpler approach and just executes all
14410 // of the stores if %al is non-zero. It's less code, and it's probably
14411 // easier on the hardware branch predictor, and stores aren't all that
14412 // expensive anyway.
14414 // Create the new basic blocks. One block contains all the XMM stores,
14415 // and one block is the final destination regardless of whether any
14416 // stores were performed.
14417 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14418 MachineFunction *F = MBB->getParent();
14419 MachineFunction::iterator MBBIter = MBB;
14421 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14422 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14423 F->insert(MBBIter, XMMSaveMBB);
14424 F->insert(MBBIter, EndMBB);
14426 // Transfer the remainder of MBB and its successor edges to EndMBB.
14427 EndMBB->splice(EndMBB->begin(), MBB,
14428 llvm::next(MachineBasicBlock::iterator(MI)),
14430 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14432 // The original block will now fall through to the XMM save block.
14433 MBB->addSuccessor(XMMSaveMBB);
14434 // The XMMSaveMBB will fall through to the end block.
14435 XMMSaveMBB->addSuccessor(EndMBB);
14437 // Now add the instructions.
14438 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14439 DebugLoc DL = MI->getDebugLoc();
14441 unsigned CountReg = MI->getOperand(0).getReg();
14442 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14443 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14445 if (!Subtarget->isTargetWin64()) {
14446 // If %al is 0, branch around the XMM save block.
14447 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14448 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14449 MBB->addSuccessor(EndMBB);
14452 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14453 // In the XMM save block, save all the XMM argument registers.
14454 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14455 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14456 MachineMemOperand *MMO =
14457 F->getMachineMemOperand(
14458 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14459 MachineMemOperand::MOStore,
14460 /*Size=*/16, /*Align=*/16);
14461 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14462 .addFrameIndex(RegSaveFrameIndex)
14463 .addImm(/*Scale=*/1)
14464 .addReg(/*IndexReg=*/0)
14465 .addImm(/*Disp=*/Offset)
14466 .addReg(/*Segment=*/0)
14467 .addReg(MI->getOperand(i).getReg())
14468 .addMemOperand(MMO);
14471 MI->eraseFromParent(); // The pseudo instruction is gone now.
14476 // The EFLAGS operand of SelectItr might be missing a kill marker
14477 // because there were multiple uses of EFLAGS, and ISel didn't know
14478 // which to mark. Figure out whether SelectItr should have had a
14479 // kill marker, and set it if it should. Returns the correct kill
14481 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14482 MachineBasicBlock* BB,
14483 const TargetRegisterInfo* TRI) {
14484 // Scan forward through BB for a use/def of EFLAGS.
14485 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14486 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14487 const MachineInstr& mi = *miI;
14488 if (mi.readsRegister(X86::EFLAGS))
14490 if (mi.definesRegister(X86::EFLAGS))
14491 break; // Should have kill-flag - update below.
14494 // If we hit the end of the block, check whether EFLAGS is live into a
14496 if (miI == BB->end()) {
14497 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14498 sEnd = BB->succ_end();
14499 sItr != sEnd; ++sItr) {
14500 MachineBasicBlock* succ = *sItr;
14501 if (succ->isLiveIn(X86::EFLAGS))
14506 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14507 // out. SelectMI should have a kill flag on EFLAGS.
14508 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14512 MachineBasicBlock *
14513 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14514 MachineBasicBlock *BB) const {
14515 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14516 DebugLoc DL = MI->getDebugLoc();
14518 // To "insert" a SELECT_CC instruction, we actually have to insert the
14519 // diamond control-flow pattern. The incoming instruction knows the
14520 // destination vreg to set, the condition code register to branch on, the
14521 // true/false values to select between, and a branch opcode to use.
14522 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14523 MachineFunction::iterator It = BB;
14529 // cmpTY ccX, r1, r2
14531 // fallthrough --> copy0MBB
14532 MachineBasicBlock *thisMBB = BB;
14533 MachineFunction *F = BB->getParent();
14534 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14535 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14536 F->insert(It, copy0MBB);
14537 F->insert(It, sinkMBB);
14539 // If the EFLAGS register isn't dead in the terminator, then claim that it's
14540 // live into the sink and copy blocks.
14541 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14542 if (!MI->killsRegister(X86::EFLAGS) &&
14543 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14544 copy0MBB->addLiveIn(X86::EFLAGS);
14545 sinkMBB->addLiveIn(X86::EFLAGS);
14548 // Transfer the remainder of BB and its successor edges to sinkMBB.
14549 sinkMBB->splice(sinkMBB->begin(), BB,
14550 llvm::next(MachineBasicBlock::iterator(MI)),
14552 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14554 // Add the true and fallthrough blocks as its successors.
14555 BB->addSuccessor(copy0MBB);
14556 BB->addSuccessor(sinkMBB);
14558 // Create the conditional branch instruction.
14560 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14561 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14564 // %FalseValue = ...
14565 // # fallthrough to sinkMBB
14566 copy0MBB->addSuccessor(sinkMBB);
14569 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14571 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14572 TII->get(X86::PHI), MI->getOperand(0).getReg())
14573 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14574 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14576 MI->eraseFromParent(); // The pseudo instruction is gone now.
14580 MachineBasicBlock *
14581 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14582 bool Is64Bit) const {
14583 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14584 DebugLoc DL = MI->getDebugLoc();
14585 MachineFunction *MF = BB->getParent();
14586 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14588 assert(getTargetMachine().Options.EnableSegmentedStacks);
14590 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14591 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14594 // ... [Till the alloca]
14595 // If stacklet is not large enough, jump to mallocMBB
14598 // Allocate by subtracting from RSP
14599 // Jump to continueMBB
14602 // Allocate by call to runtime
14606 // [rest of original BB]
14609 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14610 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14611 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14613 MachineRegisterInfo &MRI = MF->getRegInfo();
14614 const TargetRegisterClass *AddrRegClass =
14615 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14617 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14618 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14619 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14620 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14621 sizeVReg = MI->getOperand(1).getReg(),
14622 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14624 MachineFunction::iterator MBBIter = BB;
14627 MF->insert(MBBIter, bumpMBB);
14628 MF->insert(MBBIter, mallocMBB);
14629 MF->insert(MBBIter, continueMBB);
14631 continueMBB->splice(continueMBB->begin(), BB, llvm::next
14632 (MachineBasicBlock::iterator(MI)), BB->end());
14633 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14635 // Add code to the main basic block to check if the stack limit has been hit,
14636 // and if so, jump to mallocMBB otherwise to bumpMBB.
14637 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14638 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14639 .addReg(tmpSPVReg).addReg(sizeVReg);
14640 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14641 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14642 .addReg(SPLimitVReg);
14643 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14645 // bumpMBB simply decreases the stack pointer, since we know the current
14646 // stacklet has enough space.
14647 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14648 .addReg(SPLimitVReg);
14649 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14650 .addReg(SPLimitVReg);
14651 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14653 // Calls into a routine in libgcc to allocate more space from the heap.
14654 const uint32_t *RegMask =
14655 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14657 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14659 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14660 .addExternalSymbol("__morestack_allocate_stack_space")
14661 .addRegMask(RegMask)
14662 .addReg(X86::RDI, RegState::Implicit)
14663 .addReg(X86::RAX, RegState::ImplicitDefine);
14665 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14667 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14668 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14669 .addExternalSymbol("__morestack_allocate_stack_space")
14670 .addRegMask(RegMask)
14671 .addReg(X86::EAX, RegState::ImplicitDefine);
14675 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14678 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14679 .addReg(Is64Bit ? X86::RAX : X86::EAX);
14680 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14682 // Set up the CFG correctly.
14683 BB->addSuccessor(bumpMBB);
14684 BB->addSuccessor(mallocMBB);
14685 mallocMBB->addSuccessor(continueMBB);
14686 bumpMBB->addSuccessor(continueMBB);
14688 // Take care of the PHI nodes.
14689 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14690 MI->getOperand(0).getReg())
14691 .addReg(mallocPtrVReg).addMBB(mallocMBB)
14692 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14694 // Delete the original pseudo instruction.
14695 MI->eraseFromParent();
14698 return continueMBB;
14701 MachineBasicBlock *
14702 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14703 MachineBasicBlock *BB) const {
14704 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14705 DebugLoc DL = MI->getDebugLoc();
14707 assert(!Subtarget->isTargetEnvMacho());
14709 // The lowering is pretty easy: we're just emitting the call to _alloca. The
14710 // non-trivial part is impdef of ESP.
14712 if (Subtarget->isTargetWin64()) {
14713 if (Subtarget->isTargetCygMing()) {
14714 // ___chkstk(Mingw64):
14715 // Clobbers R10, R11, RAX and EFLAGS.
14717 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14718 .addExternalSymbol("___chkstk")
14719 .addReg(X86::RAX, RegState::Implicit)
14720 .addReg(X86::RSP, RegState::Implicit)
14721 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14722 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14723 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14725 // __chkstk(MSVCRT): does not update stack pointer.
14726 // Clobbers R10, R11 and EFLAGS.
14727 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14728 .addExternalSymbol("__chkstk")
14729 .addReg(X86::RAX, RegState::Implicit)
14730 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14731 // RAX has the offset to be subtracted from RSP.
14732 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14737 const char *StackProbeSymbol =
14738 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14740 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14741 .addExternalSymbol(StackProbeSymbol)
14742 .addReg(X86::EAX, RegState::Implicit)
14743 .addReg(X86::ESP, RegState::Implicit)
14744 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14745 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14746 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14749 MI->eraseFromParent(); // The pseudo instruction is gone now.
14753 MachineBasicBlock *
14754 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14755 MachineBasicBlock *BB) const {
14756 // This is pretty easy. We're taking the value that we received from
14757 // our load from the relocation, sticking it in either RDI (x86-64)
14758 // or EAX and doing an indirect call. The return value will then
14759 // be in the normal return register.
14760 const X86InstrInfo *TII
14761 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14762 DebugLoc DL = MI->getDebugLoc();
14763 MachineFunction *F = BB->getParent();
14765 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14766 assert(MI->getOperand(3).isGlobal() && "This should be a global");
14768 // Get a register mask for the lowered call.
14769 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14770 // proper register mask.
14771 const uint32_t *RegMask =
14772 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14773 if (Subtarget->is64Bit()) {
14774 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14775 TII->get(X86::MOV64rm), X86::RDI)
14777 .addImm(0).addReg(0)
14778 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14779 MI->getOperand(3).getTargetFlags())
14781 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14782 addDirectMem(MIB, X86::RDI);
14783 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14784 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14785 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14786 TII->get(X86::MOV32rm), X86::EAX)
14788 .addImm(0).addReg(0)
14789 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14790 MI->getOperand(3).getTargetFlags())
14792 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14793 addDirectMem(MIB, X86::EAX);
14794 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14796 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14797 TII->get(X86::MOV32rm), X86::EAX)
14798 .addReg(TII->getGlobalBaseReg(F))
14799 .addImm(0).addReg(0)
14800 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14801 MI->getOperand(3).getTargetFlags())
14803 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14804 addDirectMem(MIB, X86::EAX);
14805 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14808 MI->eraseFromParent(); // The pseudo instruction is gone now.
14812 MachineBasicBlock *
14813 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14814 MachineBasicBlock *MBB) const {
14815 DebugLoc DL = MI->getDebugLoc();
14816 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14818 MachineFunction *MF = MBB->getParent();
14819 MachineRegisterInfo &MRI = MF->getRegInfo();
14821 const BasicBlock *BB = MBB->getBasicBlock();
14822 MachineFunction::iterator I = MBB;
14825 // Memory Reference
14826 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14827 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14830 unsigned MemOpndSlot = 0;
14832 unsigned CurOp = 0;
14834 DstReg = MI->getOperand(CurOp++).getReg();
14835 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14836 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14837 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14838 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14840 MemOpndSlot = CurOp;
14842 MVT PVT = getPointerTy();
14843 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14844 "Invalid Pointer Size!");
14846 // For v = setjmp(buf), we generate
14849 // buf[LabelOffset] = restoreMBB
14850 // SjLjSetup restoreMBB
14856 // v = phi(main, restore)
14861 MachineBasicBlock *thisMBB = MBB;
14862 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14863 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14864 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14865 MF->insert(I, mainMBB);
14866 MF->insert(I, sinkMBB);
14867 MF->push_back(restoreMBB);
14869 MachineInstrBuilder MIB;
14871 // Transfer the remainder of BB and its successor edges to sinkMBB.
14872 sinkMBB->splice(sinkMBB->begin(), MBB,
14873 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14874 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14877 unsigned PtrStoreOpc = 0;
14878 unsigned LabelReg = 0;
14879 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14880 Reloc::Model RM = getTargetMachine().getRelocationModel();
14881 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14882 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14884 // Prepare IP either in reg or imm.
14885 if (!UseImmLabel) {
14886 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14887 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14888 LabelReg = MRI.createVirtualRegister(PtrRC);
14889 if (Subtarget->is64Bit()) {
14890 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14894 .addMBB(restoreMBB)
14897 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14898 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14899 .addReg(XII->getGlobalBaseReg(MF))
14902 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14906 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14908 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14909 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14910 if (i == X86::AddrDisp)
14911 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14913 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14916 MIB.addReg(LabelReg);
14918 MIB.addMBB(restoreMBB);
14919 MIB.setMemRefs(MMOBegin, MMOEnd);
14921 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14922 .addMBB(restoreMBB);
14924 const X86RegisterInfo *RegInfo =
14925 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14926 MIB.addRegMask(RegInfo->getNoPreservedMask());
14927 thisMBB->addSuccessor(mainMBB);
14928 thisMBB->addSuccessor(restoreMBB);
14932 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14933 mainMBB->addSuccessor(sinkMBB);
14936 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14937 TII->get(X86::PHI), DstReg)
14938 .addReg(mainDstReg).addMBB(mainMBB)
14939 .addReg(restoreDstReg).addMBB(restoreMBB);
14942 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14943 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14944 restoreMBB->addSuccessor(sinkMBB);
14946 MI->eraseFromParent();
14950 MachineBasicBlock *
14951 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14952 MachineBasicBlock *MBB) const {
14953 DebugLoc DL = MI->getDebugLoc();
14954 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14956 MachineFunction *MF = MBB->getParent();
14957 MachineRegisterInfo &MRI = MF->getRegInfo();
14959 // Memory Reference
14960 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14961 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14963 MVT PVT = getPointerTy();
14964 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14965 "Invalid Pointer Size!");
14967 const TargetRegisterClass *RC =
14968 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14969 unsigned Tmp = MRI.createVirtualRegister(RC);
14970 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14971 const X86RegisterInfo *RegInfo =
14972 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14973 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14974 unsigned SP = RegInfo->getStackRegister();
14976 MachineInstrBuilder MIB;
14978 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14979 const int64_t SPOffset = 2 * PVT.getStoreSize();
14981 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14982 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14985 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14986 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14987 MIB.addOperand(MI->getOperand(i));
14988 MIB.setMemRefs(MMOBegin, MMOEnd);
14990 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14991 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14992 if (i == X86::AddrDisp)
14993 MIB.addDisp(MI->getOperand(i), LabelOffset);
14995 MIB.addOperand(MI->getOperand(i));
14997 MIB.setMemRefs(MMOBegin, MMOEnd);
14999 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15000 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15001 if (i == X86::AddrDisp)
15002 MIB.addDisp(MI->getOperand(i), SPOffset);
15004 MIB.addOperand(MI->getOperand(i));
15006 MIB.setMemRefs(MMOBegin, MMOEnd);
15008 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15010 MI->eraseFromParent();
15014 MachineBasicBlock *
15015 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15016 MachineBasicBlock *BB) const {
15017 switch (MI->getOpcode()) {
15018 default: llvm_unreachable("Unexpected instr type to insert");
15019 case X86::TAILJMPd64:
15020 case X86::TAILJMPr64:
15021 case X86::TAILJMPm64:
15022 llvm_unreachable("TAILJMP64 would not be touched here.");
15023 case X86::TCRETURNdi64:
15024 case X86::TCRETURNri64:
15025 case X86::TCRETURNmi64:
15027 case X86::WIN_ALLOCA:
15028 return EmitLoweredWinAlloca(MI, BB);
15029 case X86::SEG_ALLOCA_32:
15030 return EmitLoweredSegAlloca(MI, BB, false);
15031 case X86::SEG_ALLOCA_64:
15032 return EmitLoweredSegAlloca(MI, BB, true);
15033 case X86::TLSCall_32:
15034 case X86::TLSCall_64:
15035 return EmitLoweredTLSCall(MI, BB);
15036 case X86::CMOV_GR8:
15037 case X86::CMOV_FR32:
15038 case X86::CMOV_FR64:
15039 case X86::CMOV_V4F32:
15040 case X86::CMOV_V2F64:
15041 case X86::CMOV_V2I64:
15042 case X86::CMOV_V8F32:
15043 case X86::CMOV_V4F64:
15044 case X86::CMOV_V4I64:
15045 case X86::CMOV_GR16:
15046 case X86::CMOV_GR32:
15047 case X86::CMOV_RFP32:
15048 case X86::CMOV_RFP64:
15049 case X86::CMOV_RFP80:
15050 return EmitLoweredSelect(MI, BB);
15052 case X86::FP32_TO_INT16_IN_MEM:
15053 case X86::FP32_TO_INT32_IN_MEM:
15054 case X86::FP32_TO_INT64_IN_MEM:
15055 case X86::FP64_TO_INT16_IN_MEM:
15056 case X86::FP64_TO_INT32_IN_MEM:
15057 case X86::FP64_TO_INT64_IN_MEM:
15058 case X86::FP80_TO_INT16_IN_MEM:
15059 case X86::FP80_TO_INT32_IN_MEM:
15060 case X86::FP80_TO_INT64_IN_MEM: {
15061 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15062 DebugLoc DL = MI->getDebugLoc();
15064 // Change the floating point control register to use "round towards zero"
15065 // mode when truncating to an integer value.
15066 MachineFunction *F = BB->getParent();
15067 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15068 addFrameReference(BuildMI(*BB, MI, DL,
15069 TII->get(X86::FNSTCW16m)), CWFrameIdx);
15071 // Load the old value of the high byte of the control word...
15073 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15074 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15077 // Set the high part to be round to zero...
15078 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15081 // Reload the modified control word now...
15082 addFrameReference(BuildMI(*BB, MI, DL,
15083 TII->get(X86::FLDCW16m)), CWFrameIdx);
15085 // Restore the memory image of control word to original value
15086 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15089 // Get the X86 opcode to use.
15091 switch (MI->getOpcode()) {
15092 default: llvm_unreachable("illegal opcode!");
15093 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15094 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15095 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15096 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15097 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15098 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15099 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15100 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15101 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15105 MachineOperand &Op = MI->getOperand(0);
15107 AM.BaseType = X86AddressMode::RegBase;
15108 AM.Base.Reg = Op.getReg();
15110 AM.BaseType = X86AddressMode::FrameIndexBase;
15111 AM.Base.FrameIndex = Op.getIndex();
15113 Op = MI->getOperand(1);
15115 AM.Scale = Op.getImm();
15116 Op = MI->getOperand(2);
15118 AM.IndexReg = Op.getImm();
15119 Op = MI->getOperand(3);
15120 if (Op.isGlobal()) {
15121 AM.GV = Op.getGlobal();
15123 AM.Disp = Op.getImm();
15125 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15126 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15128 // Reload the original control word now.
15129 addFrameReference(BuildMI(*BB, MI, DL,
15130 TII->get(X86::FLDCW16m)), CWFrameIdx);
15132 MI->eraseFromParent(); // The pseudo instruction is gone now.
15135 // String/text processing lowering.
15136 case X86::PCMPISTRM128REG:
15137 case X86::VPCMPISTRM128REG:
15138 case X86::PCMPISTRM128MEM:
15139 case X86::VPCMPISTRM128MEM:
15140 case X86::PCMPESTRM128REG:
15141 case X86::VPCMPESTRM128REG:
15142 case X86::PCMPESTRM128MEM:
15143 case X86::VPCMPESTRM128MEM:
15144 assert(Subtarget->hasSSE42() &&
15145 "Target must have SSE4.2 or AVX features enabled");
15146 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15148 // String/text processing lowering.
15149 case X86::PCMPISTRIREG:
15150 case X86::VPCMPISTRIREG:
15151 case X86::PCMPISTRIMEM:
15152 case X86::VPCMPISTRIMEM:
15153 case X86::PCMPESTRIREG:
15154 case X86::VPCMPESTRIREG:
15155 case X86::PCMPESTRIMEM:
15156 case X86::VPCMPESTRIMEM:
15157 assert(Subtarget->hasSSE42() &&
15158 "Target must have SSE4.2 or AVX features enabled");
15159 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15161 // Thread synchronization.
15163 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15167 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15169 // Atomic Lowering.
15170 case X86::ATOMAND8:
15171 case X86::ATOMAND16:
15172 case X86::ATOMAND32:
15173 case X86::ATOMAND64:
15176 case X86::ATOMOR16:
15177 case X86::ATOMOR32:
15178 case X86::ATOMOR64:
15180 case X86::ATOMXOR16:
15181 case X86::ATOMXOR8:
15182 case X86::ATOMXOR32:
15183 case X86::ATOMXOR64:
15185 case X86::ATOMNAND8:
15186 case X86::ATOMNAND16:
15187 case X86::ATOMNAND32:
15188 case X86::ATOMNAND64:
15190 case X86::ATOMMAX8:
15191 case X86::ATOMMAX16:
15192 case X86::ATOMMAX32:
15193 case X86::ATOMMAX64:
15195 case X86::ATOMMIN8:
15196 case X86::ATOMMIN16:
15197 case X86::ATOMMIN32:
15198 case X86::ATOMMIN64:
15200 case X86::ATOMUMAX8:
15201 case X86::ATOMUMAX16:
15202 case X86::ATOMUMAX32:
15203 case X86::ATOMUMAX64:
15205 case X86::ATOMUMIN8:
15206 case X86::ATOMUMIN16:
15207 case X86::ATOMUMIN32:
15208 case X86::ATOMUMIN64:
15209 return EmitAtomicLoadArith(MI, BB);
15211 // This group does 64-bit operations on a 32-bit host.
15212 case X86::ATOMAND6432:
15213 case X86::ATOMOR6432:
15214 case X86::ATOMXOR6432:
15215 case X86::ATOMNAND6432:
15216 case X86::ATOMADD6432:
15217 case X86::ATOMSUB6432:
15218 case X86::ATOMMAX6432:
15219 case X86::ATOMMIN6432:
15220 case X86::ATOMUMAX6432:
15221 case X86::ATOMUMIN6432:
15222 case X86::ATOMSWAP6432:
15223 return EmitAtomicLoadArith6432(MI, BB);
15225 case X86::VASTART_SAVE_XMM_REGS:
15226 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15228 case X86::VAARG_64:
15229 return EmitVAARG64WithCustomInserter(MI, BB);
15231 case X86::EH_SjLj_SetJmp32:
15232 case X86::EH_SjLj_SetJmp64:
15233 return emitEHSjLjSetJmp(MI, BB);
15235 case X86::EH_SjLj_LongJmp32:
15236 case X86::EH_SjLj_LongJmp64:
15237 return emitEHSjLjLongJmp(MI, BB);
15241 //===----------------------------------------------------------------------===//
15242 // X86 Optimization Hooks
15243 //===----------------------------------------------------------------------===//
15245 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15248 const SelectionDAG &DAG,
15249 unsigned Depth) const {
15250 unsigned BitWidth = KnownZero.getBitWidth();
15251 unsigned Opc = Op.getOpcode();
15252 assert((Opc >= ISD::BUILTIN_OP_END ||
15253 Opc == ISD::INTRINSIC_WO_CHAIN ||
15254 Opc == ISD::INTRINSIC_W_CHAIN ||
15255 Opc == ISD::INTRINSIC_VOID) &&
15256 "Should use MaskedValueIsZero if you don't know whether Op"
15257 " is a target node!");
15259 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
15273 // These nodes' second result is a boolean.
15274 if (Op.getResNo() == 0)
15277 case X86ISD::SETCC:
15278 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15280 case ISD::INTRINSIC_WO_CHAIN: {
15281 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15282 unsigned NumLoBits = 0;
15285 case Intrinsic::x86_sse_movmsk_ps:
15286 case Intrinsic::x86_avx_movmsk_ps_256:
15287 case Intrinsic::x86_sse2_movmsk_pd:
15288 case Intrinsic::x86_avx_movmsk_pd_256:
15289 case Intrinsic::x86_mmx_pmovmskb:
15290 case Intrinsic::x86_sse2_pmovmskb_128:
15291 case Intrinsic::x86_avx2_pmovmskb: {
15292 // High bits of movmskp{s|d}, pmovmskb are known zero.
15294 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15295 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
15296 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
15297 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
15298 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
15299 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
15300 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
15301 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
15303 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15312 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15313 unsigned Depth) const {
15314 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15315 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15316 return Op.getValueType().getScalarType().getSizeInBits();
15322 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15323 /// node is a GlobalAddress + offset.
15324 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15325 const GlobalValue* &GA,
15326 int64_t &Offset) const {
15327 if (N->getOpcode() == X86ISD::Wrapper) {
15328 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15329 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15330 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15334 return TargetLowering::isGAPlusOffset(N, GA, Offset);
15337 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15338 /// same as extracting the high 128-bit part of 256-bit vector and then
15339 /// inserting the result into the low part of a new 256-bit vector
15340 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15341 EVT VT = SVOp->getValueType(0);
15342 unsigned NumElems = VT.getVectorNumElements();
15344 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15345 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15346 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15347 SVOp->getMaskElt(j) >= 0)
15353 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15354 /// same as extracting the low 128-bit part of 256-bit vector and then
15355 /// inserting the result into the high part of a new 256-bit vector
15356 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15357 EVT VT = SVOp->getValueType(0);
15358 unsigned NumElems = VT.getVectorNumElements();
15360 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15361 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15362 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15363 SVOp->getMaskElt(j) >= 0)
15369 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15370 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15371 TargetLowering::DAGCombinerInfo &DCI,
15372 const X86Subtarget* Subtarget) {
15374 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15375 SDValue V1 = SVOp->getOperand(0);
15376 SDValue V2 = SVOp->getOperand(1);
15377 EVT VT = SVOp->getValueType(0);
15378 unsigned NumElems = VT.getVectorNumElements();
15380 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15381 V2.getOpcode() == ISD::CONCAT_VECTORS) {
15385 // V UNDEF BUILD_VECTOR UNDEF
15387 // CONCAT_VECTOR CONCAT_VECTOR
15390 // RESULT: V + zero extended
15392 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15393 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15394 V1.getOperand(1).getOpcode() != ISD::UNDEF)
15397 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15400 // To match the shuffle mask, the first half of the mask should
15401 // be exactly the first vector, and all the rest a splat with the
15402 // first element of the second one.
15403 for (unsigned i = 0; i != NumElems/2; ++i)
15404 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15405 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15408 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15409 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15410 if (Ld->hasNUsesOfValue(1, 0)) {
15411 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15412 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15414 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15415 array_lengthof(Ops),
15417 Ld->getPointerInfo(),
15418 Ld->getAlignment(),
15419 false/*isVolatile*/, true/*ReadMem*/,
15420 false/*WriteMem*/);
15422 // Make sure the newly-created LOAD is in the same position as Ld in
15423 // terms of dependency. We create a TokenFactor for Ld and ResNode,
15424 // and update uses of Ld's output chain to use the TokenFactor.
15425 if (Ld->hasAnyUseOfValue(1)) {
15426 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15427 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15428 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15429 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15430 SDValue(ResNode.getNode(), 1));
15433 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15437 // Emit a zeroed vector and insert the desired subvector on its
15439 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15440 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15441 return DCI.CombineTo(N, InsV);
15444 //===--------------------------------------------------------------------===//
15445 // Combine some shuffles into subvector extracts and inserts:
15448 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15449 if (isShuffleHigh128VectorInsertLow(SVOp)) {
15450 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15451 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15452 return DCI.CombineTo(N, InsV);
15455 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15456 if (isShuffleLow128VectorInsertHigh(SVOp)) {
15457 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15458 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15459 return DCI.CombineTo(N, InsV);
15465 /// PerformShuffleCombine - Performs several different shuffle combines.
15466 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15467 TargetLowering::DAGCombinerInfo &DCI,
15468 const X86Subtarget *Subtarget) {
15470 EVT VT = N->getValueType(0);
15472 // Don't create instructions with illegal types after legalize types has run.
15473 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15474 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15477 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15478 if (Subtarget->hasFp256() && VT.is256BitVector() &&
15479 N->getOpcode() == ISD::VECTOR_SHUFFLE)
15480 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15482 // Only handle 128 wide vector from here on.
15483 if (!VT.is128BitVector())
15486 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15487 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15488 // consecutive, non-overlapping, and in the right order.
15489 SmallVector<SDValue, 16> Elts;
15490 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15491 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15493 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15496 /// PerformTruncateCombine - Converts truncate operation to
15497 /// a sequence of vector shuffle operations.
15498 /// It is possible when we truncate 256-bit vector to 128-bit vector
15499 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15500 TargetLowering::DAGCombinerInfo &DCI,
15501 const X86Subtarget *Subtarget) {
15505 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15506 /// specific shuffle of a load can be folded into a single element load.
15507 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15508 /// shuffles have been customed lowered so we need to handle those here.
15509 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15510 TargetLowering::DAGCombinerInfo &DCI) {
15511 if (DCI.isBeforeLegalizeOps())
15514 SDValue InVec = N->getOperand(0);
15515 SDValue EltNo = N->getOperand(1);
15517 if (!isa<ConstantSDNode>(EltNo))
15520 EVT VT = InVec.getValueType();
15522 bool HasShuffleIntoBitcast = false;
15523 if (InVec.getOpcode() == ISD::BITCAST) {
15524 // Don't duplicate a load with other uses.
15525 if (!InVec.hasOneUse())
15527 EVT BCVT = InVec.getOperand(0).getValueType();
15528 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15530 InVec = InVec.getOperand(0);
15531 HasShuffleIntoBitcast = true;
15534 if (!isTargetShuffle(InVec.getOpcode()))
15537 // Don't duplicate a load with other uses.
15538 if (!InVec.hasOneUse())
15541 SmallVector<int, 16> ShuffleMask;
15543 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15547 // Select the input vector, guarding against out of range extract vector.
15548 unsigned NumElems = VT.getVectorNumElements();
15549 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15550 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15551 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15552 : InVec.getOperand(1);
15554 // If inputs to shuffle are the same for both ops, then allow 2 uses
15555 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15557 if (LdNode.getOpcode() == ISD::BITCAST) {
15558 // Don't duplicate a load with other uses.
15559 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15562 AllowedUses = 1; // only allow 1 load use if we have a bitcast
15563 LdNode = LdNode.getOperand(0);
15566 if (!ISD::isNormalLoad(LdNode.getNode()))
15569 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15571 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15574 if (HasShuffleIntoBitcast) {
15575 // If there's a bitcast before the shuffle, check if the load type and
15576 // alignment is valid.
15577 unsigned Align = LN0->getAlignment();
15578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15579 unsigned NewAlign = TLI.getDataLayout()->
15580 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15582 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15586 // All checks match so transform back to vector_shuffle so that DAG combiner
15587 // can finish the job
15590 // Create shuffle node taking into account the case that its a unary shuffle
15591 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15592 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15593 InVec.getOperand(0), Shuffle,
15595 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15596 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15600 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15601 /// generation and convert it from being a bunch of shuffles and extracts
15602 /// to a simple store and scalar loads to extract the elements.
15603 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15604 TargetLowering::DAGCombinerInfo &DCI) {
15605 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15606 if (NewOp.getNode())
15609 SDValue InputVector = N->getOperand(0);
15610 // Detect whether we are trying to convert from mmx to i32 and the bitcast
15611 // from mmx to v2i32 has a single usage.
15612 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15613 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15614 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15615 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15616 N->getValueType(0),
15617 InputVector.getNode()->getOperand(0));
15619 // Only operate on vectors of 4 elements, where the alternative shuffling
15620 // gets to be more expensive.
15621 if (InputVector.getValueType() != MVT::v4i32)
15624 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15625 // single use which is a sign-extend or zero-extend, and all elements are
15627 SmallVector<SDNode *, 4> Uses;
15628 unsigned ExtractedElements = 0;
15629 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15630 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15631 if (UI.getUse().getResNo() != InputVector.getResNo())
15634 SDNode *Extract = *UI;
15635 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15638 if (Extract->getValueType(0) != MVT::i32)
15640 if (!Extract->hasOneUse())
15642 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15643 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15645 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15648 // Record which element was extracted.
15649 ExtractedElements |=
15650 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15652 Uses.push_back(Extract);
15655 // If not all the elements were used, this may not be worthwhile.
15656 if (ExtractedElements != 15)
15659 // Ok, we've now decided to do the transformation.
15660 SDLoc dl(InputVector);
15662 // Store the value to a temporary stack slot.
15663 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15664 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15665 MachinePointerInfo(), false, false, 0);
15667 // Replace each use (extract) with a load of the appropriate element.
15668 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15669 UE = Uses.end(); UI != UE; ++UI) {
15670 SDNode *Extract = *UI;
15672 // cOMpute the element's address.
15673 SDValue Idx = Extract->getOperand(1);
15675 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15676 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15677 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15678 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15680 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15681 StackPtr, OffsetVal);
15683 // Load the scalar.
15684 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15685 ScalarAddr, MachinePointerInfo(),
15686 false, false, false, 0);
15688 // Replace the exact with the load.
15689 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15692 // The replacement was made in place; don't return anything.
15696 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15697 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15698 SDValue RHS, SelectionDAG &DAG,
15699 const X86Subtarget *Subtarget) {
15700 if (!VT.isVector())
15703 switch (VT.getSimpleVT().SimpleTy) {
15708 if (!Subtarget->hasAVX2())
15713 if (!Subtarget->hasSSE2())
15717 // SSE2 has only a small subset of the operations.
15718 bool hasUnsigned = Subtarget->hasSSE41() ||
15719 (Subtarget->hasSSE2() && VT == MVT::v16i8);
15720 bool hasSigned = Subtarget->hasSSE41() ||
15721 (Subtarget->hasSSE2() && VT == MVT::v8i16);
15723 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15725 // Check for x CC y ? x : y.
15726 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15727 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15732 return hasUnsigned ? X86ISD::UMIN : 0;
15735 return hasUnsigned ? X86ISD::UMAX : 0;
15738 return hasSigned ? X86ISD::SMIN : 0;
15741 return hasSigned ? X86ISD::SMAX : 0;
15743 // Check for x CC y ? y : x -- a min/max with reversed arms.
15744 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15745 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15750 return hasUnsigned ? X86ISD::UMAX : 0;
15753 return hasUnsigned ? X86ISD::UMIN : 0;
15756 return hasSigned ? X86ISD::SMAX : 0;
15759 return hasSigned ? X86ISD::SMIN : 0;
15766 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15768 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15769 TargetLowering::DAGCombinerInfo &DCI,
15770 const X86Subtarget *Subtarget) {
15772 SDValue Cond = N->getOperand(0);
15773 // Get the LHS/RHS of the select.
15774 SDValue LHS = N->getOperand(1);
15775 SDValue RHS = N->getOperand(2);
15776 EVT VT = LHS.getValueType();
15778 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15779 // instructions match the semantics of the common C idiom x<y?x:y but not
15780 // x<=y?x:y, because of how they handle negative zero (which can be
15781 // ignored in unsafe-math mode).
15782 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15783 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15784 (Subtarget->hasSSE2() ||
15785 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15786 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15788 unsigned Opcode = 0;
15789 // Check for x CC y ? x : y.
15790 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15791 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15795 // Converting this to a min would handle NaNs incorrectly, and swapping
15796 // the operands would cause it to handle comparisons between positive
15797 // and negative zero incorrectly.
15798 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15799 if (!DAG.getTarget().Options.UnsafeFPMath &&
15800 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15802 std::swap(LHS, RHS);
15804 Opcode = X86ISD::FMIN;
15807 // Converting this to a min would handle comparisons between positive
15808 // and negative zero incorrectly.
15809 if (!DAG.getTarget().Options.UnsafeFPMath &&
15810 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15812 Opcode = X86ISD::FMIN;
15815 // Converting this to a min would handle both negative zeros and NaNs
15816 // incorrectly, but we can swap the operands to fix both.
15817 std::swap(LHS, RHS);
15821 Opcode = X86ISD::FMIN;
15825 // Converting this to a max would handle comparisons between positive
15826 // and negative zero incorrectly.
15827 if (!DAG.getTarget().Options.UnsafeFPMath &&
15828 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15830 Opcode = X86ISD::FMAX;
15833 // Converting this to a max would handle NaNs incorrectly, and swapping
15834 // the operands would cause it to handle comparisons between positive
15835 // and negative zero incorrectly.
15836 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15837 if (!DAG.getTarget().Options.UnsafeFPMath &&
15838 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15840 std::swap(LHS, RHS);
15842 Opcode = X86ISD::FMAX;
15845 // Converting this to a max would handle both negative zeros and NaNs
15846 // incorrectly, but we can swap the operands to fix both.
15847 std::swap(LHS, RHS);
15851 Opcode = X86ISD::FMAX;
15854 // Check for x CC y ? y : x -- a min/max with reversed arms.
15855 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15856 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15860 // Converting this to a min would handle comparisons between positive
15861 // and negative zero incorrectly, and swapping the operands would
15862 // cause it to handle NaNs incorrectly.
15863 if (!DAG.getTarget().Options.UnsafeFPMath &&
15864 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15865 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15867 std::swap(LHS, RHS);
15869 Opcode = X86ISD::FMIN;
15872 // Converting this to a min would handle NaNs incorrectly.
15873 if (!DAG.getTarget().Options.UnsafeFPMath &&
15874 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15876 Opcode = X86ISD::FMIN;
15879 // Converting this to a min would handle both negative zeros and NaNs
15880 // incorrectly, but we can swap the operands to fix both.
15881 std::swap(LHS, RHS);
15885 Opcode = X86ISD::FMIN;
15889 // Converting this to a max would handle NaNs incorrectly.
15890 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15892 Opcode = X86ISD::FMAX;
15895 // Converting this to a max would handle comparisons between positive
15896 // and negative zero incorrectly, and swapping the operands would
15897 // cause it to handle NaNs incorrectly.
15898 if (!DAG.getTarget().Options.UnsafeFPMath &&
15899 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15900 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15902 std::swap(LHS, RHS);
15904 Opcode = X86ISD::FMAX;
15907 // Converting this to a max would handle both negative zeros and NaNs
15908 // incorrectly, but we can swap the operands to fix both.
15909 std::swap(LHS, RHS);
15913 Opcode = X86ISD::FMAX;
15919 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15922 // If this is a select between two integer constants, try to do some
15924 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15925 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15926 // Don't do this for crazy integer types.
15927 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15928 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15929 // so that TrueC (the true value) is larger than FalseC.
15930 bool NeedsCondInvert = false;
15932 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15933 // Efficiently invertible.
15934 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15935 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15936 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15937 NeedsCondInvert = true;
15938 std::swap(TrueC, FalseC);
15941 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15942 if (FalseC->getAPIntValue() == 0 &&
15943 TrueC->getAPIntValue().isPowerOf2()) {
15944 if (NeedsCondInvert) // Invert the condition if needed.
15945 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15946 DAG.getConstant(1, Cond.getValueType()));
15948 // Zero extend the condition if needed.
15949 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15951 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15952 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15953 DAG.getConstant(ShAmt, MVT::i8));
15956 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15957 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15958 if (NeedsCondInvert) // Invert the condition if needed.
15959 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15960 DAG.getConstant(1, Cond.getValueType()));
15962 // Zero extend the condition if needed.
15963 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15964 FalseC->getValueType(0), Cond);
15965 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15966 SDValue(FalseC, 0));
15969 // Optimize cases that will turn into an LEA instruction. This requires
15970 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15971 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15972 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15973 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15975 bool isFastMultiplier = false;
15977 switch ((unsigned char)Diff) {
15979 case 1: // result = add base, cond
15980 case 2: // result = lea base( , cond*2)
15981 case 3: // result = lea base(cond, cond*2)
15982 case 4: // result = lea base( , cond*4)
15983 case 5: // result = lea base(cond, cond*4)
15984 case 8: // result = lea base( , cond*8)
15985 case 9: // result = lea base(cond, cond*8)
15986 isFastMultiplier = true;
15991 if (isFastMultiplier) {
15992 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15993 if (NeedsCondInvert) // Invert the condition if needed.
15994 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15995 DAG.getConstant(1, Cond.getValueType()));
15997 // Zero extend the condition if needed.
15998 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16000 // Scale the condition by the difference.
16002 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16003 DAG.getConstant(Diff, Cond.getValueType()));
16005 // Add the base if non-zero.
16006 if (FalseC->getAPIntValue() != 0)
16007 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16008 SDValue(FalseC, 0));
16015 // Canonicalize max and min:
16016 // (x > y) ? x : y -> (x >= y) ? x : y
16017 // (x < y) ? x : y -> (x <= y) ? x : y
16018 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16019 // the need for an extra compare
16020 // against zero. e.g.
16021 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16023 // testl %edi, %edi
16025 // cmovgl %edi, %eax
16029 // cmovsl %eax, %edi
16030 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16031 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16032 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16033 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16038 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16039 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16040 Cond.getOperand(0), Cond.getOperand(1), NewCC);
16041 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16046 // Match VSELECTs into subs with unsigned saturation.
16047 if (!DCI.isBeforeLegalize() &&
16048 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16049 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16050 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16051 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16052 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16054 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16055 // left side invert the predicate to simplify logic below.
16057 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16059 CC = ISD::getSetCCInverse(CC, true);
16060 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16064 if (Other.getNode() && Other->getNumOperands() == 2 &&
16065 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16066 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16067 SDValue CondRHS = Cond->getOperand(1);
16069 // Look for a general sub with unsigned saturation first.
16070 // x >= y ? x-y : 0 --> subus x, y
16071 // x > y ? x-y : 0 --> subus x, y
16072 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16073 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16074 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16076 // If the RHS is a constant we have to reverse the const canonicalization.
16077 // x > C-1 ? x+-C : 0 --> subus x, C
16078 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16079 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16080 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16081 if (CondRHS.getConstantOperandVal(0) == -A-1)
16082 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16083 DAG.getConstant(-A, VT));
16086 // Another special case: If C was a sign bit, the sub has been
16087 // canonicalized into a xor.
16088 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16089 // it's safe to decanonicalize the xor?
16090 // x s< 0 ? x^C : 0 --> subus x, C
16091 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16092 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16093 isSplatVector(OpRHS.getNode())) {
16094 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16096 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16101 // Try to match a min/max vector operation.
16102 if (!DCI.isBeforeLegalize() &&
16103 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16104 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16105 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16107 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16108 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16109 Cond.getOpcode() == ISD::SETCC) {
16111 assert(Cond.getValueType().isVector() &&
16112 "vector select expects a vector selector!");
16114 EVT IntVT = Cond.getValueType();
16115 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16116 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16118 if (!TValIsAllOnes && !FValIsAllZeros) {
16119 // Try invert the condition if true value is not all 1s and false value
16121 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16122 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16124 if (TValIsAllZeros || FValIsAllOnes) {
16125 SDValue CC = Cond.getOperand(2);
16126 ISD::CondCode NewCC =
16127 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16128 Cond.getOperand(0).getValueType().isInteger());
16129 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16130 std::swap(LHS, RHS);
16131 TValIsAllOnes = FValIsAllOnes;
16132 FValIsAllZeros = TValIsAllZeros;
16136 if (TValIsAllOnes || FValIsAllZeros) {
16139 if (TValIsAllOnes && FValIsAllZeros)
16141 else if (TValIsAllOnes)
16142 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16143 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16144 else if (FValIsAllZeros)
16145 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16146 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16148 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16152 // If we know that this node is legal then we know that it is going to be
16153 // matched by one of the SSE/AVX BLEND instructions. These instructions only
16154 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16155 // to simplify previous instructions.
16156 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16157 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16158 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16159 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16161 // Don't optimize vector selects that map to mask-registers.
16165 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16166 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16168 APInt KnownZero, KnownOne;
16169 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16170 DCI.isBeforeLegalizeOps());
16171 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16172 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16173 DCI.CommitTargetLoweringOpt(TLO);
16179 // Check whether a boolean test is testing a boolean value generated by
16180 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16183 // Simplify the following patterns:
16184 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16185 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16186 // to (Op EFLAGS Cond)
16188 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16189 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16190 // to (Op EFLAGS !Cond)
16192 // where Op could be BRCOND or CMOV.
16194 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16195 // Quit if not CMP and SUB with its value result used.
16196 if (Cmp.getOpcode() != X86ISD::CMP &&
16197 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16200 // Quit if not used as a boolean value.
16201 if (CC != X86::COND_E && CC != X86::COND_NE)
16204 // Check CMP operands. One of them should be 0 or 1 and the other should be
16205 // an SetCC or extended from it.
16206 SDValue Op1 = Cmp.getOperand(0);
16207 SDValue Op2 = Cmp.getOperand(1);
16210 const ConstantSDNode* C = 0;
16211 bool needOppositeCond = (CC == X86::COND_E);
16212 bool checkAgainstTrue = false; // Is it a comparison against 1?
16214 if ((C = dyn_cast<ConstantSDNode>(Op1)))
16216 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16218 else // Quit if all operands are not constants.
16221 if (C->getZExtValue() == 1) {
16222 needOppositeCond = !needOppositeCond;
16223 checkAgainstTrue = true;
16224 } else if (C->getZExtValue() != 0)
16225 // Quit if the constant is neither 0 or 1.
16228 bool truncatedToBoolWithAnd = false;
16229 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16230 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16231 SetCC.getOpcode() == ISD::TRUNCATE ||
16232 SetCC.getOpcode() == ISD::AND) {
16233 if (SetCC.getOpcode() == ISD::AND) {
16235 ConstantSDNode *CS;
16236 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16237 CS->getZExtValue() == 1)
16239 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16240 CS->getZExtValue() == 1)
16244 SetCC = SetCC.getOperand(OpIdx);
16245 truncatedToBoolWithAnd = true;
16247 SetCC = SetCC.getOperand(0);
16250 switch (SetCC.getOpcode()) {
16251 case X86ISD::SETCC_CARRY:
16252 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16253 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16254 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16255 // truncated to i1 using 'and'.
16256 if (checkAgainstTrue && !truncatedToBoolWithAnd)
16258 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16259 "Invalid use of SETCC_CARRY!");
16261 case X86ISD::SETCC:
16262 // Set the condition code or opposite one if necessary.
16263 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16264 if (needOppositeCond)
16265 CC = X86::GetOppositeBranchCondition(CC);
16266 return SetCC.getOperand(1);
16267 case X86ISD::CMOV: {
16268 // Check whether false/true value has canonical one, i.e. 0 or 1.
16269 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16270 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16271 // Quit if true value is not a constant.
16274 // Quit if false value is not a constant.
16276 SDValue Op = SetCC.getOperand(0);
16277 // Skip 'zext' or 'trunc' node.
16278 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16279 Op.getOpcode() == ISD::TRUNCATE)
16280 Op = Op.getOperand(0);
16281 // A special case for rdrand/rdseed, where 0 is set if false cond is
16283 if ((Op.getOpcode() != X86ISD::RDRAND &&
16284 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16287 // Quit if false value is not the constant 0 or 1.
16288 bool FValIsFalse = true;
16289 if (FVal && FVal->getZExtValue() != 0) {
16290 if (FVal->getZExtValue() != 1)
16292 // If FVal is 1, opposite cond is needed.
16293 needOppositeCond = !needOppositeCond;
16294 FValIsFalse = false;
16296 // Quit if TVal is not the constant opposite of FVal.
16297 if (FValIsFalse && TVal->getZExtValue() != 1)
16299 if (!FValIsFalse && TVal->getZExtValue() != 0)
16301 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16302 if (needOppositeCond)
16303 CC = X86::GetOppositeBranchCondition(CC);
16304 return SetCC.getOperand(3);
16311 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16312 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16313 TargetLowering::DAGCombinerInfo &DCI,
16314 const X86Subtarget *Subtarget) {
16317 // If the flag operand isn't dead, don't touch this CMOV.
16318 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16321 SDValue FalseOp = N->getOperand(0);
16322 SDValue TrueOp = N->getOperand(1);
16323 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16324 SDValue Cond = N->getOperand(3);
16326 if (CC == X86::COND_E || CC == X86::COND_NE) {
16327 switch (Cond.getOpcode()) {
16331 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16332 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16333 return (CC == X86::COND_E) ? FalseOp : TrueOp;
16339 Flags = checkBoolTestSetCCCombine(Cond, CC);
16340 if (Flags.getNode() &&
16341 // Extra check as FCMOV only supports a subset of X86 cond.
16342 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16343 SDValue Ops[] = { FalseOp, TrueOp,
16344 DAG.getConstant(CC, MVT::i8), Flags };
16345 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16346 Ops, array_lengthof(Ops));
16349 // If this is a select between two integer constants, try to do some
16350 // optimizations. Note that the operands are ordered the opposite of SELECT
16352 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16353 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16354 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16355 // larger than FalseC (the false value).
16356 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16357 CC = X86::GetOppositeBranchCondition(CC);
16358 std::swap(TrueC, FalseC);
16359 std::swap(TrueOp, FalseOp);
16362 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
16363 // This is efficient for any integer data type (including i8/i16) and
16365 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16366 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16367 DAG.getConstant(CC, MVT::i8), Cond);
16369 // Zero extend the condition if needed.
16370 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16372 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16373 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16374 DAG.getConstant(ShAmt, MVT::i8));
16375 if (N->getNumValues() == 2) // Dead flag value?
16376 return DCI.CombineTo(N, Cond, SDValue());
16380 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
16381 // for any integer data type, including i8/i16.
16382 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16383 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16384 DAG.getConstant(CC, MVT::i8), Cond);
16386 // Zero extend the condition if needed.
16387 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16388 FalseC->getValueType(0), Cond);
16389 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16390 SDValue(FalseC, 0));
16392 if (N->getNumValues() == 2) // Dead flag value?
16393 return DCI.CombineTo(N, Cond, SDValue());
16397 // Optimize cases that will turn into an LEA instruction. This requires
16398 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16399 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16400 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16401 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16403 bool isFastMultiplier = false;
16405 switch ((unsigned char)Diff) {
16407 case 1: // result = add base, cond
16408 case 2: // result = lea base( , cond*2)
16409 case 3: // result = lea base(cond, cond*2)
16410 case 4: // result = lea base( , cond*4)
16411 case 5: // result = lea base(cond, cond*4)
16412 case 8: // result = lea base( , cond*8)
16413 case 9: // result = lea base(cond, cond*8)
16414 isFastMultiplier = true;
16419 if (isFastMultiplier) {
16420 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16421 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16422 DAG.getConstant(CC, MVT::i8), Cond);
16423 // Zero extend the condition if needed.
16424 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16426 // Scale the condition by the difference.
16428 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16429 DAG.getConstant(Diff, Cond.getValueType()));
16431 // Add the base if non-zero.
16432 if (FalseC->getAPIntValue() != 0)
16433 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16434 SDValue(FalseC, 0));
16435 if (N->getNumValues() == 2) // Dead flag value?
16436 return DCI.CombineTo(N, Cond, SDValue());
16443 // Handle these cases:
16444 // (select (x != c), e, c) -> select (x != c), e, x),
16445 // (select (x == c), c, e) -> select (x == c), x, e)
16446 // where the c is an integer constant, and the "select" is the combination
16447 // of CMOV and CMP.
16449 // The rationale for this change is that the conditional-move from a constant
16450 // needs two instructions, however, conditional-move from a register needs
16451 // only one instruction.
16453 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16454 // some instruction-combining opportunities. This opt needs to be
16455 // postponed as late as possible.
16457 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16458 // the DCI.xxxx conditions are provided to postpone the optimization as
16459 // late as possible.
16461 ConstantSDNode *CmpAgainst = 0;
16462 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16463 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16464 !isa<ConstantSDNode>(Cond.getOperand(0))) {
16466 if (CC == X86::COND_NE &&
16467 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16468 CC = X86::GetOppositeBranchCondition(CC);
16469 std::swap(TrueOp, FalseOp);
16472 if (CC == X86::COND_E &&
16473 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16474 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16475 DAG.getConstant(CC, MVT::i8), Cond };
16476 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16477 array_lengthof(Ops));
16485 /// PerformMulCombine - Optimize a single multiply with constant into two
16486 /// in order to implement it with two cheaper instructions, e.g.
16487 /// LEA + SHL, LEA + LEA.
16488 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16489 TargetLowering::DAGCombinerInfo &DCI) {
16490 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16493 EVT VT = N->getValueType(0);
16494 if (VT != MVT::i64)
16497 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16500 uint64_t MulAmt = C->getZExtValue();
16501 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16504 uint64_t MulAmt1 = 0;
16505 uint64_t MulAmt2 = 0;
16506 if ((MulAmt % 9) == 0) {
16508 MulAmt2 = MulAmt / 9;
16509 } else if ((MulAmt % 5) == 0) {
16511 MulAmt2 = MulAmt / 5;
16512 } else if ((MulAmt % 3) == 0) {
16514 MulAmt2 = MulAmt / 3;
16517 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16520 if (isPowerOf2_64(MulAmt2) &&
16521 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16522 // If second multiplifer is pow2, issue it first. We want the multiply by
16523 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16525 std::swap(MulAmt1, MulAmt2);
16528 if (isPowerOf2_64(MulAmt1))
16529 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16530 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16532 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16533 DAG.getConstant(MulAmt1, VT));
16535 if (isPowerOf2_64(MulAmt2))
16536 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16537 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16539 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16540 DAG.getConstant(MulAmt2, VT));
16542 // Do not add new nodes to DAG combiner worklist.
16543 DCI.CombineTo(N, NewMul, false);
16548 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16549 SDValue N0 = N->getOperand(0);
16550 SDValue N1 = N->getOperand(1);
16551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16552 EVT VT = N0.getValueType();
16554 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16555 // since the result of setcc_c is all zero's or all ones.
16556 if (VT.isInteger() && !VT.isVector() &&
16557 N1C && N0.getOpcode() == ISD::AND &&
16558 N0.getOperand(1).getOpcode() == ISD::Constant) {
16559 SDValue N00 = N0.getOperand(0);
16560 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16561 ((N00.getOpcode() == ISD::ANY_EXTEND ||
16562 N00.getOpcode() == ISD::ZERO_EXTEND) &&
16563 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16564 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16565 APInt ShAmt = N1C->getAPIntValue();
16566 Mask = Mask.shl(ShAmt);
16568 return DAG.getNode(ISD::AND, SDLoc(N), VT,
16569 N00, DAG.getConstant(Mask, VT));
16573 // Hardware support for vector shifts is sparse which makes us scalarize the
16574 // vector operations in many cases. Also, on sandybridge ADD is faster than
16576 // (shl V, 1) -> add V,V
16577 if (isSplatVector(N1.getNode())) {
16578 assert(N0.getValueType().isVector() && "Invalid vector shift type");
16579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16580 // We shift all of the values by one. In many cases we do not have
16581 // hardware support for this operation. This is better expressed as an ADD
16583 if (N1C && (1 == N1C->getZExtValue())) {
16584 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16591 /// \brief Returns a vector of 0s if the node in input is a vector logical
16592 /// shift by a constant amount which is known to be bigger than or equal
16593 /// to the vector element size in bits.
16594 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16595 const X86Subtarget *Subtarget) {
16596 EVT VT = N->getValueType(0);
16598 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16599 (!Subtarget->hasInt256() ||
16600 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16603 SDValue Amt = N->getOperand(1);
16605 if (isSplatVector(Amt.getNode())) {
16606 SDValue SclrAmt = Amt->getOperand(0);
16607 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16608 APInt ShiftAmt = C->getAPIntValue();
16609 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16611 // SSE2/AVX2 logical shifts always return a vector of 0s
16612 // if the shift amount is bigger than or equal to
16613 // the element size. The constant shift amount will be
16614 // encoded as a 8-bit immediate.
16615 if (ShiftAmt.trunc(8).uge(MaxAmount))
16616 return getZeroVector(VT, Subtarget, DAG, DL);
16623 /// PerformShiftCombine - Combine shifts.
16624 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16625 TargetLowering::DAGCombinerInfo &DCI,
16626 const X86Subtarget *Subtarget) {
16627 if (N->getOpcode() == ISD::SHL) {
16628 SDValue V = PerformSHLCombine(N, DAG);
16629 if (V.getNode()) return V;
16632 if (N->getOpcode() != ISD::SRA) {
16633 // Try to fold this logical shift into a zero vector.
16634 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16635 if (V.getNode()) return V;
16641 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
16642 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16643 // and friends. Likewise for OR -> CMPNEQSS.
16644 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16645 TargetLowering::DAGCombinerInfo &DCI,
16646 const X86Subtarget *Subtarget) {
16649 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16650 // we're requiring SSE2 for both.
16651 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16652 SDValue N0 = N->getOperand(0);
16653 SDValue N1 = N->getOperand(1);
16654 SDValue CMP0 = N0->getOperand(1);
16655 SDValue CMP1 = N1->getOperand(1);
16658 // The SETCCs should both refer to the same CMP.
16659 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16662 SDValue CMP00 = CMP0->getOperand(0);
16663 SDValue CMP01 = CMP0->getOperand(1);
16664 EVT VT = CMP00.getValueType();
16666 if (VT == MVT::f32 || VT == MVT::f64) {
16667 bool ExpectingFlags = false;
16668 // Check for any users that want flags:
16669 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16670 !ExpectingFlags && UI != UE; ++UI)
16671 switch (UI->getOpcode()) {
16676 ExpectingFlags = true;
16678 case ISD::CopyToReg:
16679 case ISD::SIGN_EXTEND:
16680 case ISD::ZERO_EXTEND:
16681 case ISD::ANY_EXTEND:
16685 if (!ExpectingFlags) {
16686 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16687 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16689 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16690 X86::CondCode tmp = cc0;
16695 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
16696 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16697 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16698 X86ISD::NodeType NTOperator = is64BitFP ?
16699 X86ISD::FSETCCsd : X86ISD::FSETCCss;
16700 // FIXME: need symbolic constants for these magic numbers.
16701 // See X86ATTInstPrinter.cpp:printSSECC().
16702 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16703 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16704 DAG.getConstant(x86cc, MVT::i8));
16705 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16707 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16708 DAG.getConstant(1, MVT::i32));
16709 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16710 return OneBitOfTruth;
16718 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16719 /// so it can be folded inside ANDNP.
16720 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16721 EVT VT = N->getValueType(0);
16723 // Match direct AllOnes for 128 and 256-bit vectors
16724 if (ISD::isBuildVectorAllOnes(N))
16727 // Look through a bit convert.
16728 if (N->getOpcode() == ISD::BITCAST)
16729 N = N->getOperand(0).getNode();
16731 // Sometimes the operand may come from a insert_subvector building a 256-bit
16733 if (VT.is256BitVector() &&
16734 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16735 SDValue V1 = N->getOperand(0);
16736 SDValue V2 = N->getOperand(1);
16738 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16739 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16740 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16741 ISD::isBuildVectorAllOnes(V2.getNode()))
16748 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16749 // register. In most cases we actually compare or select YMM-sized registers
16750 // and mixing the two types creates horrible code. This method optimizes
16751 // some of the transition sequences.
16752 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16753 TargetLowering::DAGCombinerInfo &DCI,
16754 const X86Subtarget *Subtarget) {
16755 EVT VT = N->getValueType(0);
16756 if (!VT.is256BitVector())
16759 assert((N->getOpcode() == ISD::ANY_EXTEND ||
16760 N->getOpcode() == ISD::ZERO_EXTEND ||
16761 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16763 SDValue Narrow = N->getOperand(0);
16764 EVT NarrowVT = Narrow->getValueType(0);
16765 if (!NarrowVT.is128BitVector())
16768 if (Narrow->getOpcode() != ISD::XOR &&
16769 Narrow->getOpcode() != ISD::AND &&
16770 Narrow->getOpcode() != ISD::OR)
16773 SDValue N0 = Narrow->getOperand(0);
16774 SDValue N1 = Narrow->getOperand(1);
16777 // The Left side has to be a trunc.
16778 if (N0.getOpcode() != ISD::TRUNCATE)
16781 // The type of the truncated inputs.
16782 EVT WideVT = N0->getOperand(0)->getValueType(0);
16786 // The right side has to be a 'trunc' or a constant vector.
16787 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16788 bool RHSConst = (isSplatVector(N1.getNode()) &&
16789 isa<ConstantSDNode>(N1->getOperand(0)));
16790 if (!RHSTrunc && !RHSConst)
16793 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16795 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16798 // Set N0 and N1 to hold the inputs to the new wide operation.
16799 N0 = N0->getOperand(0);
16801 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16802 N1->getOperand(0));
16803 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16804 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16805 } else if (RHSTrunc) {
16806 N1 = N1->getOperand(0);
16809 // Generate the wide operation.
16810 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16811 unsigned Opcode = N->getOpcode();
16813 case ISD::ANY_EXTEND:
16815 case ISD::ZERO_EXTEND: {
16816 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16817 APInt Mask = APInt::getAllOnesValue(InBits);
16818 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16819 return DAG.getNode(ISD::AND, DL, VT,
16820 Op, DAG.getConstant(Mask, VT));
16822 case ISD::SIGN_EXTEND:
16823 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16824 Op, DAG.getValueType(NarrowVT));
16826 llvm_unreachable("Unexpected opcode");
16830 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16831 TargetLowering::DAGCombinerInfo &DCI,
16832 const X86Subtarget *Subtarget) {
16833 EVT VT = N->getValueType(0);
16834 if (DCI.isBeforeLegalizeOps())
16837 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16841 // Create BLSI, and BLSR instructions
16842 // BLSI is X & (-X)
16843 // BLSR is X & (X-1)
16844 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16845 SDValue N0 = N->getOperand(0);
16846 SDValue N1 = N->getOperand(1);
16849 // Check LHS for neg
16850 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16851 isZero(N0.getOperand(0)))
16852 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16854 // Check RHS for neg
16855 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16856 isZero(N1.getOperand(0)))
16857 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16859 // Check LHS for X-1
16860 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16861 isAllOnes(N0.getOperand(1)))
16862 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16864 // Check RHS for X-1
16865 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16866 isAllOnes(N1.getOperand(1)))
16867 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16872 // Want to form ANDNP nodes:
16873 // 1) In the hopes of then easily combining them with OR and AND nodes
16874 // to form PBLEND/PSIGN.
16875 // 2) To match ANDN packed intrinsics
16876 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16879 SDValue N0 = N->getOperand(0);
16880 SDValue N1 = N->getOperand(1);
16883 // Check LHS for vnot
16884 if (N0.getOpcode() == ISD::XOR &&
16885 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16886 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16887 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16889 // Check RHS for vnot
16890 if (N1.getOpcode() == ISD::XOR &&
16891 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16892 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16893 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16898 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16899 TargetLowering::DAGCombinerInfo &DCI,
16900 const X86Subtarget *Subtarget) {
16901 EVT VT = N->getValueType(0);
16902 if (DCI.isBeforeLegalizeOps())
16905 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16909 SDValue N0 = N->getOperand(0);
16910 SDValue N1 = N->getOperand(1);
16912 // look for psign/blend
16913 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16914 if (!Subtarget->hasSSSE3() ||
16915 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16918 // Canonicalize pandn to RHS
16919 if (N0.getOpcode() == X86ISD::ANDNP)
16921 // or (and (m, y), (pandn m, x))
16922 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16923 SDValue Mask = N1.getOperand(0);
16924 SDValue X = N1.getOperand(1);
16926 if (N0.getOperand(0) == Mask)
16927 Y = N0.getOperand(1);
16928 if (N0.getOperand(1) == Mask)
16929 Y = N0.getOperand(0);
16931 // Check to see if the mask appeared in both the AND and ANDNP and
16935 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16936 // Look through mask bitcast.
16937 if (Mask.getOpcode() == ISD::BITCAST)
16938 Mask = Mask.getOperand(0);
16939 if (X.getOpcode() == ISD::BITCAST)
16940 X = X.getOperand(0);
16941 if (Y.getOpcode() == ISD::BITCAST)
16942 Y = Y.getOperand(0);
16944 EVT MaskVT = Mask.getValueType();
16946 // Validate that the Mask operand is a vector sra node.
16947 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16948 // there is no psrai.b
16949 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16950 unsigned SraAmt = ~0;
16951 if (Mask.getOpcode() == ISD::SRA) {
16952 SDValue Amt = Mask.getOperand(1);
16953 if (isSplatVector(Amt.getNode())) {
16954 SDValue SclrAmt = Amt->getOperand(0);
16955 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16956 SraAmt = C->getZExtValue();
16958 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16959 SDValue SraC = Mask.getOperand(1);
16960 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16962 if ((SraAmt + 1) != EltBits)
16967 // Now we know we at least have a plendvb with the mask val. See if
16968 // we can form a psignb/w/d.
16969 // psign = x.type == y.type == mask.type && y = sub(0, x);
16970 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16971 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16972 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16973 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16974 "Unsupported VT for PSIGN");
16975 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16976 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16978 // PBLENDVB only available on SSE 4.1
16979 if (!Subtarget->hasSSE41())
16982 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16984 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16985 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16986 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16987 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16988 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16992 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16995 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16996 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16998 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17000 if (!N0.hasOneUse() || !N1.hasOneUse())
17003 SDValue ShAmt0 = N0.getOperand(1);
17004 if (ShAmt0.getValueType() != MVT::i8)
17006 SDValue ShAmt1 = N1.getOperand(1);
17007 if (ShAmt1.getValueType() != MVT::i8)
17009 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17010 ShAmt0 = ShAmt0.getOperand(0);
17011 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17012 ShAmt1 = ShAmt1.getOperand(0);
17015 unsigned Opc = X86ISD::SHLD;
17016 SDValue Op0 = N0.getOperand(0);
17017 SDValue Op1 = N1.getOperand(0);
17018 if (ShAmt0.getOpcode() == ISD::SUB) {
17019 Opc = X86ISD::SHRD;
17020 std::swap(Op0, Op1);
17021 std::swap(ShAmt0, ShAmt1);
17024 unsigned Bits = VT.getSizeInBits();
17025 if (ShAmt1.getOpcode() == ISD::SUB) {
17026 SDValue Sum = ShAmt1.getOperand(0);
17027 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17028 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17029 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17030 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17031 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17032 return DAG.getNode(Opc, DL, VT,
17034 DAG.getNode(ISD::TRUNCATE, DL,
17037 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17038 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17040 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17041 return DAG.getNode(Opc, DL, VT,
17042 N0.getOperand(0), N1.getOperand(0),
17043 DAG.getNode(ISD::TRUNCATE, DL,
17050 // Generate NEG and CMOV for integer abs.
17051 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17052 EVT VT = N->getValueType(0);
17054 // Since X86 does not have CMOV for 8-bit integer, we don't convert
17055 // 8-bit integer abs to NEG and CMOV.
17056 if (VT.isInteger() && VT.getSizeInBits() == 8)
17059 SDValue N0 = N->getOperand(0);
17060 SDValue N1 = N->getOperand(1);
17063 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17064 // and change it to SUB and CMOV.
17065 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17066 N0.getOpcode() == ISD::ADD &&
17067 N0.getOperand(1) == N1 &&
17068 N1.getOpcode() == ISD::SRA &&
17069 N1.getOperand(0) == N0.getOperand(0))
17070 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17071 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17072 // Generate SUB & CMOV.
17073 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17074 DAG.getConstant(0, VT), N0.getOperand(0));
17076 SDValue Ops[] = { N0.getOperand(0), Neg,
17077 DAG.getConstant(X86::COND_GE, MVT::i8),
17078 SDValue(Neg.getNode(), 1) };
17079 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17080 Ops, array_lengthof(Ops));
17085 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17086 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17087 TargetLowering::DAGCombinerInfo &DCI,
17088 const X86Subtarget *Subtarget) {
17089 EVT VT = N->getValueType(0);
17090 if (DCI.isBeforeLegalizeOps())
17093 if (Subtarget->hasCMov()) {
17094 SDValue RV = performIntegerAbsCombine(N, DAG);
17099 // Try forming BMI if it is available.
17100 if (!Subtarget->hasBMI())
17103 if (VT != MVT::i32 && VT != MVT::i64)
17106 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17108 // Create BLSMSK instructions by finding X ^ (X-1)
17109 SDValue N0 = N->getOperand(0);
17110 SDValue N1 = N->getOperand(1);
17113 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17114 isAllOnes(N0.getOperand(1)))
17115 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17117 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17118 isAllOnes(N1.getOperand(1)))
17119 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17124 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17125 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17126 TargetLowering::DAGCombinerInfo &DCI,
17127 const X86Subtarget *Subtarget) {
17128 LoadSDNode *Ld = cast<LoadSDNode>(N);
17129 EVT RegVT = Ld->getValueType(0);
17130 EVT MemVT = Ld->getMemoryVT();
17132 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17133 unsigned RegSz = RegVT.getSizeInBits();
17135 // On Sandybridge unaligned 256bit loads are inefficient.
17136 ISD::LoadExtType Ext = Ld->getExtensionType();
17137 unsigned Alignment = Ld->getAlignment();
17138 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17139 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17140 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17141 unsigned NumElems = RegVT.getVectorNumElements();
17145 SDValue Ptr = Ld->getBasePtr();
17146 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17148 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17150 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17151 Ld->getPointerInfo(), Ld->isVolatile(),
17152 Ld->isNonTemporal(), Ld->isInvariant(),
17154 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17155 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17156 Ld->getPointerInfo(), Ld->isVolatile(),
17157 Ld->isNonTemporal(), Ld->isInvariant(),
17158 std::min(16U, Alignment));
17159 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17161 Load2.getValue(1));
17163 SDValue NewVec = DAG.getUNDEF(RegVT);
17164 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17165 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17166 return DCI.CombineTo(N, NewVec, TF, true);
17169 // If this is a vector EXT Load then attempt to optimize it using a
17170 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17171 // expansion is still better than scalar code.
17172 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17173 // emit a shuffle and a arithmetic shift.
17174 // TODO: It is possible to support ZExt by zeroing the undef values
17175 // during the shuffle phase or after the shuffle.
17176 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17177 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17178 assert(MemVT != RegVT && "Cannot extend to the same type");
17179 assert(MemVT.isVector() && "Must load a vector from memory");
17181 unsigned NumElems = RegVT.getVectorNumElements();
17182 unsigned MemSz = MemVT.getSizeInBits();
17183 assert(RegSz > MemSz && "Register size must be greater than the mem size");
17185 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17188 // All sizes must be a power of two.
17189 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17192 // Attempt to load the original value using scalar loads.
17193 // Find the largest scalar type that divides the total loaded size.
17194 MVT SclrLoadTy = MVT::i8;
17195 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17196 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17197 MVT Tp = (MVT::SimpleValueType)tp;
17198 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17203 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17204 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17206 SclrLoadTy = MVT::f64;
17208 // Calculate the number of scalar loads that we need to perform
17209 // in order to load our vector from memory.
17210 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17211 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17214 unsigned loadRegZize = RegSz;
17215 if (Ext == ISD::SEXTLOAD && RegSz == 256)
17218 // Represent our vector as a sequence of elements which are the
17219 // largest scalar that we can load.
17220 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17221 loadRegZize/SclrLoadTy.getSizeInBits());
17223 // Represent the data using the same element type that is stored in
17224 // memory. In practice, we ''widen'' MemVT.
17226 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17227 loadRegZize/MemVT.getScalarType().getSizeInBits());
17229 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17230 "Invalid vector type");
17232 // We can't shuffle using an illegal type.
17233 if (!TLI.isTypeLegal(WideVecVT))
17236 SmallVector<SDValue, 8> Chains;
17237 SDValue Ptr = Ld->getBasePtr();
17238 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17239 TLI.getPointerTy());
17240 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17242 for (unsigned i = 0; i < NumLoads; ++i) {
17243 // Perform a single load.
17244 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17245 Ptr, Ld->getPointerInfo(),
17246 Ld->isVolatile(), Ld->isNonTemporal(),
17247 Ld->isInvariant(), Ld->getAlignment());
17248 Chains.push_back(ScalarLoad.getValue(1));
17249 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17250 // another round of DAGCombining.
17252 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17254 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17255 ScalarLoad, DAG.getIntPtrConstant(i));
17257 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17260 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17263 // Bitcast the loaded value to a vector of the original element type, in
17264 // the size of the target vector type.
17265 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17266 unsigned SizeRatio = RegSz/MemSz;
17268 if (Ext == ISD::SEXTLOAD) {
17269 // If we have SSE4.1 we can directly emit a VSEXT node.
17270 if (Subtarget->hasSSE41()) {
17271 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17272 return DCI.CombineTo(N, Sext, TF, true);
17275 // Otherwise we'll shuffle the small elements in the high bits of the
17276 // larger type and perform an arithmetic shift. If the shift is not legal
17277 // it's better to scalarize.
17278 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17281 // Redistribute the loaded elements into the different locations.
17282 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17283 for (unsigned i = 0; i != NumElems; ++i)
17284 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17286 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17287 DAG.getUNDEF(WideVecVT),
17290 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17292 // Build the arithmetic shift.
17293 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17294 MemVT.getVectorElementType().getSizeInBits();
17295 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17296 DAG.getConstant(Amt, RegVT));
17298 return DCI.CombineTo(N, Shuff, TF, true);
17301 // Redistribute the loaded elements into the different locations.
17302 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17303 for (unsigned i = 0; i != NumElems; ++i)
17304 ShuffleVec[i*SizeRatio] = i;
17306 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17307 DAG.getUNDEF(WideVecVT),
17310 // Bitcast to the requested type.
17311 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17312 // Replace the original load with the new sequence
17313 // and return the new chain.
17314 return DCI.CombineTo(N, Shuff, TF, true);
17320 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17321 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17322 const X86Subtarget *Subtarget) {
17323 StoreSDNode *St = cast<StoreSDNode>(N);
17324 EVT VT = St->getValue().getValueType();
17325 EVT StVT = St->getMemoryVT();
17327 SDValue StoredVal = St->getOperand(1);
17328 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17330 // If we are saving a concatenation of two XMM registers, perform two stores.
17331 // On Sandy Bridge, 256-bit memory operations are executed by two
17332 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17333 // memory operation.
17334 unsigned Alignment = St->getAlignment();
17335 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17336 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17337 StVT == VT && !IsAligned) {
17338 unsigned NumElems = VT.getVectorNumElements();
17342 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17343 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17345 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17346 SDValue Ptr0 = St->getBasePtr();
17347 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17349 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17350 St->getPointerInfo(), St->isVolatile(),
17351 St->isNonTemporal(), Alignment);
17352 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17353 St->getPointerInfo(), St->isVolatile(),
17354 St->isNonTemporal(),
17355 std::min(16U, Alignment));
17356 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17359 // Optimize trunc store (of multiple scalars) to shuffle and store.
17360 // First, pack all of the elements in one place. Next, store to memory
17361 // in fewer chunks.
17362 if (St->isTruncatingStore() && VT.isVector()) {
17363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17364 unsigned NumElems = VT.getVectorNumElements();
17365 assert(StVT != VT && "Cannot truncate to the same type");
17366 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17367 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17369 // From, To sizes and ElemCount must be pow of two
17370 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17371 // We are going to use the original vector elt for storing.
17372 // Accumulated smaller vector elements must be a multiple of the store size.
17373 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17375 unsigned SizeRatio = FromSz / ToSz;
17377 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17379 // Create a type on which we perform the shuffle
17380 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17381 StVT.getScalarType(), NumElems*SizeRatio);
17383 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17385 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17386 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17387 for (unsigned i = 0; i != NumElems; ++i)
17388 ShuffleVec[i] = i * SizeRatio;
17390 // Can't shuffle using an illegal type.
17391 if (!TLI.isTypeLegal(WideVecVT))
17394 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17395 DAG.getUNDEF(WideVecVT),
17397 // At this point all of the data is stored at the bottom of the
17398 // register. We now need to save it to mem.
17400 // Find the largest store unit
17401 MVT StoreType = MVT::i8;
17402 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17403 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17404 MVT Tp = (MVT::SimpleValueType)tp;
17405 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17409 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17410 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17411 (64 <= NumElems * ToSz))
17412 StoreType = MVT::f64;
17414 // Bitcast the original vector into a vector of store-size units
17415 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17416 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17417 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17418 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17419 SmallVector<SDValue, 8> Chains;
17420 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17421 TLI.getPointerTy());
17422 SDValue Ptr = St->getBasePtr();
17424 // Perform one or more big stores into memory.
17425 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17426 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17427 StoreType, ShuffWide,
17428 DAG.getIntPtrConstant(i));
17429 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17430 St->getPointerInfo(), St->isVolatile(),
17431 St->isNonTemporal(), St->getAlignment());
17432 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17433 Chains.push_back(Ch);
17436 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17440 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
17441 // the FP state in cases where an emms may be missing.
17442 // A preferable solution to the general problem is to figure out the right
17443 // places to insert EMMS. This qualifies as a quick hack.
17445 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17446 if (VT.getSizeInBits() != 64)
17449 const Function *F = DAG.getMachineFunction().getFunction();
17450 bool NoImplicitFloatOps = F->getAttributes().
17451 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17452 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17453 && Subtarget->hasSSE2();
17454 if ((VT.isVector() ||
17455 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17456 isa<LoadSDNode>(St->getValue()) &&
17457 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17458 St->getChain().hasOneUse() && !St->isVolatile()) {
17459 SDNode* LdVal = St->getValue().getNode();
17460 LoadSDNode *Ld = 0;
17461 int TokenFactorIndex = -1;
17462 SmallVector<SDValue, 8> Ops;
17463 SDNode* ChainVal = St->getChain().getNode();
17464 // Must be a store of a load. We currently handle two cases: the load
17465 // is a direct child, and it's under an intervening TokenFactor. It is
17466 // possible to dig deeper under nested TokenFactors.
17467 if (ChainVal == LdVal)
17468 Ld = cast<LoadSDNode>(St->getChain());
17469 else if (St->getValue().hasOneUse() &&
17470 ChainVal->getOpcode() == ISD::TokenFactor) {
17471 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17472 if (ChainVal->getOperand(i).getNode() == LdVal) {
17473 TokenFactorIndex = i;
17474 Ld = cast<LoadSDNode>(St->getValue());
17476 Ops.push_back(ChainVal->getOperand(i));
17480 if (!Ld || !ISD::isNormalLoad(Ld))
17483 // If this is not the MMX case, i.e. we are just turning i64 load/store
17484 // into f64 load/store, avoid the transformation if there are multiple
17485 // uses of the loaded value.
17486 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17491 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17492 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17494 if (Subtarget->is64Bit() || F64IsLegal) {
17495 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17496 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17497 Ld->getPointerInfo(), Ld->isVolatile(),
17498 Ld->isNonTemporal(), Ld->isInvariant(),
17499 Ld->getAlignment());
17500 SDValue NewChain = NewLd.getValue(1);
17501 if (TokenFactorIndex != -1) {
17502 Ops.push_back(NewChain);
17503 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17506 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17507 St->getPointerInfo(),
17508 St->isVolatile(), St->isNonTemporal(),
17509 St->getAlignment());
17512 // Otherwise, lower to two pairs of 32-bit loads / stores.
17513 SDValue LoAddr = Ld->getBasePtr();
17514 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17515 DAG.getConstant(4, MVT::i32));
17517 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17518 Ld->getPointerInfo(),
17519 Ld->isVolatile(), Ld->isNonTemporal(),
17520 Ld->isInvariant(), Ld->getAlignment());
17521 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17522 Ld->getPointerInfo().getWithOffset(4),
17523 Ld->isVolatile(), Ld->isNonTemporal(),
17525 MinAlign(Ld->getAlignment(), 4));
17527 SDValue NewChain = LoLd.getValue(1);
17528 if (TokenFactorIndex != -1) {
17529 Ops.push_back(LoLd);
17530 Ops.push_back(HiLd);
17531 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17535 LoAddr = St->getBasePtr();
17536 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17537 DAG.getConstant(4, MVT::i32));
17539 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17540 St->getPointerInfo(),
17541 St->isVolatile(), St->isNonTemporal(),
17542 St->getAlignment());
17543 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17544 St->getPointerInfo().getWithOffset(4),
17546 St->isNonTemporal(),
17547 MinAlign(St->getAlignment(), 4));
17548 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17553 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17554 /// and return the operands for the horizontal operation in LHS and RHS. A
17555 /// horizontal operation performs the binary operation on successive elements
17556 /// of its first operand, then on successive elements of its second operand,
17557 /// returning the resulting values in a vector. For example, if
17558 /// A = < float a0, float a1, float a2, float a3 >
17560 /// B = < float b0, float b1, float b2, float b3 >
17561 /// then the result of doing a horizontal operation on A and B is
17562 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17563 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17564 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17565 /// set to A, RHS to B, and the routine returns 'true'.
17566 /// Note that the binary operation should have the property that if one of the
17567 /// operands is UNDEF then the result is UNDEF.
17568 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17569 // Look for the following pattern: if
17570 // A = < float a0, float a1, float a2, float a3 >
17571 // B = < float b0, float b1, float b2, float b3 >
17573 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17574 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17575 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17576 // which is A horizontal-op B.
17578 // At least one of the operands should be a vector shuffle.
17579 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17580 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17583 EVT VT = LHS.getValueType();
17585 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17586 "Unsupported vector type for horizontal add/sub");
17588 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17589 // operate independently on 128-bit lanes.
17590 unsigned NumElts = VT.getVectorNumElements();
17591 unsigned NumLanes = VT.getSizeInBits()/128;
17592 unsigned NumLaneElts = NumElts / NumLanes;
17593 assert((NumLaneElts % 2 == 0) &&
17594 "Vector type should have an even number of elements in each lane");
17595 unsigned HalfLaneElts = NumLaneElts/2;
17597 // View LHS in the form
17598 // LHS = VECTOR_SHUFFLE A, B, LMask
17599 // If LHS is not a shuffle then pretend it is the shuffle
17600 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17601 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17604 SmallVector<int, 16> LMask(NumElts);
17605 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17606 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17607 A = LHS.getOperand(0);
17608 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17609 B = LHS.getOperand(1);
17610 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17611 std::copy(Mask.begin(), Mask.end(), LMask.begin());
17613 if (LHS.getOpcode() != ISD::UNDEF)
17615 for (unsigned i = 0; i != NumElts; ++i)
17619 // Likewise, view RHS in the form
17620 // RHS = VECTOR_SHUFFLE C, D, RMask
17622 SmallVector<int, 16> RMask(NumElts);
17623 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17624 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17625 C = RHS.getOperand(0);
17626 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17627 D = RHS.getOperand(1);
17628 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17629 std::copy(Mask.begin(), Mask.end(), RMask.begin());
17631 if (RHS.getOpcode() != ISD::UNDEF)
17633 for (unsigned i = 0; i != NumElts; ++i)
17637 // Check that the shuffles are both shuffling the same vectors.
17638 if (!(A == C && B == D) && !(A == D && B == C))
17641 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17642 if (!A.getNode() && !B.getNode())
17645 // If A and B occur in reverse order in RHS, then "swap" them (which means
17646 // rewriting the mask).
17648 CommuteVectorShuffleMask(RMask, NumElts);
17650 // At this point LHS and RHS are equivalent to
17651 // LHS = VECTOR_SHUFFLE A, B, LMask
17652 // RHS = VECTOR_SHUFFLE A, B, RMask
17653 // Check that the masks correspond to performing a horizontal operation.
17654 for (unsigned i = 0; i != NumElts; ++i) {
17655 int LIdx = LMask[i], RIdx = RMask[i];
17657 // Ignore any UNDEF components.
17658 if (LIdx < 0 || RIdx < 0 ||
17659 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17660 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17663 // Check that successive elements are being operated on. If not, this is
17664 // not a horizontal operation.
17665 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17666 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17667 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17668 if (!(LIdx == Index && RIdx == Index + 1) &&
17669 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17673 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17674 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17678 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17679 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17680 const X86Subtarget *Subtarget) {
17681 EVT VT = N->getValueType(0);
17682 SDValue LHS = N->getOperand(0);
17683 SDValue RHS = N->getOperand(1);
17685 // Try to synthesize horizontal adds from adds of shuffles.
17686 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17687 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17688 isHorizontalBinOp(LHS, RHS, true))
17689 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17693 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17694 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17695 const X86Subtarget *Subtarget) {
17696 EVT VT = N->getValueType(0);
17697 SDValue LHS = N->getOperand(0);
17698 SDValue RHS = N->getOperand(1);
17700 // Try to synthesize horizontal subs from subs of shuffles.
17701 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17702 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17703 isHorizontalBinOp(LHS, RHS, false))
17704 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17708 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17709 /// X86ISD::FXOR nodes.
17710 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17711 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17712 // F[X]OR(0.0, x) -> x
17713 // F[X]OR(x, 0.0) -> x
17714 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17715 if (C->getValueAPF().isPosZero())
17716 return N->getOperand(1);
17717 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17718 if (C->getValueAPF().isPosZero())
17719 return N->getOperand(0);
17723 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17724 /// X86ISD::FMAX nodes.
17725 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17726 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17728 // Only perform optimizations if UnsafeMath is used.
17729 if (!DAG.getTarget().Options.UnsafeFPMath)
17732 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17733 // into FMINC and FMAXC, which are Commutative operations.
17734 unsigned NewOp = 0;
17735 switch (N->getOpcode()) {
17736 default: llvm_unreachable("unknown opcode");
17737 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
17738 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
17741 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17742 N->getOperand(0), N->getOperand(1));
17745 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17746 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17747 // FAND(0.0, x) -> 0.0
17748 // FAND(x, 0.0) -> 0.0
17749 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17750 if (C->getValueAPF().isPosZero())
17751 return N->getOperand(0);
17752 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17753 if (C->getValueAPF().isPosZero())
17754 return N->getOperand(1);
17758 static SDValue PerformBTCombine(SDNode *N,
17760 TargetLowering::DAGCombinerInfo &DCI) {
17761 // BT ignores high bits in the bit index operand.
17762 SDValue Op1 = N->getOperand(1);
17763 if (Op1.hasOneUse()) {
17764 unsigned BitWidth = Op1.getValueSizeInBits();
17765 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17766 APInt KnownZero, KnownOne;
17767 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17768 !DCI.isBeforeLegalizeOps());
17769 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17770 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17771 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17772 DCI.CommitTargetLoweringOpt(TLO);
17777 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17778 SDValue Op = N->getOperand(0);
17779 if (Op.getOpcode() == ISD::BITCAST)
17780 Op = Op.getOperand(0);
17781 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17782 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17783 VT.getVectorElementType().getSizeInBits() ==
17784 OpVT.getVectorElementType().getSizeInBits()) {
17785 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17790 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17791 const X86Subtarget *Subtarget) {
17792 EVT VT = N->getValueType(0);
17793 if (!VT.isVector())
17796 SDValue N0 = N->getOperand(0);
17797 SDValue N1 = N->getOperand(1);
17798 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17801 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17802 // both SSE and AVX2 since there is no sign-extended shift right
17803 // operation on a vector with 64-bit elements.
17804 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17805 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17806 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17807 N0.getOpcode() == ISD::SIGN_EXTEND)) {
17808 SDValue N00 = N0.getOperand(0);
17810 // EXTLOAD has a better solution on AVX2,
17811 // it may be replaced with X86ISD::VSEXT node.
17812 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17813 if (!ISD::isNormalLoad(N00.getNode()))
17816 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17817 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17819 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17825 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17826 TargetLowering::DAGCombinerInfo &DCI,
17827 const X86Subtarget *Subtarget) {
17828 if (!DCI.isBeforeLegalizeOps())
17831 if (!Subtarget->hasFp256())
17834 EVT VT = N->getValueType(0);
17835 if (VT.isVector() && VT.getSizeInBits() == 256) {
17836 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17844 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17845 const X86Subtarget* Subtarget) {
17847 EVT VT = N->getValueType(0);
17849 // Let legalize expand this if it isn't a legal type yet.
17850 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17853 EVT ScalarVT = VT.getScalarType();
17854 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17855 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17858 SDValue A = N->getOperand(0);
17859 SDValue B = N->getOperand(1);
17860 SDValue C = N->getOperand(2);
17862 bool NegA = (A.getOpcode() == ISD::FNEG);
17863 bool NegB = (B.getOpcode() == ISD::FNEG);
17864 bool NegC = (C.getOpcode() == ISD::FNEG);
17866 // Negative multiplication when NegA xor NegB
17867 bool NegMul = (NegA != NegB);
17869 A = A.getOperand(0);
17871 B = B.getOperand(0);
17873 C = C.getOperand(0);
17877 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17879 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17881 return DAG.getNode(Opcode, dl, VT, A, B, C);
17884 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17885 TargetLowering::DAGCombinerInfo &DCI,
17886 const X86Subtarget *Subtarget) {
17887 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
17888 // (and (i32 x86isd::setcc_carry), 1)
17889 // This eliminates the zext. This transformation is necessary because
17890 // ISD::SETCC is always legalized to i8.
17892 SDValue N0 = N->getOperand(0);
17893 EVT VT = N->getValueType(0);
17895 if (N0.getOpcode() == ISD::AND &&
17897 N0.getOperand(0).hasOneUse()) {
17898 SDValue N00 = N0.getOperand(0);
17899 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17900 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17901 if (!C || C->getZExtValue() != 1)
17903 return DAG.getNode(ISD::AND, dl, VT,
17904 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17905 N00.getOperand(0), N00.getOperand(1)),
17906 DAG.getConstant(1, VT));
17910 if (VT.is256BitVector()) {
17911 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17919 // Optimize x == -y --> x+y == 0
17920 // x != -y --> x+y != 0
17921 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17922 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17923 SDValue LHS = N->getOperand(0);
17924 SDValue RHS = N->getOperand(1);
17926 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17927 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17928 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17929 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17930 LHS.getValueType(), RHS, LHS.getOperand(1));
17931 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17932 addV, DAG.getConstant(0, addV.getValueType()), CC);
17934 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17935 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17936 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17937 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17938 RHS.getValueType(), LHS, RHS.getOperand(1));
17939 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17940 addV, DAG.getConstant(0, addV.getValueType()), CC);
17945 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17946 // as "sbb reg,reg", since it can be extended without zext and produces
17947 // an all-ones bit which is more useful than 0/1 in some cases.
17948 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17949 return DAG.getNode(ISD::AND, DL, MVT::i8,
17950 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17951 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17952 DAG.getConstant(1, MVT::i8));
17955 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17956 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17957 TargetLowering::DAGCombinerInfo &DCI,
17958 const X86Subtarget *Subtarget) {
17960 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17961 SDValue EFLAGS = N->getOperand(1);
17963 if (CC == X86::COND_A) {
17964 // Try to convert COND_A into COND_B in an attempt to facilitate
17965 // materializing "setb reg".
17967 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17968 // cannot take an immediate as its first operand.
17970 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17971 EFLAGS.getValueType().isInteger() &&
17972 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17973 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17974 EFLAGS.getNode()->getVTList(),
17975 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17976 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17977 return MaterializeSETB(DL, NewEFLAGS, DAG);
17981 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17982 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17984 if (CC == X86::COND_B)
17985 return MaterializeSETB(DL, EFLAGS, DAG);
17989 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17990 if (Flags.getNode()) {
17991 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17992 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17998 // Optimize branch condition evaluation.
18000 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18001 TargetLowering::DAGCombinerInfo &DCI,
18002 const X86Subtarget *Subtarget) {
18004 SDValue Chain = N->getOperand(0);
18005 SDValue Dest = N->getOperand(1);
18006 SDValue EFLAGS = N->getOperand(3);
18007 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18011 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18012 if (Flags.getNode()) {
18013 SDValue Cond = DAG.getConstant(CC, MVT::i8);
18014 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18021 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18022 const X86TargetLowering *XTLI) {
18023 SDValue Op0 = N->getOperand(0);
18024 EVT InVT = Op0->getValueType(0);
18026 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18027 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18029 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18030 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18031 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18034 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18035 // a 32-bit target where SSE doesn't support i64->FP operations.
18036 if (Op0.getOpcode() == ISD::LOAD) {
18037 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18038 EVT VT = Ld->getValueType(0);
18039 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18040 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18041 !XTLI->getSubtarget()->is64Bit() &&
18042 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18043 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18044 Ld->getChain(), Op0, DAG);
18045 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18052 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18053 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18054 X86TargetLowering::DAGCombinerInfo &DCI) {
18055 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18056 // the result is either zero or one (depending on the input carry bit).
18057 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18058 if (X86::isZeroNode(N->getOperand(0)) &&
18059 X86::isZeroNode(N->getOperand(1)) &&
18060 // We don't have a good way to replace an EFLAGS use, so only do this when
18062 SDValue(N, 1).use_empty()) {
18064 EVT VT = N->getValueType(0);
18065 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18066 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18067 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18068 DAG.getConstant(X86::COND_B,MVT::i8),
18070 DAG.getConstant(1, VT));
18071 return DCI.CombineTo(N, Res1, CarryOut);
18077 // fold (add Y, (sete X, 0)) -> adc 0, Y
18078 // (add Y, (setne X, 0)) -> sbb -1, Y
18079 // (sub (sete X, 0), Y) -> sbb 0, Y
18080 // (sub (setne X, 0), Y) -> adc -1, Y
18081 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18084 // Look through ZExts.
18085 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18086 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18089 SDValue SetCC = Ext.getOperand(0);
18090 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18093 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18094 if (CC != X86::COND_E && CC != X86::COND_NE)
18097 SDValue Cmp = SetCC.getOperand(1);
18098 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18099 !X86::isZeroNode(Cmp.getOperand(1)) ||
18100 !Cmp.getOperand(0).getValueType().isInteger())
18103 SDValue CmpOp0 = Cmp.getOperand(0);
18104 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18105 DAG.getConstant(1, CmpOp0.getValueType()));
18107 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18108 if (CC == X86::COND_NE)
18109 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18110 DL, OtherVal.getValueType(), OtherVal,
18111 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18112 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18113 DL, OtherVal.getValueType(), OtherVal,
18114 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18117 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18118 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18119 const X86Subtarget *Subtarget) {
18120 EVT VT = N->getValueType(0);
18121 SDValue Op0 = N->getOperand(0);
18122 SDValue Op1 = N->getOperand(1);
18124 // Try to synthesize horizontal adds from adds of shuffles.
18125 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18126 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18127 isHorizontalBinOp(Op0, Op1, true))
18128 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18130 return OptimizeConditionalInDecrement(N, DAG);
18133 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18134 const X86Subtarget *Subtarget) {
18135 SDValue Op0 = N->getOperand(0);
18136 SDValue Op1 = N->getOperand(1);
18138 // X86 can't encode an immediate LHS of a sub. See if we can push the
18139 // negation into a preceding instruction.
18140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18141 // If the RHS of the sub is a XOR with one use and a constant, invert the
18142 // immediate. Then add one to the LHS of the sub so we can turn
18143 // X-Y -> X+~Y+1, saving one register.
18144 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18145 isa<ConstantSDNode>(Op1.getOperand(1))) {
18146 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18147 EVT VT = Op0.getValueType();
18148 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18150 DAG.getConstant(~XorC, VT));
18151 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18152 DAG.getConstant(C->getAPIntValue()+1, VT));
18156 // Try to synthesize horizontal adds from adds of shuffles.
18157 EVT VT = N->getValueType(0);
18158 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18159 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18160 isHorizontalBinOp(Op0, Op1, true))
18161 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18163 return OptimizeConditionalInDecrement(N, DAG);
18166 /// performVZEXTCombine - Performs build vector combines
18167 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18168 TargetLowering::DAGCombinerInfo &DCI,
18169 const X86Subtarget *Subtarget) {
18170 // (vzext (bitcast (vzext (x)) -> (vzext x)
18171 SDValue In = N->getOperand(0);
18172 while (In.getOpcode() == ISD::BITCAST)
18173 In = In.getOperand(0);
18175 if (In.getOpcode() != X86ISD::VZEXT)
18178 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18182 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18183 DAGCombinerInfo &DCI) const {
18184 SelectionDAG &DAG = DCI.DAG;
18185 switch (N->getOpcode()) {
18187 case ISD::EXTRACT_VECTOR_ELT:
18188 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18190 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18191 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18192 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
18193 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
18194 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
18195 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
18198 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
18199 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
18200 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
18201 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
18202 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
18203 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
18204 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
18205 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
18206 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
18208 case X86ISD::FOR: return PerformFORCombine(N, DAG);
18210 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
18211 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
18212 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
18213 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
18214 case ISD::ANY_EXTEND:
18215 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
18216 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
18217 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18218 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18219 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
18220 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18221 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18222 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
18223 case X86ISD::SHUFP: // Handle all target specific shuffles
18224 case X86ISD::PALIGNR:
18225 case X86ISD::UNPCKH:
18226 case X86ISD::UNPCKL:
18227 case X86ISD::MOVHLPS:
18228 case X86ISD::MOVLHPS:
18229 case X86ISD::PSHUFD:
18230 case X86ISD::PSHUFHW:
18231 case X86ISD::PSHUFLW:
18232 case X86ISD::MOVSS:
18233 case X86ISD::MOVSD:
18234 case X86ISD::VPERMILP:
18235 case X86ISD::VPERM2X128:
18236 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18237 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
18243 /// isTypeDesirableForOp - Return true if the target has native support for
18244 /// the specified value type and it is 'desirable' to use the type for the
18245 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18246 /// instruction encodings are longer and some i16 instructions are slow.
18247 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18248 if (!isTypeLegal(VT))
18250 if (VT != MVT::i16)
18257 case ISD::SIGN_EXTEND:
18258 case ISD::ZERO_EXTEND:
18259 case ISD::ANY_EXTEND:
18272 /// IsDesirableToPromoteOp - This method query the target whether it is
18273 /// beneficial for dag combiner to promote the specified node. If true, it
18274 /// should return the desired promotion type by reference.
18275 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18276 EVT VT = Op.getValueType();
18277 if (VT != MVT::i16)
18280 bool Promote = false;
18281 bool Commute = false;
18282 switch (Op.getOpcode()) {
18285 LoadSDNode *LD = cast<LoadSDNode>(Op);
18286 // If the non-extending load has a single use and it's not live out, then it
18287 // might be folded.
18288 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18289 Op.hasOneUse()*/) {
18290 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18291 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18292 // The only case where we'd want to promote LOAD (rather then it being
18293 // promoted as an operand is when it's only use is liveout.
18294 if (UI->getOpcode() != ISD::CopyToReg)
18301 case ISD::SIGN_EXTEND:
18302 case ISD::ZERO_EXTEND:
18303 case ISD::ANY_EXTEND:
18308 SDValue N0 = Op.getOperand(0);
18309 // Look out for (store (shl (load), x)).
18310 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18323 SDValue N0 = Op.getOperand(0);
18324 SDValue N1 = Op.getOperand(1);
18325 if (!Commute && MayFoldLoad(N1))
18327 // Avoid disabling potential load folding opportunities.
18328 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18330 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18340 //===----------------------------------------------------------------------===//
18341 // X86 Inline Assembly Support
18342 //===----------------------------------------------------------------------===//
18345 // Helper to match a string separated by whitespace.
18346 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18347 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18349 for (unsigned i = 0, e = args.size(); i != e; ++i) {
18350 StringRef piece(*args[i]);
18351 if (!s.startswith(piece)) // Check if the piece matches.
18354 s = s.substr(piece.size());
18355 StringRef::size_type pos = s.find_first_not_of(" \t");
18356 if (pos == 0) // We matched a prefix.
18364 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18367 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18368 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18370 std::string AsmStr = IA->getAsmString();
18372 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18373 if (!Ty || Ty->getBitWidth() % 16 != 0)
18376 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18377 SmallVector<StringRef, 4> AsmPieces;
18378 SplitString(AsmStr, AsmPieces, ";\n");
18380 switch (AsmPieces.size()) {
18381 default: return false;
18383 // FIXME: this should verify that we are targeting a 486 or better. If not,
18384 // we will turn this bswap into something that will be lowered to logical
18385 // ops instead of emitting the bswap asm. For now, we don't support 486 or
18386 // lower so don't worry about this.
18388 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18389 matchAsm(AsmPieces[0], "bswapl", "$0") ||
18390 matchAsm(AsmPieces[0], "bswapq", "$0") ||
18391 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18392 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18393 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18394 // No need to check constraints, nothing other than the equivalent of
18395 // "=r,0" would be valid here.
18396 return IntrinsicLowering::LowerToByteSwap(CI);
18399 // rorw $$8, ${0:w} --> llvm.bswap.i16
18400 if (CI->getType()->isIntegerTy(16) &&
18401 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18402 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18403 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18405 const std::string &ConstraintsStr = IA->getConstraintString();
18406 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18407 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18408 if (AsmPieces.size() == 4 &&
18409 AsmPieces[0] == "~{cc}" &&
18410 AsmPieces[1] == "~{dirflag}" &&
18411 AsmPieces[2] == "~{flags}" &&
18412 AsmPieces[3] == "~{fpsr}")
18413 return IntrinsicLowering::LowerToByteSwap(CI);
18417 if (CI->getType()->isIntegerTy(32) &&
18418 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18419 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18420 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18421 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18423 const std::string &ConstraintsStr = IA->getConstraintString();
18424 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18425 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18426 if (AsmPieces.size() == 4 &&
18427 AsmPieces[0] == "~{cc}" &&
18428 AsmPieces[1] == "~{dirflag}" &&
18429 AsmPieces[2] == "~{flags}" &&
18430 AsmPieces[3] == "~{fpsr}")
18431 return IntrinsicLowering::LowerToByteSwap(CI);
18434 if (CI->getType()->isIntegerTy(64)) {
18435 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18436 if (Constraints.size() >= 2 &&
18437 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18438 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18439 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
18440 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18441 matchAsm(AsmPieces[1], "bswap", "%edx") &&
18442 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18443 return IntrinsicLowering::LowerToByteSwap(CI);
18451 /// getConstraintType - Given a constraint letter, return the type of
18452 /// constraint it is for this target.
18453 X86TargetLowering::ConstraintType
18454 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18455 if (Constraint.size() == 1) {
18456 switch (Constraint[0]) {
18467 return C_RegisterClass;
18491 return TargetLowering::getConstraintType(Constraint);
18494 /// Examine constraint type and operand type and determine a weight value.
18495 /// This object must already have been set up with the operand type
18496 /// and the current alternative constraint selected.
18497 TargetLowering::ConstraintWeight
18498 X86TargetLowering::getSingleConstraintMatchWeight(
18499 AsmOperandInfo &info, const char *constraint) const {
18500 ConstraintWeight weight = CW_Invalid;
18501 Value *CallOperandVal = info.CallOperandVal;
18502 // If we don't have a value, we can't do a match,
18503 // but allow it at the lowest weight.
18504 if (CallOperandVal == NULL)
18506 Type *type = CallOperandVal->getType();
18507 // Look at the constraint type.
18508 switch (*constraint) {
18510 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18521 if (CallOperandVal->getType()->isIntegerTy())
18522 weight = CW_SpecificReg;
18527 if (type->isFloatingPointTy())
18528 weight = CW_SpecificReg;
18531 if (type->isX86_MMXTy() && Subtarget->hasMMX())
18532 weight = CW_SpecificReg;
18536 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18537 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18538 weight = CW_Register;
18541 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18542 if (C->getZExtValue() <= 31)
18543 weight = CW_Constant;
18547 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18548 if (C->getZExtValue() <= 63)
18549 weight = CW_Constant;
18553 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18554 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18555 weight = CW_Constant;
18559 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18560 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18561 weight = CW_Constant;
18565 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18566 if (C->getZExtValue() <= 3)
18567 weight = CW_Constant;
18571 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18572 if (C->getZExtValue() <= 0xff)
18573 weight = CW_Constant;
18578 if (dyn_cast<ConstantFP>(CallOperandVal)) {
18579 weight = CW_Constant;
18583 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18584 if ((C->getSExtValue() >= -0x80000000LL) &&
18585 (C->getSExtValue() <= 0x7fffffffLL))
18586 weight = CW_Constant;
18590 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18591 if (C->getZExtValue() <= 0xffffffff)
18592 weight = CW_Constant;
18599 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18600 /// with another that has more specific requirements based on the type of the
18601 /// corresponding operand.
18602 const char *X86TargetLowering::
18603 LowerXConstraint(EVT ConstraintVT) const {
18604 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18605 // 'f' like normal targets.
18606 if (ConstraintVT.isFloatingPoint()) {
18607 if (Subtarget->hasSSE2())
18609 if (Subtarget->hasSSE1())
18613 return TargetLowering::LowerXConstraint(ConstraintVT);
18616 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18617 /// vector. If it is invalid, don't add anything to Ops.
18618 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18619 std::string &Constraint,
18620 std::vector<SDValue>&Ops,
18621 SelectionDAG &DAG) const {
18622 SDValue Result(0, 0);
18624 // Only support length 1 constraints for now.
18625 if (Constraint.length() > 1) return;
18627 char ConstraintLetter = Constraint[0];
18628 switch (ConstraintLetter) {
18631 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18632 if (C->getZExtValue() <= 31) {
18633 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18639 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18640 if (C->getZExtValue() <= 63) {
18641 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18648 if (isInt<8>(C->getSExtValue())) {
18649 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18655 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18656 if (C->getZExtValue() <= 255) {
18657 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18663 // 32-bit signed value
18664 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18665 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18666 C->getSExtValue())) {
18667 // Widen to 64 bits here to get it sign extended.
18668 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18671 // FIXME gcc accepts some relocatable values here too, but only in certain
18672 // memory models; it's complicated.
18677 // 32-bit unsigned value
18678 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18679 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18680 C->getZExtValue())) {
18681 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18685 // FIXME gcc accepts some relocatable values here too, but only in certain
18686 // memory models; it's complicated.
18690 // Literal immediates are always ok.
18691 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18692 // Widen to 64 bits here to get it sign extended.
18693 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18697 // In any sort of PIC mode addresses need to be computed at runtime by
18698 // adding in a register or some sort of table lookup. These can't
18699 // be used as immediates.
18700 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18703 // If we are in non-pic codegen mode, we allow the address of a global (with
18704 // an optional displacement) to be used with 'i'.
18705 GlobalAddressSDNode *GA = 0;
18706 int64_t Offset = 0;
18708 // Match either (GA), (GA+C), (GA+C1+C2), etc.
18710 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18711 Offset += GA->getOffset();
18713 } else if (Op.getOpcode() == ISD::ADD) {
18714 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18715 Offset += C->getZExtValue();
18716 Op = Op.getOperand(0);
18719 } else if (Op.getOpcode() == ISD::SUB) {
18720 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18721 Offset += -C->getZExtValue();
18722 Op = Op.getOperand(0);
18727 // Otherwise, this isn't something we can handle, reject it.
18731 const GlobalValue *GV = GA->getGlobal();
18732 // If we require an extra load to get this address, as in PIC mode, we
18733 // can't accept it.
18734 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18735 getTargetMachine())))
18738 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18739 GA->getValueType(0), Offset);
18744 if (Result.getNode()) {
18745 Ops.push_back(Result);
18748 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18751 std::pair<unsigned, const TargetRegisterClass*>
18752 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18754 // First, see if this is a constraint that directly corresponds to an LLVM
18756 if (Constraint.size() == 1) {
18757 // GCC Constraint Letters
18758 switch (Constraint[0]) {
18760 // TODO: Slight differences here in allocation order and leaving
18761 // RIP in the class. Do they matter any more here than they do
18762 // in the normal allocation?
18763 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18764 if (Subtarget->is64Bit()) {
18765 if (VT == MVT::i32 || VT == MVT::f32)
18766 return std::make_pair(0U, &X86::GR32RegClass);
18767 if (VT == MVT::i16)
18768 return std::make_pair(0U, &X86::GR16RegClass);
18769 if (VT == MVT::i8 || VT == MVT::i1)
18770 return std::make_pair(0U, &X86::GR8RegClass);
18771 if (VT == MVT::i64 || VT == MVT::f64)
18772 return std::make_pair(0U, &X86::GR64RegClass);
18775 // 32-bit fallthrough
18776 case 'Q': // Q_REGS
18777 if (VT == MVT::i32 || VT == MVT::f32)
18778 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18779 if (VT == MVT::i16)
18780 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18781 if (VT == MVT::i8 || VT == MVT::i1)
18782 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18783 if (VT == MVT::i64)
18784 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18786 case 'r': // GENERAL_REGS
18787 case 'l': // INDEX_REGS
18788 if (VT == MVT::i8 || VT == MVT::i1)
18789 return std::make_pair(0U, &X86::GR8RegClass);
18790 if (VT == MVT::i16)
18791 return std::make_pair(0U, &X86::GR16RegClass);
18792 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18793 return std::make_pair(0U, &X86::GR32RegClass);
18794 return std::make_pair(0U, &X86::GR64RegClass);
18795 case 'R': // LEGACY_REGS
18796 if (VT == MVT::i8 || VT == MVT::i1)
18797 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18798 if (VT == MVT::i16)
18799 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18800 if (VT == MVT::i32 || !Subtarget->is64Bit())
18801 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18802 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18803 case 'f': // FP Stack registers.
18804 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18805 // value to the correct fpstack register class.
18806 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18807 return std::make_pair(0U, &X86::RFP32RegClass);
18808 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18809 return std::make_pair(0U, &X86::RFP64RegClass);
18810 return std::make_pair(0U, &X86::RFP80RegClass);
18811 case 'y': // MMX_REGS if MMX allowed.
18812 if (!Subtarget->hasMMX()) break;
18813 return std::make_pair(0U, &X86::VR64RegClass);
18814 case 'Y': // SSE_REGS if SSE2 allowed
18815 if (!Subtarget->hasSSE2()) break;
18817 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18818 if (!Subtarget->hasSSE1()) break;
18820 switch (VT.SimpleTy) {
18822 // Scalar SSE types.
18825 return std::make_pair(0U, &X86::FR32RegClass);
18828 return std::make_pair(0U, &X86::FR64RegClass);
18836 return std::make_pair(0U, &X86::VR128RegClass);
18844 return std::make_pair(0U, &X86::VR256RegClass);
18849 return std::make_pair(0U, &X86::VR512RegClass);
18855 // Use the default implementation in TargetLowering to convert the register
18856 // constraint into a member of a register class.
18857 std::pair<unsigned, const TargetRegisterClass*> Res;
18858 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18860 // Not found as a standard register?
18861 if (Res.second == 0) {
18862 // Map st(0) -> st(7) -> ST0
18863 if (Constraint.size() == 7 && Constraint[0] == '{' &&
18864 tolower(Constraint[1]) == 's' &&
18865 tolower(Constraint[2]) == 't' &&
18866 Constraint[3] == '(' &&
18867 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18868 Constraint[5] == ')' &&
18869 Constraint[6] == '}') {
18871 Res.first = X86::ST0+Constraint[4]-'0';
18872 Res.second = &X86::RFP80RegClass;
18876 // GCC allows "st(0)" to be called just plain "st".
18877 if (StringRef("{st}").equals_lower(Constraint)) {
18878 Res.first = X86::ST0;
18879 Res.second = &X86::RFP80RegClass;
18884 if (StringRef("{flags}").equals_lower(Constraint)) {
18885 Res.first = X86::EFLAGS;
18886 Res.second = &X86::CCRRegClass;
18890 // 'A' means EAX + EDX.
18891 if (Constraint == "A") {
18892 Res.first = X86::EAX;
18893 Res.second = &X86::GR32_ADRegClass;
18899 // Otherwise, check to see if this is a register class of the wrong value
18900 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18901 // turn into {ax},{dx}.
18902 if (Res.second->hasType(VT))
18903 return Res; // Correct type already, nothing to do.
18905 // All of the single-register GCC register classes map their values onto
18906 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
18907 // really want an 8-bit or 32-bit register, map to the appropriate register
18908 // class and return the appropriate register.
18909 if (Res.second == &X86::GR16RegClass) {
18910 if (VT == MVT::i8 || VT == MVT::i1) {
18911 unsigned DestReg = 0;
18912 switch (Res.first) {
18914 case X86::AX: DestReg = X86::AL; break;
18915 case X86::DX: DestReg = X86::DL; break;
18916 case X86::CX: DestReg = X86::CL; break;
18917 case X86::BX: DestReg = X86::BL; break;
18920 Res.first = DestReg;
18921 Res.second = &X86::GR8RegClass;
18923 } else if (VT == MVT::i32 || VT == MVT::f32) {
18924 unsigned DestReg = 0;
18925 switch (Res.first) {
18927 case X86::AX: DestReg = X86::EAX; break;
18928 case X86::DX: DestReg = X86::EDX; break;
18929 case X86::CX: DestReg = X86::ECX; break;
18930 case X86::BX: DestReg = X86::EBX; break;
18931 case X86::SI: DestReg = X86::ESI; break;
18932 case X86::DI: DestReg = X86::EDI; break;
18933 case X86::BP: DestReg = X86::EBP; break;
18934 case X86::SP: DestReg = X86::ESP; break;
18937 Res.first = DestReg;
18938 Res.second = &X86::GR32RegClass;
18940 } else if (VT == MVT::i64 || VT == MVT::f64) {
18941 unsigned DestReg = 0;
18942 switch (Res.first) {
18944 case X86::AX: DestReg = X86::RAX; break;
18945 case X86::DX: DestReg = X86::RDX; break;
18946 case X86::CX: DestReg = X86::RCX; break;
18947 case X86::BX: DestReg = X86::RBX; break;
18948 case X86::SI: DestReg = X86::RSI; break;
18949 case X86::DI: DestReg = X86::RDI; break;
18950 case X86::BP: DestReg = X86::RBP; break;
18951 case X86::SP: DestReg = X86::RSP; break;
18954 Res.first = DestReg;
18955 Res.second = &X86::GR64RegClass;
18958 } else if (Res.second == &X86::FR32RegClass ||
18959 Res.second == &X86::FR64RegClass ||
18960 Res.second == &X86::VR128RegClass ||
18961 Res.second == &X86::VR256RegClass ||
18962 Res.second == &X86::FR32XRegClass ||
18963 Res.second == &X86::FR64XRegClass ||
18964 Res.second == &X86::VR128XRegClass ||
18965 Res.second == &X86::VR256XRegClass ||
18966 Res.second == &X86::VR512RegClass) {
18967 // Handle references to XMM physical registers that got mapped into the
18968 // wrong class. This can happen with constraints like {xmm0} where the
18969 // target independent register mapper will just pick the first match it can
18970 // find, ignoring the required type.
18972 if (VT == MVT::f32 || VT == MVT::i32)
18973 Res.second = &X86::FR32RegClass;
18974 else if (VT == MVT::f64 || VT == MVT::i64)
18975 Res.second = &X86::FR64RegClass;
18976 else if (X86::VR128RegClass.hasType(VT))
18977 Res.second = &X86::VR128RegClass;
18978 else if (X86::VR256RegClass.hasType(VT))
18979 Res.second = &X86::VR256RegClass;
18980 else if (X86::VR512RegClass.hasType(VT))
18981 Res.second = &X86::VR512RegClass;