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 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400 // Extract subvector is special because the value type
1401 // (result) is 256/128-bit but the source is 512-bit wide.
1402 if (VT.is128BitVector() || VT.is256BitVector())
1403 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1405 if (VT.getVectorElementType() == MVT::i1)
1406 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1408 // Do not attempt to custom lower other non-512-bit vectors
1409 if (!VT.is512BitVector())
1412 if (VT != MVT::v8i64) {
1413 setOperationAction(ISD::XOR, VT, Promote);
1414 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1415 setOperationAction(ISD::OR, VT, Promote);
1416 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1417 setOperationAction(ISD::AND, VT, Promote);
1418 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1420 if ( EltSize >= 32) {
1421 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1422 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1423 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1424 setOperationAction(ISD::VSELECT, VT, Legal);
1425 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1426 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1427 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1430 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1431 MVT VT = (MVT::SimpleValueType)i;
1433 // Do not attempt to promote non-256-bit vectors
1434 if (!VT.is512BitVector())
1437 setOperationAction(ISD::LOAD, VT, Promote);
1438 AddPromotedToType (ISD::LOAD, VT, MVT::v8i64);
1439 setOperationAction(ISD::SELECT, VT, Promote);
1440 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1444 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1445 // of this type with custom code.
1446 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1447 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1448 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1452 // We want to custom lower some of our intrinsics.
1453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1454 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1456 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1457 // handle type legalization for these operations here.
1459 // FIXME: We really should do custom legalization for addition and
1460 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1461 // than generic legalization for 64-bit multiplication-with-overflow, though.
1462 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1463 // Add/Sub/Mul with overflow operations are custom lowered.
1465 setOperationAction(ISD::SADDO, VT, Custom);
1466 setOperationAction(ISD::UADDO, VT, Custom);
1467 setOperationAction(ISD::SSUBO, VT, Custom);
1468 setOperationAction(ISD::USUBO, VT, Custom);
1469 setOperationAction(ISD::SMULO, VT, Custom);
1470 setOperationAction(ISD::UMULO, VT, Custom);
1473 // There are no 8-bit 3-address imul/mul instructions
1474 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1475 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1477 if (!Subtarget->is64Bit()) {
1478 // These libcalls are not available in 32-bit.
1479 setLibcallName(RTLIB::SHL_I128, 0);
1480 setLibcallName(RTLIB::SRL_I128, 0);
1481 setLibcallName(RTLIB::SRA_I128, 0);
1484 // Combine sin / cos into one node or libcall if possible.
1485 if (Subtarget->hasSinCos()) {
1486 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1487 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1488 if (Subtarget->isTargetDarwin()) {
1489 // For MacOSX, we don't want to the normal expansion of a libcall to
1490 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1492 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1493 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1497 // We have target-specific dag combine patterns for the following nodes:
1498 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1499 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1500 setTargetDAGCombine(ISD::VSELECT);
1501 setTargetDAGCombine(ISD::SELECT);
1502 setTargetDAGCombine(ISD::SHL);
1503 setTargetDAGCombine(ISD::SRA);
1504 setTargetDAGCombine(ISD::SRL);
1505 setTargetDAGCombine(ISD::OR);
1506 setTargetDAGCombine(ISD::AND);
1507 setTargetDAGCombine(ISD::ADD);
1508 setTargetDAGCombine(ISD::FADD);
1509 setTargetDAGCombine(ISD::FSUB);
1510 setTargetDAGCombine(ISD::FMA);
1511 setTargetDAGCombine(ISD::SUB);
1512 setTargetDAGCombine(ISD::LOAD);
1513 setTargetDAGCombine(ISD::STORE);
1514 setTargetDAGCombine(ISD::ZERO_EXTEND);
1515 setTargetDAGCombine(ISD::ANY_EXTEND);
1516 setTargetDAGCombine(ISD::SIGN_EXTEND);
1517 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1518 setTargetDAGCombine(ISD::TRUNCATE);
1519 setTargetDAGCombine(ISD::SINT_TO_FP);
1520 setTargetDAGCombine(ISD::SETCC);
1521 if (Subtarget->is64Bit())
1522 setTargetDAGCombine(ISD::MUL);
1523 setTargetDAGCombine(ISD::XOR);
1525 computeRegisterProperties();
1527 // On Darwin, -Os means optimize for size without hurting performance,
1528 // do not reduce the limit.
1529 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1530 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1531 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1532 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1534 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1535 setPrefLoopAlignment(4); // 2^4 bytes.
1537 // Predictable cmov don't hurt on atom because it's in-order.
1538 PredictableSelectIsExpensive = !Subtarget->isAtom();
1540 setPrefFunctionAlignment(4); // 2^4 bytes.
1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1544 if (!VT.isVector()) return MVT::i8;
1545 return VT.changeVectorElementTypeToInteger();
1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1549 /// the desired ByVal argument alignment.
1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1553 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1554 if (VTy->getBitWidth() == 128)
1556 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1557 unsigned EltAlign = 0;
1558 getMaxByValAlign(ATy->getElementType(), EltAlign);
1559 if (EltAlign > MaxAlign)
1560 MaxAlign = EltAlign;
1561 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1562 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1563 unsigned EltAlign = 0;
1564 getMaxByValAlign(STy->getElementType(i), EltAlign);
1565 if (EltAlign > MaxAlign)
1566 MaxAlign = EltAlign;
1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1574 /// function arguments in the caller parameter area. For X86, aggregates
1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1576 /// are at 4-byte boundaries.
1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1578 if (Subtarget->is64Bit()) {
1579 // Max of 8 and alignment of type.
1580 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1587 if (Subtarget->hasSSE1())
1588 getMaxByValAlign(Ty, Align);
1592 /// getOptimalMemOpType - Returns the target specific optimal type for load
1593 /// and store operations as a result of memset, memcpy, and memmove
1594 /// lowering. If DstAlign is zero that means it's safe to destination
1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1596 /// means there isn't a need to check it against alignment requirement,
1597 /// probably because the source does not need to be loaded. If 'IsMemset' is
1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1600 /// source is constant so it does not need to be loaded.
1601 /// It returns EVT::Other if the type should be determined using generic
1602 /// target-independent logic.
1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1605 unsigned DstAlign, unsigned SrcAlign,
1606 bool IsMemset, bool ZeroMemset,
1608 MachineFunction &MF) const {
1609 const Function *F = MF.getFunction();
1610 if ((!IsMemset || ZeroMemset) &&
1611 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1612 Attribute::NoImplicitFloat)) {
1614 (Subtarget->isUnalignedMemAccessFast() ||
1615 ((DstAlign == 0 || DstAlign >= 16) &&
1616 (SrcAlign == 0 || SrcAlign >= 16)))) {
1618 if (Subtarget->hasInt256())
1620 if (Subtarget->hasFp256())
1623 if (Subtarget->hasSSE2())
1625 if (Subtarget->hasSSE1())
1627 } else if (!MemcpyStrSrc && Size >= 8 &&
1628 !Subtarget->is64Bit() &&
1629 Subtarget->hasSSE2()) {
1630 // Do not use f64 to lower memcpy if source is string constant. It's
1631 // better to use i32 to avoid the loads.
1635 if (Subtarget->is64Bit() && Size >= 8)
1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1642 return X86ScalarSSEf32;
1643 else if (VT == MVT::f64)
1644 return X86ScalarSSEf64;
1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1651 *Fast = Subtarget->isUnalignedMemAccessFast();
1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1656 /// current function. The returned value is a member of the
1657 /// MachineJumpTableInfo::JTEntryKind enum.
1658 unsigned X86TargetLowering::getJumpTableEncoding() const {
1659 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1661 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662 Subtarget->isPICStyleGOT())
1663 return MachineJumpTableInfo::EK_Custom32;
1665 // Otherwise, use the normal jump table encoding heuristics.
1666 return TargetLowering::getJumpTableEncoding();
1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1671 const MachineBasicBlock *MBB,
1672 unsigned uid,MCContext &Ctx) const{
1673 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1674 Subtarget->isPICStyleGOT());
1675 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1677 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1678 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1684 SelectionDAG &DAG) const {
1685 if (!Subtarget->is64Bit())
1686 // This doesn't have SDLoc associated with it, but is not really the
1687 // same as a Register.
1688 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1695 const MCExpr *X86TargetLowering::
1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1697 MCContext &Ctx) const {
1698 // X86-64 uses RIP relative addressing based on the jump table label.
1699 if (Subtarget->isPICStyleRIPRel())
1700 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1702 // Otherwise, the reference is relative to the PIC base.
1703 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1706 // FIXME: Why this routine is here? Move to RegInfo!
1707 std::pair<const TargetRegisterClass*, uint8_t>
1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1709 const TargetRegisterClass *RRC = 0;
1711 switch (VT.SimpleTy) {
1713 return TargetLowering::findRepresentativeClass(VT);
1714 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1715 RRC = Subtarget->is64Bit() ?
1716 (const TargetRegisterClass*)&X86::GR64RegClass :
1717 (const TargetRegisterClass*)&X86::GR32RegClass;
1720 RRC = &X86::VR64RegClass;
1722 case MVT::f32: case MVT::f64:
1723 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1724 case MVT::v4f32: case MVT::v2f64:
1725 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1727 RRC = &X86::VR128RegClass;
1730 return std::make_pair(RRC, Cost);
1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1734 unsigned &Offset) const {
1735 if (!Subtarget->isTargetLinux())
1738 if (Subtarget->is64Bit()) {
1739 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1741 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1753 //===----------------------------------------------------------------------===//
1754 // Return Value Calling Convention Implementation
1755 //===----------------------------------------------------------------------===//
1757 #include "X86GenCallingConv.inc"
1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1761 MachineFunction &MF, bool isVarArg,
1762 const SmallVectorImpl<ISD::OutputArg> &Outs,
1763 LLVMContext &Context) const {
1764 SmallVector<CCValAssign, 16> RVLocs;
1765 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1767 return CCInfo.CheckReturn(Outs, RetCC_X86);
1771 X86TargetLowering::LowerReturn(SDValue Chain,
1772 CallingConv::ID CallConv, bool isVarArg,
1773 const SmallVectorImpl<ISD::OutputArg> &Outs,
1774 const SmallVectorImpl<SDValue> &OutVals,
1775 SDLoc dl, SelectionDAG &DAG) const {
1776 MachineFunction &MF = DAG.getMachineFunction();
1777 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1779 SmallVector<CCValAssign, 16> RVLocs;
1780 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1781 RVLocs, *DAG.getContext());
1782 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1785 SmallVector<SDValue, 6> RetOps;
1786 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1787 // Operand #1 = Bytes To Pop
1788 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1791 // Copy the result values into the output registers.
1792 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1793 CCValAssign &VA = RVLocs[i];
1794 assert(VA.isRegLoc() && "Can only return in registers!");
1795 SDValue ValToCopy = OutVals[i];
1796 EVT ValVT = ValToCopy.getValueType();
1798 // Promote values to the appropriate types
1799 if (VA.getLocInfo() == CCValAssign::SExt)
1800 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801 else if (VA.getLocInfo() == CCValAssign::ZExt)
1802 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803 else if (VA.getLocInfo() == CCValAssign::AExt)
1804 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1805 else if (VA.getLocInfo() == CCValAssign::BCvt)
1806 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1808 // If this is x86-64, and we disabled SSE, we can't return FP values,
1809 // or SSE or MMX vectors.
1810 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1811 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1812 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1813 report_fatal_error("SSE register return with SSE disabled");
1815 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1816 // llvm-gcc has never done it right and no one has noticed, so this
1817 // should be OK for now.
1818 if (ValVT == MVT::f64 &&
1819 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1820 report_fatal_error("SSE2 register return with SSE2 disabled");
1822 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1823 // the RET instruction and handled by the FP Stackifier.
1824 if (VA.getLocReg() == X86::ST0 ||
1825 VA.getLocReg() == X86::ST1) {
1826 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1827 // change the value to the FP stack register class.
1828 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1829 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1830 RetOps.push_back(ValToCopy);
1831 // Don't emit a copytoreg.
1835 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1836 // which is returned in RAX / RDX.
1837 if (Subtarget->is64Bit()) {
1838 if (ValVT == MVT::x86mmx) {
1839 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1840 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1841 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1843 // If we don't have SSE2 available, convert to v4f32 so the generated
1844 // register is legal.
1845 if (!Subtarget->hasSSE2())
1846 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1851 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1852 Flag = Chain.getValue(1);
1853 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1856 // The x86-64 ABIs require that for returning structs by value we copy
1857 // the sret argument into %rax/%eax (depending on ABI) for the return.
1858 // Win32 requires us to put the sret argument to %eax as well.
1859 // We saved the argument into a virtual register in the entry block,
1860 // so now we copy the value out and into %rax/%eax.
1861 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1862 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1863 MachineFunction &MF = DAG.getMachineFunction();
1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865 unsigned Reg = FuncInfo->getSRetReturnReg();
1867 "SRetReturnReg should have been set in LowerFormalArguments().");
1868 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1871 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1872 X86::RAX : X86::EAX;
1873 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1874 Flag = Chain.getValue(1);
1876 // RAX/EAX now acts like a return value.
1877 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1880 RetOps[0] = Chain; // Update chain.
1882 // Add the flag if we have it.
1884 RetOps.push_back(Flag);
1886 return DAG.getNode(X86ISD::RET_FLAG, dl,
1887 MVT::Other, &RetOps[0], RetOps.size());
1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1891 if (N->getNumValues() != 1)
1893 if (!N->hasNUsesOfValue(1, 0))
1896 SDValue TCChain = Chain;
1897 SDNode *Copy = *N->use_begin();
1898 if (Copy->getOpcode() == ISD::CopyToReg) {
1899 // If the copy has a glue operand, we conservatively assume it isn't safe to
1900 // perform a tail call.
1901 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1903 TCChain = Copy->getOperand(0);
1904 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1907 bool HasRet = false;
1908 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1910 if (UI->getOpcode() != X86ISD::RET_FLAG)
1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1924 ISD::NodeType ExtendKind) const {
1926 // TODO: Is this also valid on 32-bit?
1927 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1928 ReturnMVT = MVT::i8;
1930 ReturnMVT = MVT::i32;
1932 MVT MinVT = getRegisterType(ReturnMVT);
1933 return VT.bitsLT(MinVT) ? MinVT : VT;
1936 /// LowerCallResult - Lower the result values of a call into the
1937 /// appropriate copies out of appropriate physical registers.
1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1941 CallingConv::ID CallConv, bool isVarArg,
1942 const SmallVectorImpl<ISD::InputArg> &Ins,
1943 SDLoc dl, SelectionDAG &DAG,
1944 SmallVectorImpl<SDValue> &InVals) const {
1946 // Assign locations to each value returned by this call.
1947 SmallVector<CCValAssign, 16> RVLocs;
1948 bool Is64Bit = Subtarget->is64Bit();
1949 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1950 getTargetMachine(), RVLocs, *DAG.getContext());
1951 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1953 // Copy all of the result registers out of their specified physreg.
1954 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1955 CCValAssign &VA = RVLocs[i];
1956 EVT CopyVT = VA.getValVT();
1958 // If this is x86-64, and we disabled SSE, we can't return FP values
1959 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1960 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1961 report_fatal_error("SSE register return with SSE disabled");
1966 // If this is a call to a function that returns an fp value on the floating
1967 // point stack, we must guarantee the value is popped from the stack, so
1968 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1969 // if the return value is not used. We use the FpPOP_RETVAL instruction
1971 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1972 // If we prefer to use the value in xmm registers, copy it out as f80 and
1973 // use a truncate to move it from fp stack reg to xmm reg.
1974 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1975 SDValue Ops[] = { Chain, InFlag };
1976 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1977 MVT::Other, MVT::Glue, Ops), 1);
1978 Val = Chain.getValue(0);
1980 // Round the f80 to the right size, which also moves it to the appropriate
1982 if (CopyVT != VA.getValVT())
1983 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1984 // This truncation won't change the value.
1985 DAG.getIntPtrConstant(1));
1987 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1988 CopyVT, InFlag).getValue(1);
1989 Val = Chain.getValue(0);
1991 InFlag = Chain.getValue(2);
1992 InVals.push_back(Val);
1998 //===----------------------------------------------------------------------===//
1999 // C & StdCall & Fast Calling Convention implementation
2000 //===----------------------------------------------------------------------===//
2001 // StdCall calling convention seems to be standard for many Windows' API
2002 // routines and around. It differs from C calling convention just a little:
2003 // callee should clean up the stack, not caller. Symbols should be also
2004 // decorated in some fancy way :) It doesn't support any vector arguments.
2005 // For info on fast calling convention see Fast Calling Convention (tail call)
2006 // implementation LowerX86_32FastCCCallTo.
2008 /// CallIsStructReturn - Determines whether a call uses struct return
2010 enum StructReturnType {
2015 static StructReturnType
2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2018 return NotStructReturn;
2020 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2021 if (!Flags.isSRet())
2022 return NotStructReturn;
2023 if (Flags.isInReg())
2024 return RegStructReturn;
2025 return StackStructReturn;
2028 /// ArgsAreStructReturn - Determines whether a function uses struct
2029 /// return semantics.
2030 static StructReturnType
2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2033 return NotStructReturn;
2035 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2036 if (!Flags.isSRet())
2037 return NotStructReturn;
2038 if (Flags.isInReg())
2039 return RegStructReturn;
2040 return StackStructReturn;
2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2044 /// by "Src" to address "Dst" with size and alignment information specified by
2045 /// the specific parameter attribute. The copy will be passed as a byval
2046 /// function parameter.
2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2049 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2051 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2053 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2054 /*isVolatile*/false, /*AlwaysInline=*/true,
2055 MachinePointerInfo(), MachinePointerInfo());
2058 /// IsTailCallConvention - Return true if the calling convention is one that
2059 /// supports tail call optimization.
2060 static bool IsTailCallConvention(CallingConv::ID CC) {
2061 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2062 CC == CallingConv::HiPE);
2065 /// \brief Return true if the calling convention is a C calling convention.
2066 static bool IsCCallConvention(CallingConv::ID CC) {
2067 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2068 CC == CallingConv::X86_64_SysV);
2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2072 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2076 CallingConv::ID CalleeCC = CS.getCallingConv();
2077 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2084 /// a tailcall target by changing its ABI.
2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2086 bool GuaranteedTailCallOpt) {
2087 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2091 X86TargetLowering::LowerMemArgument(SDValue Chain,
2092 CallingConv::ID CallConv,
2093 const SmallVectorImpl<ISD::InputArg> &Ins,
2094 SDLoc dl, SelectionDAG &DAG,
2095 const CCValAssign &VA,
2096 MachineFrameInfo *MFI,
2098 // Create the nodes corresponding to a load from this parameter slot.
2099 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2100 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2101 getTargetMachine().Options.GuaranteedTailCallOpt);
2102 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2105 // If value is passed by pointer we have address passed instead of the value
2107 if (VA.getLocInfo() == CCValAssign::Indirect)
2108 ValVT = VA.getLocVT();
2110 ValVT = VA.getValVT();
2112 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2113 // changed with more analysis.
2114 // In case of tail call optimization mark all arguments mutable. Since they
2115 // could be overwritten by lowering of arguments in case of a tail call.
2116 if (Flags.isByVal()) {
2117 unsigned Bytes = Flags.getByValSize();
2118 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2119 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2120 return DAG.getFrameIndex(FI, getPointerTy());
2122 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2123 VA.getLocMemOffset(), isImmutable);
2124 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2125 return DAG.getLoad(ValVT, dl, Chain, FIN,
2126 MachinePointerInfo::getFixedStack(FI),
2127 false, false, false, 0);
2132 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2133 CallingConv::ID CallConv,
2135 const SmallVectorImpl<ISD::InputArg> &Ins,
2138 SmallVectorImpl<SDValue> &InVals)
2140 MachineFunction &MF = DAG.getMachineFunction();
2141 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2143 const Function* Fn = MF.getFunction();
2144 if (Fn->hasExternalLinkage() &&
2145 Subtarget->isTargetCygMing() &&
2146 Fn->getName() == "main")
2147 FuncInfo->setForceFramePointer(true);
2149 MachineFrameInfo *MFI = MF.getFrameInfo();
2150 bool Is64Bit = Subtarget->is64Bit();
2151 bool IsWindows = Subtarget->isTargetWindows();
2152 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2154 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2155 "Var args not supported with calling convention fastcc, ghc or hipe");
2157 // Assign locations to all of the incoming arguments.
2158 SmallVector<CCValAssign, 16> ArgLocs;
2159 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2160 ArgLocs, *DAG.getContext());
2162 // Allocate shadow area for Win64
2164 CCInfo.AllocateStack(32, 8);
2166 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2168 unsigned LastVal = ~0U;
2170 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171 CCValAssign &VA = ArgLocs[i];
2172 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2174 assert(VA.getValNo() != LastVal &&
2175 "Don't support value assigned to multiple locs yet");
2177 LastVal = VA.getValNo();
2179 if (VA.isRegLoc()) {
2180 EVT RegVT = VA.getLocVT();
2181 const TargetRegisterClass *RC;
2182 if (RegVT == MVT::i32)
2183 RC = &X86::GR32RegClass;
2184 else if (Is64Bit && RegVT == MVT::i64)
2185 RC = &X86::GR64RegClass;
2186 else if (RegVT == MVT::f32)
2187 RC = &X86::FR32RegClass;
2188 else if (RegVT == MVT::f64)
2189 RC = &X86::FR64RegClass;
2190 else if (RegVT.is512BitVector())
2191 RC = &X86::VR512RegClass;
2192 else if (RegVT.is256BitVector())
2193 RC = &X86::VR256RegClass;
2194 else if (RegVT.is128BitVector())
2195 RC = &X86::VR128RegClass;
2196 else if (RegVT == MVT::x86mmx)
2197 RC = &X86::VR64RegClass;
2198 else if (RegVT == MVT::v8i1)
2199 RC = &X86::VK8RegClass;
2200 else if (RegVT == MVT::v16i1)
2201 RC = &X86::VK16RegClass;
2203 llvm_unreachable("Unknown argument type!");
2205 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2206 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2208 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2209 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2211 if (VA.getLocInfo() == CCValAssign::SExt)
2212 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2213 DAG.getValueType(VA.getValVT()));
2214 else if (VA.getLocInfo() == CCValAssign::ZExt)
2215 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2216 DAG.getValueType(VA.getValVT()));
2217 else if (VA.getLocInfo() == CCValAssign::BCvt)
2218 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2220 if (VA.isExtInLoc()) {
2221 // Handle MMX values passed in XMM regs.
2222 if (RegVT.isVector())
2223 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2225 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2228 assert(VA.isMemLoc());
2229 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2232 // If value is passed via pointer - do a load.
2233 if (VA.getLocInfo() == CCValAssign::Indirect)
2234 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2235 MachinePointerInfo(), false, false, false, 0);
2237 InVals.push_back(ArgValue);
2240 // The x86-64 ABIs require that for returning structs by value we copy
2241 // the sret argument into %rax/%eax (depending on ABI) for the return.
2242 // Win32 requires us to put the sret argument to %eax as well.
2243 // Save the argument into a virtual register so that we can access it
2244 // from the return points.
2245 if (MF.getFunction()->hasStructRetAttr() &&
2246 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2247 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2248 unsigned Reg = FuncInfo->getSRetReturnReg();
2250 MVT PtrTy = getPointerTy();
2251 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2252 FuncInfo->setSRetReturnReg(Reg);
2254 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2255 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2258 unsigned StackSize = CCInfo.getNextStackOffset();
2259 // Align stack specially for tail calls.
2260 if (FuncIsMadeTailCallSafe(CallConv,
2261 MF.getTarget().Options.GuaranteedTailCallOpt))
2262 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2264 // If the function takes variable number of arguments, make a frame index for
2265 // the start of the first vararg value... for expansion of llvm.va_start.
2267 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2268 CallConv != CallingConv::X86_ThisCall)) {
2269 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2272 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2274 // FIXME: We should really autogenerate these arrays
2275 static const uint16_t GPR64ArgRegsWin64[] = {
2276 X86::RCX, X86::RDX, X86::R8, X86::R9
2278 static const uint16_t GPR64ArgRegs64Bit[] = {
2279 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2281 static const uint16_t XMMArgRegs64Bit[] = {
2282 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2283 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2285 const uint16_t *GPR64ArgRegs;
2286 unsigned NumXMMRegs = 0;
2289 // The XMM registers which might contain var arg parameters are shadowed
2290 // in their paired GPR. So we only need to save the GPR to their home
2292 TotalNumIntRegs = 4;
2293 GPR64ArgRegs = GPR64ArgRegsWin64;
2295 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2296 GPR64ArgRegs = GPR64ArgRegs64Bit;
2298 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2301 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2304 bool NoImplicitFloatOps = Fn->getAttributes().
2305 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2306 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2307 "SSE register cannot be used when SSE is disabled!");
2308 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2309 NoImplicitFloatOps) &&
2310 "SSE register cannot be used when SSE is disabled!");
2311 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2312 !Subtarget->hasSSE1())
2313 // Kernel mode asks for SSE to be disabled, so don't push them
2315 TotalNumXMMRegs = 0;
2318 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2319 // Get to the caller-allocated home save location. Add 8 to account
2320 // for the return address.
2321 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2322 FuncInfo->setRegSaveFrameIndex(
2323 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2324 // Fixup to set vararg frame on shadow area (4 x i64).
2326 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2328 // For X86-64, if there are vararg parameters that are passed via
2329 // registers, then we must store them to their spots on the stack so
2330 // they may be loaded by deferencing the result of va_next.
2331 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2332 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2333 FuncInfo->setRegSaveFrameIndex(
2334 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2338 // Store the integer parameter registers.
2339 SmallVector<SDValue, 8> MemOps;
2340 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2342 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2343 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2344 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2345 DAG.getIntPtrConstant(Offset));
2346 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2347 &X86::GR64RegClass);
2348 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2350 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351 MachinePointerInfo::getFixedStack(
2352 FuncInfo->getRegSaveFrameIndex(), Offset),
2354 MemOps.push_back(Store);
2358 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2359 // Now store the XMM (fp + vector) parameter registers.
2360 SmallVector<SDValue, 11> SaveXMMOps;
2361 SaveXMMOps.push_back(Chain);
2363 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2364 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2365 SaveXMMOps.push_back(ALVal);
2367 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368 FuncInfo->getRegSaveFrameIndex()));
2369 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2370 FuncInfo->getVarArgsFPOffset()));
2372 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2373 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2374 &X86::VR128RegClass);
2375 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2376 SaveXMMOps.push_back(Val);
2378 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2380 &SaveXMMOps[0], SaveXMMOps.size()));
2383 if (!MemOps.empty())
2384 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2385 &MemOps[0], MemOps.size());
2389 // Some CCs need callee pop.
2390 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2391 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2392 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2394 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2395 // If this is an sret function, the return should pop the hidden pointer.
2396 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2397 argsAreStructReturn(Ins) == StackStructReturn)
2398 FuncInfo->setBytesToPopOnReturn(4);
2402 // RegSaveFrameIndex is X86-64 only.
2403 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2404 if (CallConv == CallingConv::X86_FastCall ||
2405 CallConv == CallingConv::X86_ThisCall)
2406 // fastcc functions can't have varargs.
2407 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2410 FuncInfo->setArgumentStackSize(StackSize);
2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2417 SDValue StackPtr, SDValue Arg,
2418 SDLoc dl, SelectionDAG &DAG,
2419 const CCValAssign &VA,
2420 ISD::ArgFlagsTy Flags) const {
2421 unsigned LocMemOffset = VA.getLocMemOffset();
2422 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2423 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2424 if (Flags.isByVal())
2425 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2427 return DAG.getStore(Chain, dl, Arg, PtrOff,
2428 MachinePointerInfo::getStack(LocMemOffset),
2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2433 /// optimization is performed and it is required.
2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2436 SDValue &OutRetAddr, SDValue Chain,
2437 bool IsTailCall, bool Is64Bit,
2438 int FPDiff, SDLoc dl) const {
2439 // Adjust the Return address stack slot.
2440 EVT VT = getPointerTy();
2441 OutRetAddr = getReturnAddressFrameIndex(DAG);
2443 // Load the "old" Return address.
2444 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2445 false, false, false, 0);
2446 return SDValue(OutRetAddr.getNode(), 1);
2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2450 /// optimization is performed and it is required (FPDiff!=0).
2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2453 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2454 unsigned SlotSize, int FPDiff, SDLoc dl) {
2455 // Store the return address to the appropriate stack slot.
2456 if (!FPDiff) return Chain;
2457 // Calculate the new stack slot for the return address.
2458 int NewReturnAddrFI =
2459 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2461 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2462 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2463 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2470 SmallVectorImpl<SDValue> &InVals) const {
2471 SelectionDAG &DAG = CLI.DAG;
2473 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2474 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2475 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2476 SDValue Chain = CLI.Chain;
2477 SDValue Callee = CLI.Callee;
2478 CallingConv::ID CallConv = CLI.CallConv;
2479 bool &isTailCall = CLI.IsTailCall;
2480 bool isVarArg = CLI.IsVarArg;
2482 MachineFunction &MF = DAG.getMachineFunction();
2483 bool Is64Bit = Subtarget->is64Bit();
2484 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2485 bool IsWindows = Subtarget->isTargetWindows();
2486 StructReturnType SR = callIsStructReturn(Outs);
2487 bool IsSibcall = false;
2489 if (MF.getTarget().Options.DisableTailCalls)
2493 // Check if it's really possible to do a tail call.
2494 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2495 isVarArg, SR != NotStructReturn,
2496 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2497 Outs, OutVals, Ins, DAG);
2499 // Sibcalls are automatically detected tailcalls which do not require
2501 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2508 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509 "Var args not supported with calling convention fastcc, ghc or hipe");
2511 // Analyze operands of the call, assigning locations to each operand.
2512 SmallVector<CCValAssign, 16> ArgLocs;
2513 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2514 ArgLocs, *DAG.getContext());
2516 // Allocate shadow area for Win64
2518 CCInfo.AllocateStack(32, 8);
2520 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2522 // Get a count of how many bytes are to be pushed on the stack.
2523 unsigned NumBytes = CCInfo.getNextStackOffset();
2525 // This is a sibcall. The memory operands are available in caller's
2526 // own caller's stack.
2528 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2529 IsTailCallConvention(CallConv))
2530 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2533 if (isTailCall && !IsSibcall) {
2534 // Lower arguments at fp - stackoffset + fpdiff.
2535 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2536 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2538 FPDiff = NumBytesCallerPushed - NumBytes;
2540 // Set the delta of movement of the returnaddr stackslot.
2541 // But only set if delta is greater than previous delta.
2542 if (FPDiff < X86Info->getTCReturnAddrDelta())
2543 X86Info->setTCReturnAddrDelta(FPDiff);
2547 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2550 SDValue RetAddrFrIdx;
2551 // Load return address for tail calls.
2552 if (isTailCall && FPDiff)
2553 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2554 Is64Bit, FPDiff, dl);
2556 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2557 SmallVector<SDValue, 8> MemOpChains;
2560 // Walk the register/memloc assignments, inserting copies/loads. In the case
2561 // of tail call optimization arguments are handle later.
2562 const X86RegisterInfo *RegInfo =
2563 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2564 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2565 CCValAssign &VA = ArgLocs[i];
2566 EVT RegVT = VA.getLocVT();
2567 SDValue Arg = OutVals[i];
2568 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2569 bool isByVal = Flags.isByVal();
2571 // Promote the value if needed.
2572 switch (VA.getLocInfo()) {
2573 default: llvm_unreachable("Unknown loc info!");
2574 case CCValAssign::Full: break;
2575 case CCValAssign::SExt:
2576 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2578 case CCValAssign::ZExt:
2579 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2581 case CCValAssign::AExt:
2582 if (RegVT.is128BitVector()) {
2583 // Special case: passing MMX values in XMM registers.
2584 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2585 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2586 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2588 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2590 case CCValAssign::BCvt:
2591 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2593 case CCValAssign::Indirect: {
2594 // Store the argument.
2595 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2596 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2597 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2598 MachinePointerInfo::getFixedStack(FI),
2605 if (VA.isRegLoc()) {
2606 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2607 if (isVarArg && IsWin64) {
2608 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2609 // shadow reg if callee is a varargs function.
2610 unsigned ShadowReg = 0;
2611 switch (VA.getLocReg()) {
2612 case X86::XMM0: ShadowReg = X86::RCX; break;
2613 case X86::XMM1: ShadowReg = X86::RDX; break;
2614 case X86::XMM2: ShadowReg = X86::R8; break;
2615 case X86::XMM3: ShadowReg = X86::R9; break;
2618 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2620 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2621 assert(VA.isMemLoc());
2622 if (StackPtr.getNode() == 0)
2623 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2625 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2626 dl, DAG, VA, Flags));
2630 if (!MemOpChains.empty())
2631 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2632 &MemOpChains[0], MemOpChains.size());
2634 if (Subtarget->isPICStyleGOT()) {
2635 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2638 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2639 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2641 // If we are tail calling and generating PIC/GOT style code load the
2642 // address of the callee into ECX. The value in ecx is used as target of
2643 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2644 // for tail calls on PIC/GOT architectures. Normally we would just put the
2645 // address of GOT into ebx and then call target@PLT. But for tail calls
2646 // ebx would be restored (since ebx is callee saved) before jumping to the
2649 // Note: The actual moving to ECX is done further down.
2650 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2651 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2652 !G->getGlobal()->hasProtectedVisibility())
2653 Callee = LowerGlobalAddress(Callee, DAG);
2654 else if (isa<ExternalSymbolSDNode>(Callee))
2655 Callee = LowerExternalSymbol(Callee, DAG);
2659 if (Is64Bit && isVarArg && !IsWin64) {
2660 // From AMD64 ABI document:
2661 // For calls that may call functions that use varargs or stdargs
2662 // (prototype-less calls or calls to functions containing ellipsis (...) in
2663 // the declaration) %al is used as hidden argument to specify the number
2664 // of SSE registers used. The contents of %al do not need to match exactly
2665 // the number of registers, but must be an ubound on the number of SSE
2666 // registers used and is in the range 0 - 8 inclusive.
2668 // Count the number of XMM registers allocated.
2669 static const uint16_t XMMArgRegs[] = {
2670 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2671 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2673 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2674 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2675 && "SSE registers cannot be used when SSE is disabled");
2677 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2678 DAG.getConstant(NumXMMRegs, MVT::i8)));
2681 // For tail calls lower the arguments to the 'real' stack slot.
2683 // Force all the incoming stack arguments to be loaded from the stack
2684 // before any new outgoing arguments are stored to the stack, because the
2685 // outgoing stack slots may alias the incoming argument stack slots, and
2686 // the alias isn't otherwise explicit. This is slightly more conservative
2687 // than necessary, because it means that each store effectively depends
2688 // on every argument instead of just those arguments it would clobber.
2689 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2691 SmallVector<SDValue, 8> MemOpChains2;
2694 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2695 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696 CCValAssign &VA = ArgLocs[i];
2699 assert(VA.isMemLoc());
2700 SDValue Arg = OutVals[i];
2701 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2702 // Create frame index.
2703 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2704 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2705 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2706 FIN = DAG.getFrameIndex(FI, getPointerTy());
2708 if (Flags.isByVal()) {
2709 // Copy relative to framepointer.
2710 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2711 if (StackPtr.getNode() == 0)
2712 StackPtr = DAG.getCopyFromReg(Chain, dl,
2713 RegInfo->getStackRegister(),
2715 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2717 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2721 // Store relative to framepointer.
2722 MemOpChains2.push_back(
2723 DAG.getStore(ArgChain, dl, Arg, FIN,
2724 MachinePointerInfo::getFixedStack(FI),
2730 if (!MemOpChains2.empty())
2731 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2732 &MemOpChains2[0], MemOpChains2.size());
2734 // Store the return address to the appropriate stack slot.
2735 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2736 getPointerTy(), RegInfo->getSlotSize(),
2740 // Build a sequence of copy-to-reg nodes chained together with token chain
2741 // and flag operands which copy the outgoing args into registers.
2743 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2745 RegsToPass[i].second, InFlag);
2746 InFlag = Chain.getValue(1);
2749 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2750 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2751 // In the 64-bit large code model, we have to make all calls
2752 // through a register, since the call instruction's 32-bit
2753 // pc-relative offset may not be large enough to hold the whole
2755 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2756 // If the callee is a GlobalAddress node (quite common, every direct call
2757 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2760 // We should use extra load for direct calls to dllimported functions in
2762 const GlobalValue *GV = G->getGlobal();
2763 if (!GV->hasDLLImportLinkage()) {
2764 unsigned char OpFlags = 0;
2765 bool ExtraLoad = false;
2766 unsigned WrapperKind = ISD::DELETED_NODE;
2768 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2769 // external symbols most go through the PLT in PIC mode. If the symbol
2770 // has hidden or protected visibility, or if it is static or local, then
2771 // we don't need to use the PLT - we can directly call it.
2772 if (Subtarget->isTargetELF() &&
2773 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2774 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2775 OpFlags = X86II::MO_PLT;
2776 } else if (Subtarget->isPICStyleStubAny() &&
2777 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2778 (!Subtarget->getTargetTriple().isMacOSX() ||
2779 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2780 // PC-relative references to external symbols should go through $stub,
2781 // unless we're building with the leopard linker or later, which
2782 // automatically synthesizes these stubs.
2783 OpFlags = X86II::MO_DARWIN_STUB;
2784 } else if (Subtarget->isPICStyleRIPRel() &&
2785 isa<Function>(GV) &&
2786 cast<Function>(GV)->getAttributes().
2787 hasAttribute(AttributeSet::FunctionIndex,
2788 Attribute::NonLazyBind)) {
2789 // If the function is marked as non-lazy, generate an indirect call
2790 // which loads from the GOT directly. This avoids runtime overhead
2791 // at the cost of eager binding (and one extra byte of encoding).
2792 OpFlags = X86II::MO_GOTPCREL;
2793 WrapperKind = X86ISD::WrapperRIP;
2797 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2798 G->getOffset(), OpFlags);
2800 // Add a wrapper if needed.
2801 if (WrapperKind != ISD::DELETED_NODE)
2802 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2803 // Add extra indirection if needed.
2805 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2806 MachinePointerInfo::getGOT(),
2807 false, false, false, 0);
2809 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2810 unsigned char OpFlags = 0;
2812 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2813 // external symbols should go through the PLT.
2814 if (Subtarget->isTargetELF() &&
2815 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2816 OpFlags = X86II::MO_PLT;
2817 } else if (Subtarget->isPICStyleStubAny() &&
2818 (!Subtarget->getTargetTriple().isMacOSX() ||
2819 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2820 // PC-relative references to external symbols should go through $stub,
2821 // unless we're building with the leopard linker or later, which
2822 // automatically synthesizes these stubs.
2823 OpFlags = X86II::MO_DARWIN_STUB;
2826 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2830 // Returns a chain & a flag for retval copy to use.
2831 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2832 SmallVector<SDValue, 8> Ops;
2834 if (!IsSibcall && isTailCall) {
2835 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2836 DAG.getIntPtrConstant(0, true), InFlag, dl);
2837 InFlag = Chain.getValue(1);
2840 Ops.push_back(Chain);
2841 Ops.push_back(Callee);
2844 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2846 // Add argument registers to the end of the list so that they are known live
2848 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2849 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2850 RegsToPass[i].second.getValueType()));
2852 // Add a register mask operand representing the call-preserved registers.
2853 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2854 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2855 assert(Mask && "Missing call preserved mask for calling convention");
2856 Ops.push_back(DAG.getRegisterMask(Mask));
2858 if (InFlag.getNode())
2859 Ops.push_back(InFlag);
2863 //// If this is the first return lowered for this function, add the regs
2864 //// to the liveout set for the function.
2865 // This isn't right, although it's probably harmless on x86; liveouts
2866 // should be computed from returns not tail calls. Consider a void
2867 // function making a tail call to a function returning int.
2868 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2871 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2872 InFlag = Chain.getValue(1);
2874 // Create the CALLSEQ_END node.
2875 unsigned NumBytesForCalleeToPush;
2876 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2877 getTargetMachine().Options.GuaranteedTailCallOpt))
2878 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2879 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2880 SR == StackStructReturn)
2881 // If this is a call to a struct-return function, the callee
2882 // pops the hidden struct pointer, so we have to push it back.
2883 // This is common for Darwin/X86, Linux & Mingw32 targets.
2884 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2885 NumBytesForCalleeToPush = 4;
2887 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2889 // Returns a flag for retval copy to use.
2891 Chain = DAG.getCALLSEQ_END(Chain,
2892 DAG.getIntPtrConstant(NumBytes, true),
2893 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2896 InFlag = Chain.getValue(1);
2899 // Handle result values, copying them out of physregs into vregs that we
2901 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902 Ins, dl, DAG, InVals);
2905 //===----------------------------------------------------------------------===//
2906 // Fast Calling Convention (tail call) implementation
2907 //===----------------------------------------------------------------------===//
2909 // Like std call, callee cleans arguments, convention except that ECX is
2910 // reserved for storing the tail called function address. Only 2 registers are
2911 // free for argument passing (inreg). Tail call optimization is performed
2913 // * tailcallopt is enabled
2914 // * caller/callee are fastcc
2915 // On X86_64 architecture with GOT-style position independent code only local
2916 // (within module) calls are supported at the moment.
2917 // To keep the stack aligned according to platform abi the function
2918 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2919 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2920 // If a tail called function callee has more arguments than the caller the
2921 // caller needs to make sure that there is room to move the RETADDR to. This is
2922 // achieved by reserving an area the size of the argument delta right after the
2923 // original REtADDR, but before the saved framepointer or the spilled registers
2924 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2937 /// for a 16 byte align requirement.
2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2940 SelectionDAG& DAG) const {
2941 MachineFunction &MF = DAG.getMachineFunction();
2942 const TargetMachine &TM = MF.getTarget();
2943 const X86RegisterInfo *RegInfo =
2944 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2945 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2946 unsigned StackAlignment = TFI.getStackAlignment();
2947 uint64_t AlignMask = StackAlignment - 1;
2948 int64_t Offset = StackSize;
2949 unsigned SlotSize = RegInfo->getSlotSize();
2950 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2951 // Number smaller than 12 so just add the difference.
2952 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2954 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2955 Offset = ((~AlignMask) & Offset) + StackAlignment +
2956 (StackAlignment-SlotSize);
2961 /// MatchingStackOffset - Return true if the given stack call argument is
2962 /// already available in the same position (relatively) of the caller's
2963 /// incoming argument stack.
2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2966 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2967 const X86InstrInfo *TII) {
2968 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2970 if (Arg.getOpcode() == ISD::CopyFromReg) {
2971 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2972 if (!TargetRegisterInfo::isVirtualRegister(VR))
2974 MachineInstr *Def = MRI->getVRegDef(VR);
2977 if (!Flags.isByVal()) {
2978 if (!TII->isLoadFromStackSlot(Def, FI))
2981 unsigned Opcode = Def->getOpcode();
2982 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2983 Def->getOperand(1).isFI()) {
2984 FI = Def->getOperand(1).getIndex();
2985 Bytes = Flags.getByValSize();
2989 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2990 if (Flags.isByVal())
2991 // ByVal argument is passed in as a pointer but it's now being
2992 // dereferenced. e.g.
2993 // define @foo(%struct.X* %A) {
2994 // tail call @bar(%struct.X* byval %A)
2997 SDValue Ptr = Ld->getBasePtr();
2998 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3001 FI = FINode->getIndex();
3002 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3003 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3004 FI = FINode->getIndex();
3005 Bytes = Flags.getByValSize();
3009 assert(FI != INT_MAX);
3010 if (!MFI->isFixedObjectIndex(FI))
3012 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3016 /// for tail call optimization. Targets which want to do tail call
3017 /// optimization should implement this function.
3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3020 CallingConv::ID CalleeCC,
3022 bool isCalleeStructRet,
3023 bool isCallerStructRet,
3025 const SmallVectorImpl<ISD::OutputArg> &Outs,
3026 const SmallVectorImpl<SDValue> &OutVals,
3027 const SmallVectorImpl<ISD::InputArg> &Ins,
3028 SelectionDAG &DAG) const {
3029 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3032 // If -tailcallopt is specified, make fastcc functions tail-callable.
3033 const MachineFunction &MF = DAG.getMachineFunction();
3034 const Function *CallerF = MF.getFunction();
3036 // If the function return type is x86_fp80 and the callee return type is not,
3037 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3038 // perform a tailcall optimization here.
3039 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3042 CallingConv::ID CallerCC = CallerF->getCallingConv();
3043 bool CCMatch = CallerCC == CalleeCC;
3044 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3045 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3047 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3048 if (IsTailCallConvention(CalleeCC) && CCMatch)
3053 // Look for obvious safe cases to perform tail call optimization that do not
3054 // require ABI changes. This is what gcc calls sibcall.
3056 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3057 // emit a special epilogue.
3058 const X86RegisterInfo *RegInfo =
3059 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3060 if (RegInfo->needsStackRealignment(MF))
3063 // Also avoid sibcall optimization if either caller or callee uses struct
3064 // return semantics.
3065 if (isCalleeStructRet || isCallerStructRet)
3068 // An stdcall caller is expected to clean up its arguments; the callee
3069 // isn't going to do that.
3070 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3073 // Do not sibcall optimize vararg calls unless all arguments are passed via
3075 if (isVarArg && !Outs.empty()) {
3077 // Optimizing for varargs on Win64 is unlikely to be safe without
3078 // additional testing.
3079 if (IsCalleeWin64 || IsCallerWin64)
3082 SmallVector<CCValAssign, 16> ArgLocs;
3083 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3084 getTargetMachine(), ArgLocs, *DAG.getContext());
3086 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3087 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3088 if (!ArgLocs[i].isRegLoc())
3092 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3093 // stack. Therefore, if it's not used by the call it is not safe to optimize
3094 // this into a sibcall.
3095 bool Unused = false;
3096 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3103 SmallVector<CCValAssign, 16> RVLocs;
3104 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3105 getTargetMachine(), RVLocs, *DAG.getContext());
3106 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3107 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3108 CCValAssign &VA = RVLocs[i];
3109 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3114 // If the calling conventions do not match, then we'd better make sure the
3115 // results are returned in the same way as what the caller expects.
3117 SmallVector<CCValAssign, 16> RVLocs1;
3118 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3119 getTargetMachine(), RVLocs1, *DAG.getContext());
3120 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3122 SmallVector<CCValAssign, 16> RVLocs2;
3123 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3124 getTargetMachine(), RVLocs2, *DAG.getContext());
3125 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3127 if (RVLocs1.size() != RVLocs2.size())
3129 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3130 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3132 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3134 if (RVLocs1[i].isRegLoc()) {
3135 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3138 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3144 // If the callee takes no arguments then go on to check the results of the
3146 if (!Outs.empty()) {
3147 // Check if stack adjustment is needed. For now, do not do this if any
3148 // argument is passed on the stack.
3149 SmallVector<CCValAssign, 16> ArgLocs;
3150 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151 getTargetMachine(), ArgLocs, *DAG.getContext());
3153 // Allocate shadow area for Win64
3155 CCInfo.AllocateStack(32, 8);
3157 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158 if (CCInfo.getNextStackOffset()) {
3159 MachineFunction &MF = DAG.getMachineFunction();
3160 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3163 // Check if the arguments are already laid out in the right way as
3164 // the caller's fixed stack objects.
3165 MachineFrameInfo *MFI = MF.getFrameInfo();
3166 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3167 const X86InstrInfo *TII =
3168 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3169 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170 CCValAssign &VA = ArgLocs[i];
3171 SDValue Arg = OutVals[i];
3172 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3173 if (VA.getLocInfo() == CCValAssign::Indirect)
3175 if (!VA.isRegLoc()) {
3176 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3183 // If the tailcall address may be in a register, then make sure it's
3184 // possible to register allocate for it. In 32-bit, the call address can
3185 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3186 // callee-saved registers are restored. These happen to be the same
3187 // registers used to pass 'inreg' arguments so watch out for those.
3188 if (!Subtarget->is64Bit() &&
3189 ((!isa<GlobalAddressSDNode>(Callee) &&
3190 !isa<ExternalSymbolSDNode>(Callee)) ||
3191 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3192 unsigned NumInRegs = 0;
3193 // In PIC we need an extra register to formulate the address computation
3195 unsigned MaxInRegs =
3196 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3198 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199 CCValAssign &VA = ArgLocs[i];
3202 unsigned Reg = VA.getLocReg();
3205 case X86::EAX: case X86::EDX: case X86::ECX:
3206 if (++NumInRegs == MaxInRegs)
3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3219 const TargetLibraryInfo *libInfo) const {
3220 return X86::createFastISel(funcInfo, libInfo);
3223 //===----------------------------------------------------------------------===//
3224 // Other Lowering Hooks
3225 //===----------------------------------------------------------------------===//
3227 static bool MayFoldLoad(SDValue Op) {
3228 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3231 static bool MayFoldIntoStore(SDValue Op) {
3232 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3235 static bool isTargetShuffle(unsigned Opcode) {
3237 default: return false;
3238 case X86ISD::PSHUFD:
3239 case X86ISD::PSHUFHW:
3240 case X86ISD::PSHUFLW:
3242 case X86ISD::PALIGNR:
3243 case X86ISD::MOVLHPS:
3244 case X86ISD::MOVLHPD:
3245 case X86ISD::MOVHLPS:
3246 case X86ISD::MOVLPS:
3247 case X86ISD::MOVLPD:
3248 case X86ISD::MOVSHDUP:
3249 case X86ISD::MOVSLDUP:
3250 case X86ISD::MOVDDUP:
3253 case X86ISD::UNPCKL:
3254 case X86ISD::UNPCKH:
3255 case X86ISD::VPERMILP:
3256 case X86ISD::VPERM2X128:
3257 case X86ISD::VPERMI:
3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3263 SDValue V1, SelectionDAG &DAG) {
3265 default: llvm_unreachable("Unknown x86 shuffle node");
3266 case X86ISD::MOVSHDUP:
3267 case X86ISD::MOVSLDUP:
3268 case X86ISD::MOVDDUP:
3269 return DAG.getNode(Opc, dl, VT, V1);
3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3274 SDValue V1, unsigned TargetMask,
3275 SelectionDAG &DAG) {
3277 default: llvm_unreachable("Unknown x86 shuffle node");
3278 case X86ISD::PSHUFD:
3279 case X86ISD::PSHUFHW:
3280 case X86ISD::PSHUFLW:
3281 case X86ISD::VPERMILP:
3282 case X86ISD::VPERMI:
3283 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3288 SDValue V1, SDValue V2, unsigned TargetMask,
3289 SelectionDAG &DAG) {
3291 default: llvm_unreachable("Unknown x86 shuffle node");
3292 case X86ISD::PALIGNR:
3294 case X86ISD::VPERM2X128:
3295 return DAG.getNode(Opc, dl, VT, V1, V2,
3296 DAG.getConstant(TargetMask, MVT::i8));
3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3301 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3303 default: llvm_unreachable("Unknown x86 shuffle node");
3304 case X86ISD::MOVLHPS:
3305 case X86ISD::MOVLHPD:
3306 case X86ISD::MOVHLPS:
3307 case X86ISD::MOVLPS:
3308 case X86ISD::MOVLPD:
3311 case X86ISD::UNPCKL:
3312 case X86ISD::UNPCKH:
3313 return DAG.getNode(Opc, dl, VT, V1, V2);
3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3318 MachineFunction &MF = DAG.getMachineFunction();
3319 const X86RegisterInfo *RegInfo =
3320 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3321 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3322 int ReturnAddrIndex = FuncInfo->getRAIndex();
3324 if (ReturnAddrIndex == 0) {
3325 // Set up a frame object for the return address.
3326 unsigned SlotSize = RegInfo->getSlotSize();
3327 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3330 FuncInfo->setRAIndex(ReturnAddrIndex);
3333 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3337 bool hasSymbolicDisplacement) {
3338 // Offset should fit into 32 bit immediate field.
3339 if (!isInt<32>(Offset))
3342 // If we don't have a symbolic displacement - we don't have any extra
3344 if (!hasSymbolicDisplacement)
3347 // FIXME: Some tweaks might be needed for medium code model.
3348 if (M != CodeModel::Small && M != CodeModel::Kernel)
3351 // For small code model we assume that latest object is 16MB before end of 31
3352 // bits boundary. We may also accept pretty large negative constants knowing
3353 // that all objects are in the positive half of address space.
3354 if (M == CodeModel::Small && Offset < 16*1024*1024)
3357 // For kernel code model we know that all object resist in the negative half
3358 // of 32bits address space. We may not accept negative offsets, since they may
3359 // be just off and we may accept pretty large positive ones.
3360 if (M == CodeModel::Kernel && Offset > 0)
3366 /// isCalleePop - Determines whether the callee is required to pop its
3367 /// own arguments. Callee pop is necessary to support tail calls.
3368 bool X86::isCalleePop(CallingConv::ID CallingConv,
3369 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3373 switch (CallingConv) {
3376 case CallingConv::X86_StdCall:
3378 case CallingConv::X86_FastCall:
3380 case CallingConv::X86_ThisCall:
3382 case CallingConv::Fast:
3384 case CallingConv::GHC:
3386 case CallingConv::HiPE:
3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3392 /// specific condition code, returning the condition code and the LHS/RHS of the
3393 /// comparison to make.
3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3395 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3397 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3398 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3399 // X > -1 -> X == 0, jump !sign.
3400 RHS = DAG.getConstant(0, RHS.getValueType());
3401 return X86::COND_NS;
3403 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3404 // X < 0 -> X == 0, jump on sign.
3407 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3409 RHS = DAG.getConstant(0, RHS.getValueType());
3410 return X86::COND_LE;
3414 switch (SetCCOpcode) {
3415 default: llvm_unreachable("Invalid integer condition!");
3416 case ISD::SETEQ: return X86::COND_E;
3417 case ISD::SETGT: return X86::COND_G;
3418 case ISD::SETGE: return X86::COND_GE;
3419 case ISD::SETLT: return X86::COND_L;
3420 case ISD::SETLE: return X86::COND_LE;
3421 case ISD::SETNE: return X86::COND_NE;
3422 case ISD::SETULT: return X86::COND_B;
3423 case ISD::SETUGT: return X86::COND_A;
3424 case ISD::SETULE: return X86::COND_BE;
3425 case ISD::SETUGE: return X86::COND_AE;
3429 // First determine if it is required or is profitable to flip the operands.
3431 // If LHS is a foldable load, but RHS is not, flip the condition.
3432 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3433 !ISD::isNON_EXTLoad(RHS.getNode())) {
3434 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3435 std::swap(LHS, RHS);
3438 switch (SetCCOpcode) {
3444 std::swap(LHS, RHS);
3448 // On a floating point condition, the flags are set as follows:
3450 // 0 | 0 | 0 | X > Y
3451 // 0 | 0 | 1 | X < Y
3452 // 1 | 0 | 0 | X == Y
3453 // 1 | 1 | 1 | unordered
3454 switch (SetCCOpcode) {
3455 default: llvm_unreachable("Condcode should be pre-legalized away");
3457 case ISD::SETEQ: return X86::COND_E;
3458 case ISD::SETOLT: // flipped
3460 case ISD::SETGT: return X86::COND_A;
3461 case ISD::SETOLE: // flipped
3463 case ISD::SETGE: return X86::COND_AE;
3464 case ISD::SETUGT: // flipped
3466 case ISD::SETLT: return X86::COND_B;
3467 case ISD::SETUGE: // flipped
3469 case ISD::SETLE: return X86::COND_BE;
3471 case ISD::SETNE: return X86::COND_NE;
3472 case ISD::SETUO: return X86::COND_P;
3473 case ISD::SETO: return X86::COND_NP;
3475 case ISD::SETUNE: return X86::COND_INVALID;
3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3480 /// code. Current x86 isa includes the following FP cmov instructions:
3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3482 static bool hasFPCMov(unsigned X86CC) {
3498 /// isFPImmLegal - Returns true if the target can instruction select the
3499 /// specified FP immediate natively. If false, the legalizer will
3500 /// materialize the FP immediate as a load from a constant pool.
3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3503 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3510 /// the specified range (L, H].
3511 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3512 return (Val < 0) || (Val >= Low && Val < Hi);
3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3516 /// specified value.
3517 static bool isUndefOrEqual(int Val, int CmpVal) {
3518 return (Val < 0 || Val == CmpVal);
3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3522 /// from position Pos and ending in Pos+Size, falls within the specified
3523 /// sequential range (L, L+Pos]. or is undef.
3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3525 unsigned Pos, unsigned Size, int Low) {
3526 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3527 if (!isUndefOrEqual(Mask[i], Low))
3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3533 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3534 /// the second operand.
3535 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3536 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3537 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3538 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3539 return (Mask[0] < 2 && Mask[1] < 2);
3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3544 /// is suitable for input to PSHUFHW.
3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3546 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3549 // Lower quadword copied in order or undef.
3550 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3553 // Upper quadword shuffled.
3554 for (unsigned i = 4; i != 8; ++i)
3555 if (!isUndefOrInRange(Mask[i], 4, 8))
3558 if (VT == MVT::v16i16) {
3559 // Lower quadword copied in order or undef.
3560 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3563 // Upper quadword shuffled.
3564 for (unsigned i = 12; i != 16; ++i)
3565 if (!isUndefOrInRange(Mask[i], 12, 16))
3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3573 /// is suitable for input to PSHUFLW.
3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3575 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3578 // Upper quadword copied in order.
3579 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3582 // Lower quadword shuffled.
3583 for (unsigned i = 0; i != 4; ++i)
3584 if (!isUndefOrInRange(Mask[i], 0, 4))
3587 if (VT == MVT::v16i16) {
3588 // Upper quadword copied in order.
3589 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3592 // Lower quadword shuffled.
3593 for (unsigned i = 8; i != 12; ++i)
3594 if (!isUndefOrInRange(Mask[i], 8, 12))
3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PALIGNR.
3603 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3604 const X86Subtarget *Subtarget) {
3605 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3606 (VT.is256BitVector() && !Subtarget->hasInt256()))
3609 unsigned NumElts = VT.getVectorNumElements();
3610 unsigned NumLanes = VT.getSizeInBits()/128;
3611 unsigned NumLaneElts = NumElts/NumLanes;
3613 // Do not handle 64-bit element shuffles with palignr.
3614 if (NumLaneElts == 2)
3617 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3619 for (i = 0; i != NumLaneElts; ++i) {
3624 // Lane is all undef, go to next lane
3625 if (i == NumLaneElts)
3628 int Start = Mask[i+l];
3630 // Make sure its in this lane in one of the sources
3631 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3632 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3635 // If not lane 0, then we must match lane 0
3636 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3639 // Correct second source to be contiguous with first source
3640 if (Start >= (int)NumElts)
3641 Start -= NumElts - NumLaneElts;
3643 // Make sure we're shifting in the right direction.
3644 if (Start <= (int)(i+l))
3649 // Check the rest of the elements to see if they are consecutive.
3650 for (++i; i != NumLaneElts; ++i) {
3651 int Idx = Mask[i+l];
3653 // Make sure its in this lane
3654 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3655 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3658 // If not lane 0, then we must match lane 0
3659 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3662 if (Idx >= (int)NumElts)
3663 Idx -= NumElts - NumLaneElts;
3665 if (!isUndefOrEqual(Idx, Start+i))
3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3675 /// the two vector operands have swapped position.
3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3677 unsigned NumElems) {
3678 for (unsigned i = 0; i != NumElems; ++i) {
3682 else if (idx < (int)NumElems)
3683 Mask[i] = idx + NumElems;
3685 Mask[i] = idx - NumElems;
3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3692 /// reverse of what x86 shuffles want.
3693 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool HasFp256,
3694 bool Commuted = false) {
3695 if (!HasFp256 && VT.is256BitVector())
3698 unsigned NumElems = VT.getVectorNumElements();
3699 unsigned NumLanes = VT.getSizeInBits()/128;
3700 unsigned NumLaneElems = NumElems/NumLanes;
3702 if (NumLaneElems != 2 && NumLaneElems != 4)
3705 // VSHUFPSY divides the resulting vector into 4 chunks.
3706 // The sources are also splitted into 4 chunks, and each destination
3707 // chunk must come from a different source chunk.
3709 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3710 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3712 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3713 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3715 // VSHUFPDY divides the resulting vector into 4 chunks.
3716 // The sources are also splitted into 4 chunks, and each destination
3717 // chunk must come from a different source chunk.
3719 // SRC1 => X3 X2 X1 X0
3720 // SRC2 => Y3 Y2 Y1 Y0
3722 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3724 unsigned HalfLaneElems = NumLaneElems/2;
3725 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3726 for (unsigned i = 0; i != NumLaneElems; ++i) {
3727 int Idx = Mask[i+l];
3728 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3729 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3731 // For VSHUFPSY, the mask of the second half must be the same as the
3732 // first but with the appropriate offsets. This works in the same way as
3733 // VPERMILPS works with masks.
3734 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3736 if (!isUndefOrEqual(Idx, Mask[i]+l))
3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3747 if (!VT.is128BitVector())
3750 unsigned NumElems = VT.getVectorNumElements();
3755 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3756 return isUndefOrEqual(Mask[0], 6) &&
3757 isUndefOrEqual(Mask[1], 7) &&
3758 isUndefOrEqual(Mask[2], 2) &&
3759 isUndefOrEqual(Mask[3], 3);
3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3766 if (!VT.is128BitVector())
3769 unsigned NumElems = VT.getVectorNumElements();
3774 return isUndefOrEqual(Mask[0], 2) &&
3775 isUndefOrEqual(Mask[1], 3) &&
3776 isUndefOrEqual(Mask[2], 2) &&
3777 isUndefOrEqual(Mask[3], 3);
3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3782 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3783 if (!VT.is128BitVector())
3786 unsigned NumElems = VT.getVectorNumElements();
3788 if (NumElems != 2 && NumElems != 4)
3791 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3792 if (!isUndefOrEqual(Mask[i], i + NumElems))
3795 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3796 if (!isUndefOrEqual(Mask[i], i))
3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3805 if (!VT.is128BitVector())
3808 unsigned NumElems = VT.getVectorNumElements();
3810 if (NumElems != 2 && NumElems != 4)
3813 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3814 if (!isUndefOrEqual(Mask[i], i))
3817 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3818 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3825 // Some special combinations that can be optimized.
3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3829 SelectionDAG &DAG) {
3830 MVT VT = SVOp->getSimpleValueType(0);
3833 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3836 ArrayRef<int> Mask = SVOp->getMask();
3838 // These are the special masks that may be optimized.
3839 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3840 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3841 bool MatchEvenMask = true;
3842 bool MatchOddMask = true;
3843 for (int i=0; i<8; ++i) {
3844 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3845 MatchEvenMask = false;
3846 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3847 MatchOddMask = false;
3850 if (!MatchEvenMask && !MatchOddMask)
3853 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3855 SDValue Op0 = SVOp->getOperand(0);
3856 SDValue Op1 = SVOp->getOperand(1);
3858 if (MatchEvenMask) {
3859 // Shift the second operand right to 32 bits.
3860 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3861 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3863 // Shift the first operand left to 32 bits.
3864 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3865 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3867 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3868 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3873 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3874 bool HasInt256, bool V2IsSplat = false) {
3876 if (VT.is512BitVector())
3878 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3879 "Unsupported vector type for unpckh");
3881 unsigned NumElts = VT.getVectorNumElements();
3882 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3883 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3886 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3887 // independently on 128-bit lanes.
3888 unsigned NumLanes = VT.getSizeInBits()/128;
3889 unsigned NumLaneElts = NumElts/NumLanes;
3891 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3892 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3893 int BitI = Mask[l+i];
3894 int BitI1 = Mask[l+i+1];
3895 if (!isUndefOrEqual(BitI, j))
3898 if (!isUndefOrEqual(BitI1, NumElts))
3901 if (!isUndefOrEqual(BitI1, j + NumElts))
3910 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3912 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3913 bool HasInt256, bool V2IsSplat = false) {
3914 unsigned NumElts = VT.getVectorNumElements();
3916 if (VT.is512BitVector())
3918 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3919 "Unsupported vector type for unpckh");
3921 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3922 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3925 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3926 // independently on 128-bit lanes.
3927 unsigned NumLanes = VT.getSizeInBits()/128;
3928 unsigned NumLaneElts = NumElts/NumLanes;
3930 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3931 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
3932 int BitI = Mask[l+i];
3933 int BitI1 = Mask[l+i+1];
3934 if (!isUndefOrEqual(BitI, j))
3937 if (isUndefOrEqual(BitI1, NumElts))
3940 if (!isUndefOrEqual(BitI1, j+NumElts))
3948 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3949 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3951 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3952 unsigned NumElts = VT.getVectorNumElements();
3953 bool Is256BitVec = VT.is256BitVector();
3955 if (VT.is512BitVector())
3957 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3958 "Unsupported vector type for unpckh");
3960 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3961 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3964 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3965 // FIXME: Need a better way to get rid of this, there's no latency difference
3966 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3967 // the former later. We should also remove the "_undef" special mask.
3968 if (NumElts == 4 && Is256BitVec)
3971 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3972 // independently on 128-bit lanes.
3973 unsigned NumLanes = VT.getSizeInBits()/128;
3974 unsigned NumLaneElts = NumElts/NumLanes;
3976 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3977 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3978 int BitI = Mask[l+i];
3979 int BitI1 = Mask[l+i+1];
3981 if (!isUndefOrEqual(BitI, j))
3983 if (!isUndefOrEqual(BitI1, j))
3991 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3992 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3994 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3995 unsigned NumElts = VT.getVectorNumElements();
3997 if (VT.is512BitVector())
4000 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4001 "Unsupported vector type for unpckh");
4003 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4004 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4007 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4008 // independently on 128-bit lanes.
4009 unsigned NumLanes = VT.getSizeInBits()/128;
4010 unsigned NumLaneElts = NumElts/NumLanes;
4012 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4013 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4014 int BitI = Mask[l+i];
4015 int BitI1 = Mask[l+i+1];
4016 if (!isUndefOrEqual(BitI, j))
4018 if (!isUndefOrEqual(BitI1, j))
4025 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4026 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4027 /// MOVSD, and MOVD, i.e. setting the lowest element.
4028 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4029 if (VT.getVectorElementType().getSizeInBits() < 32)
4031 if (!VT.is128BitVector())
4034 unsigned NumElts = VT.getVectorNumElements();
4036 if (!isUndefOrEqual(Mask[0], NumElts))
4039 for (unsigned i = 1; i != NumElts; ++i)
4040 if (!isUndefOrEqual(Mask[i], i))
4046 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4047 /// as permutations between 128-bit chunks or halves. As an example: this
4049 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4050 /// The first half comes from the second half of V1 and the second half from the
4051 /// the second half of V2.
4052 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4053 if (!HasFp256 || !VT.is256BitVector())
4056 // The shuffle result is divided into half A and half B. In total the two
4057 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4058 // B must come from C, D, E or F.
4059 unsigned HalfSize = VT.getVectorNumElements()/2;
4060 bool MatchA = false, MatchB = false;
4062 // Check if A comes from one of C, D, E, F.
4063 for (unsigned Half = 0; Half != 4; ++Half) {
4064 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4070 // Check if B comes from one of C, D, E, F.
4071 for (unsigned Half = 0; Half != 4; ++Half) {
4072 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4078 return MatchA && MatchB;
4081 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4083 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4084 MVT VT = SVOp->getSimpleValueType(0);
4086 unsigned HalfSize = VT.getVectorNumElements()/2;
4088 unsigned FstHalf = 0, SndHalf = 0;
4089 for (unsigned i = 0; i < HalfSize; ++i) {
4090 if (SVOp->getMaskElt(i) > 0) {
4091 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4095 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4096 if (SVOp->getMaskElt(i) > 0) {
4097 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4102 return (FstHalf | (SndHalf << 4));
4105 // Symmetric in-lane mask. Each lane has 4 elements (for imm8)
4106 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4107 unsigned NumElts = VT.getVectorNumElements();
4108 if (!(VT.is256BitVector() && NumElts == 4) &&
4109 !(VT.is512BitVector() && NumElts == 8))
4113 unsigned LaneSize = 4;
4114 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4115 for (unsigned i = 0; i != LaneSize; ++i) {
4116 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4118 if (Mask[i] >= 0 && !isUndefOrEqual(Mask[i+l], Mask[i]+l))
4121 Imm8 |= (Mask[i+l] - l) << (i*2);
4128 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4129 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4130 /// Note that VPERMIL mask matching is different depending whether theunderlying
4131 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4132 /// to the same elements of the low, but to the higher half of the source.
4133 /// In VPERMILPD the two lanes could be shuffled independently of each other
4134 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4135 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4139 unsigned NumElts = VT.getVectorNumElements();
4140 // Only match 256-bit with 32/64-bit types
4141 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4144 unsigned NumLanes = VT.getSizeInBits()/128;
4145 unsigned LaneSize = NumElts/NumLanes;
4146 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4147 for (unsigned i = 0; i != LaneSize; ++i) {
4148 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4150 if (NumElts != 8 || l == 0)
4152 // VPERMILPS handling
4153 if (Mask[i] >= 0 && !isUndefOrEqual(Mask[i+l], Mask[i]+l))
4161 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4162 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4163 /// element of vector 2 and the other elements to come from vector 1 in order.
4164 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4165 bool V2IsSplat = false, bool V2IsUndef = false) {
4166 if (!VT.is128BitVector())
4169 unsigned NumOps = VT.getVectorNumElements();
4170 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4173 if (!isUndefOrEqual(Mask[0], 0))
4176 for (unsigned i = 1; i != NumOps; ++i)
4177 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4178 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4179 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4185 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4186 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4187 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4188 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4189 const X86Subtarget *Subtarget) {
4190 if (!Subtarget->hasSSE3())
4193 unsigned NumElems = VT.getVectorNumElements();
4195 if ((VT.is128BitVector() && NumElems != 4) ||
4196 (VT.is256BitVector() && NumElems != 8) ||
4197 (VT.is512BitVector() && NumElems != 16))
4200 // "i+1" is the value the indexed mask element must have
4201 for (unsigned i = 0; i != NumElems; i += 2)
4202 if (!isUndefOrEqual(Mask[i], i+1) ||
4203 !isUndefOrEqual(Mask[i+1], i+1))
4209 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4210 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4211 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4212 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4213 const X86Subtarget *Subtarget) {
4214 if (!Subtarget->hasSSE3())
4217 unsigned NumElems = VT.getVectorNumElements();
4219 if ((VT.is128BitVector() && NumElems != 4) ||
4220 (VT.is256BitVector() && NumElems != 8) ||
4221 (VT.is512BitVector() && NumElems != 16))
4224 // "i" is the value the indexed mask element must have
4225 for (unsigned i = 0; i != NumElems; i += 2)
4226 if (!isUndefOrEqual(Mask[i], i) ||
4227 !isUndefOrEqual(Mask[i+1], i))
4233 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4234 /// specifies a shuffle of elements that is suitable for input to 256-bit
4235 /// version of MOVDDUP.
4236 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4237 if (!HasFp256 || !VT.is256BitVector())
4240 unsigned NumElts = VT.getVectorNumElements();
4244 for (unsigned i = 0; i != NumElts/2; ++i)
4245 if (!isUndefOrEqual(Mask[i], 0))
4247 for (unsigned i = NumElts/2; i != NumElts; ++i)
4248 if (!isUndefOrEqual(Mask[i], NumElts/2))
4253 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4254 /// specifies a shuffle of elements that is suitable for input to 128-bit
4255 /// version of MOVDDUP.
4256 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4257 if (!VT.is128BitVector())
4260 unsigned e = VT.getVectorNumElements() / 2;
4261 for (unsigned i = 0; i != e; ++i)
4262 if (!isUndefOrEqual(Mask[i], i))
4264 for (unsigned i = 0; i != e; ++i)
4265 if (!isUndefOrEqual(Mask[e+i], i))
4270 /// isVEXTRACTIndex - Return true if the specified
4271 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4272 /// suitable for instruction that extract 128 or 256 bit vectors
4273 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4274 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4275 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4278 // The index should be aligned on a vecWidth-bit boundary.
4280 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4282 MVT VT = N->getSimpleValueType(0);
4283 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4284 bool Result = (Index * ElSize) % vecWidth == 0;
4289 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4290 /// operand specifies a subvector insert that is suitable for input to
4291 /// insertion of 128 or 256-bit subvectors
4292 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4293 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4294 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4296 // The index should be aligned on a vecWidth-bit boundary.
4298 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4300 MVT VT = N->getSimpleValueType(0);
4301 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4302 bool Result = (Index * ElSize) % vecWidth == 0;
4307 bool X86::isVINSERT128Index(SDNode *N) {
4308 return isVINSERTIndex(N, 128);
4311 bool X86::isVINSERT256Index(SDNode *N) {
4312 return isVINSERTIndex(N, 256);
4315 bool X86::isVEXTRACT128Index(SDNode *N) {
4316 return isVEXTRACTIndex(N, 128);
4319 bool X86::isVEXTRACT256Index(SDNode *N) {
4320 return isVEXTRACTIndex(N, 256);
4323 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4324 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4325 /// Handles 128-bit and 256-bit.
4326 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4327 MVT VT = N->getSimpleValueType(0);
4329 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4330 "Unsupported vector type for PSHUF/SHUFP");
4332 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4333 // independently on 128-bit lanes.
4334 unsigned NumElts = VT.getVectorNumElements();
4335 unsigned NumLanes = VT.getSizeInBits()/128;
4336 unsigned NumLaneElts = NumElts/NumLanes;
4338 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4339 "Only supports 2 or 4 elements per lane");
4341 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4343 for (unsigned i = 0; i != NumElts; ++i) {
4344 int Elt = N->getMaskElt(i);
4345 if (Elt < 0) continue;
4346 Elt &= NumLaneElts - 1;
4347 unsigned ShAmt = (i << Shift) % 8;
4348 Mask |= Elt << ShAmt;
4354 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4355 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4356 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4357 MVT VT = N->getSimpleValueType(0);
4359 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4360 "Unsupported vector type for PSHUFHW");
4362 unsigned NumElts = VT.getVectorNumElements();
4365 for (unsigned l = 0; l != NumElts; l += 8) {
4366 // 8 nodes per lane, but we only care about the last 4.
4367 for (unsigned i = 0; i < 4; ++i) {
4368 int Elt = N->getMaskElt(l+i+4);
4369 if (Elt < 0) continue;
4370 Elt &= 0x3; // only 2-bits.
4371 Mask |= Elt << (i * 2);
4378 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4379 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4380 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4381 MVT VT = N->getSimpleValueType(0);
4383 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4384 "Unsupported vector type for PSHUFHW");
4386 unsigned NumElts = VT.getVectorNumElements();
4389 for (unsigned l = 0; l != NumElts; l += 8) {
4390 // 8 nodes per lane, but we only care about the first 4.
4391 for (unsigned i = 0; i < 4; ++i) {
4392 int Elt = N->getMaskElt(l+i);
4393 if (Elt < 0) continue;
4394 Elt &= 0x3; // only 2-bits
4395 Mask |= Elt << (i * 2);
4402 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4403 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4404 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4405 MVT VT = SVOp->getSimpleValueType(0);
4406 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4408 unsigned NumElts = VT.getVectorNumElements();
4409 unsigned NumLanes = VT.getSizeInBits()/128;
4410 unsigned NumLaneElts = NumElts/NumLanes;
4414 for (i = 0; i != NumElts; ++i) {
4415 Val = SVOp->getMaskElt(i);
4419 if (Val >= (int)NumElts)
4420 Val -= NumElts - NumLaneElts;
4422 assert(Val - i > 0 && "PALIGNR imm should be positive");
4423 return (Val - i) * EltSize;
4426 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4427 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4428 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4429 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4432 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4434 MVT VecVT = N->getOperand(0).getSimpleValueType();
4435 MVT ElVT = VecVT.getVectorElementType();
4437 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4438 return Index / NumElemsPerChunk;
4441 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4442 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4443 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4444 llvm_unreachable("Illegal insert subvector for VINSERT");
4447 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4449 MVT VecVT = N->getSimpleValueType(0);
4450 MVT ElVT = VecVT.getVectorElementType();
4452 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4453 return Index / NumElemsPerChunk;
4456 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4457 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4458 /// and VINSERTI128 instructions.
4459 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4460 return getExtractVEXTRACTImmediate(N, 128);
4463 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4464 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4465 /// and VINSERTI64x4 instructions.
4466 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4467 return getExtractVEXTRACTImmediate(N, 256);
4470 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4471 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4472 /// and VINSERTI128 instructions.
4473 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4474 return getInsertVINSERTImmediate(N, 128);
4477 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4478 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4479 /// and VINSERTI64x4 instructions.
4480 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4481 return getInsertVINSERTImmediate(N, 256);
4484 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4486 bool X86::isZeroNode(SDValue Elt) {
4487 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4488 return CN->isNullValue();
4489 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4490 return CFP->getValueAPF().isPosZero();
4494 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4495 /// their permute mask.
4496 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4497 SelectionDAG &DAG) {
4498 MVT VT = SVOp->getSimpleValueType(0);
4499 unsigned NumElems = VT.getVectorNumElements();
4500 SmallVector<int, 8> MaskVec;
4502 for (unsigned i = 0; i != NumElems; ++i) {
4503 int Idx = SVOp->getMaskElt(i);
4505 if (Idx < (int)NumElems)
4510 MaskVec.push_back(Idx);
4512 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4513 SVOp->getOperand(0), &MaskVec[0]);
4516 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4517 /// match movhlps. The lower half elements should come from upper half of
4518 /// V1 (and in order), and the upper half elements should come from the upper
4519 /// half of V2 (and in order).
4520 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4521 if (!VT.is128BitVector())
4523 if (VT.getVectorNumElements() != 4)
4525 for (unsigned i = 0, e = 2; i != e; ++i)
4526 if (!isUndefOrEqual(Mask[i], i+2))
4528 for (unsigned i = 2; i != 4; ++i)
4529 if (!isUndefOrEqual(Mask[i], i+4))
4534 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4535 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4537 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4538 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4540 N = N->getOperand(0).getNode();
4541 if (!ISD::isNON_EXTLoad(N))
4544 *LD = cast<LoadSDNode>(N);
4548 // Test whether the given value is a vector value which will be legalized
4550 static bool WillBeConstantPoolLoad(SDNode *N) {
4551 if (N->getOpcode() != ISD::BUILD_VECTOR)
4554 // Check for any non-constant elements.
4555 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4556 switch (N->getOperand(i).getNode()->getOpcode()) {
4558 case ISD::ConstantFP:
4565 // Vectors of all-zeros and all-ones are materialized with special
4566 // instructions rather than being loaded.
4567 return !ISD::isBuildVectorAllZeros(N) &&
4568 !ISD::isBuildVectorAllOnes(N);
4571 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4572 /// match movlp{s|d}. The lower half elements should come from lower half of
4573 /// V1 (and in order), and the upper half elements should come from the upper
4574 /// half of V2 (and in order). And since V1 will become the source of the
4575 /// MOVLP, it must be either a vector load or a scalar load to vector.
4576 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4577 ArrayRef<int> Mask, MVT VT) {
4578 if (!VT.is128BitVector())
4581 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4583 // Is V2 is a vector load, don't do this transformation. We will try to use
4584 // load folding shufps op.
4585 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4588 unsigned NumElems = VT.getVectorNumElements();
4590 if (NumElems != 2 && NumElems != 4)
4592 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4593 if (!isUndefOrEqual(Mask[i], i))
4595 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4596 if (!isUndefOrEqual(Mask[i], i+NumElems))
4601 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4603 static bool isSplatVector(SDNode *N) {
4604 if (N->getOpcode() != ISD::BUILD_VECTOR)
4607 SDValue SplatValue = N->getOperand(0);
4608 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4609 if (N->getOperand(i) != SplatValue)
4614 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4615 /// to an zero vector.
4616 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4617 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4618 SDValue V1 = N->getOperand(0);
4619 SDValue V2 = N->getOperand(1);
4620 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4621 for (unsigned i = 0; i != NumElems; ++i) {
4622 int Idx = N->getMaskElt(i);
4623 if (Idx >= (int)NumElems) {
4624 unsigned Opc = V2.getOpcode();
4625 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4627 if (Opc != ISD::BUILD_VECTOR ||
4628 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4630 } else if (Idx >= 0) {
4631 unsigned Opc = V1.getOpcode();
4632 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4634 if (Opc != ISD::BUILD_VECTOR ||
4635 !X86::isZeroNode(V1.getOperand(Idx)))
4642 /// getZeroVector - Returns a vector of specified type with all zero elements.
4644 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4645 SelectionDAG &DAG, SDLoc dl) {
4646 assert(VT.isVector() && "Expected a vector type");
4648 // Always build SSE zero vectors as <4 x i32> bitcasted
4649 // to their dest type. This ensures they get CSE'd.
4651 if (VT.is128BitVector()) { // SSE
4652 if (Subtarget->hasSSE2()) { // SSE2
4653 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4654 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4656 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4657 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4659 } else if (VT.is256BitVector()) { // AVX
4660 if (Subtarget->hasInt256()) { // AVX2
4661 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4662 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4663 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4664 array_lengthof(Ops));
4666 // 256-bit logic and arithmetic instructions in AVX are all
4667 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4668 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4669 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4670 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4671 array_lengthof(Ops));
4674 llvm_unreachable("Unexpected vector type");
4676 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4679 /// getOnesVector - Returns a vector of specified type with all bits set.
4680 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4681 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4682 /// Then bitcast to their original type, ensuring they get CSE'd.
4683 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4685 assert(VT.isVector() && "Expected a vector type");
4687 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4689 if (VT.is256BitVector()) {
4690 if (HasInt256) { // AVX2
4691 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4692 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4693 array_lengthof(Ops));
4695 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4696 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4698 } else if (VT.is128BitVector()) {
4699 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4701 llvm_unreachable("Unexpected vector type");
4703 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4706 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4707 /// that point to V2 points to its first element.
4708 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4709 for (unsigned i = 0; i != NumElems; ++i) {
4710 if (Mask[i] > (int)NumElems) {
4716 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4717 /// operation of specified width.
4718 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4720 unsigned NumElems = VT.getVectorNumElements();
4721 SmallVector<int, 8> Mask;
4722 Mask.push_back(NumElems);
4723 for (unsigned i = 1; i != NumElems; ++i)
4725 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4728 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4729 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4731 unsigned NumElems = VT.getVectorNumElements();
4732 SmallVector<int, 8> Mask;
4733 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4735 Mask.push_back(i + NumElems);
4737 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4740 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4741 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4743 unsigned NumElems = VT.getVectorNumElements();
4744 SmallVector<int, 8> Mask;
4745 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4746 Mask.push_back(i + Half);
4747 Mask.push_back(i + NumElems + Half);
4749 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4752 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4753 // a generic shuffle instruction because the target has no such instructions.
4754 // Generate shuffles which repeat i16 and i8 several times until they can be
4755 // represented by v4f32 and then be manipulated by target suported shuffles.
4756 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4757 MVT VT = V.getSimpleValueType();
4758 int NumElems = VT.getVectorNumElements();
4761 while (NumElems > 4) {
4762 if (EltNo < NumElems/2) {
4763 V = getUnpackl(DAG, dl, VT, V, V);
4765 V = getUnpackh(DAG, dl, VT, V, V);
4766 EltNo -= NumElems/2;
4773 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4774 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4775 MVT VT = V.getSimpleValueType();
4778 if (VT.is128BitVector()) {
4779 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4780 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4781 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4783 } else if (VT.is256BitVector()) {
4784 // To use VPERMILPS to splat scalars, the second half of indicies must
4785 // refer to the higher part, which is a duplication of the lower one,
4786 // because VPERMILPS can only handle in-lane permutations.
4787 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4788 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4790 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4791 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4794 llvm_unreachable("Vector size not supported");
4796 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4799 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4800 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4801 MVT SrcVT = SV->getSimpleValueType(0);
4802 SDValue V1 = SV->getOperand(0);
4805 int EltNo = SV->getSplatIndex();
4806 int NumElems = SrcVT.getVectorNumElements();
4807 bool Is256BitVec = SrcVT.is256BitVector();
4809 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4810 "Unknown how to promote splat for type");
4812 // Extract the 128-bit part containing the splat element and update
4813 // the splat element index when it refers to the higher register.
4815 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4816 if (EltNo >= NumElems/2)
4817 EltNo -= NumElems/2;
4820 // All i16 and i8 vector types can't be used directly by a generic shuffle
4821 // instruction because the target has no such instruction. Generate shuffles
4822 // which repeat i16 and i8 several times until they fit in i32, and then can
4823 // be manipulated by target suported shuffles.
4824 MVT EltVT = SrcVT.getVectorElementType();
4825 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4826 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4828 // Recreate the 256-bit vector and place the same 128-bit vector
4829 // into the low and high part. This is necessary because we want
4830 // to use VPERM* to shuffle the vectors
4832 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4835 return getLegalSplat(DAG, V1, EltNo);
4838 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4839 /// vector of zero or undef vector. This produces a shuffle where the low
4840 /// element of V2 is swizzled into the zero/undef vector, landing at element
4841 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4842 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4844 const X86Subtarget *Subtarget,
4845 SelectionDAG &DAG) {
4846 MVT VT = V2.getSimpleValueType();
4848 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4849 unsigned NumElems = VT.getVectorNumElements();
4850 SmallVector<int, 16> MaskVec;
4851 for (unsigned i = 0; i != NumElems; ++i)
4852 // If this is the insertion idx, put the low elt of V2 here.
4853 MaskVec.push_back(i == Idx ? NumElems : i);
4854 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4857 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4858 /// target specific opcode. Returns true if the Mask could be calculated.
4859 /// Sets IsUnary to true if only uses one source.
4860 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4861 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4862 unsigned NumElems = VT.getVectorNumElements();
4866 switch(N->getOpcode()) {
4868 ImmN = N->getOperand(N->getNumOperands()-1);
4869 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4871 case X86ISD::UNPCKH:
4872 DecodeUNPCKHMask(VT, Mask);
4874 case X86ISD::UNPCKL:
4875 DecodeUNPCKLMask(VT, Mask);
4877 case X86ISD::MOVHLPS:
4878 DecodeMOVHLPSMask(NumElems, Mask);
4880 case X86ISD::MOVLHPS:
4881 DecodeMOVLHPSMask(NumElems, Mask);
4883 case X86ISD::PALIGNR:
4884 ImmN = N->getOperand(N->getNumOperands()-1);
4885 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4887 case X86ISD::PSHUFD:
4888 case X86ISD::VPERMILP:
4889 ImmN = N->getOperand(N->getNumOperands()-1);
4890 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4893 case X86ISD::PSHUFHW:
4894 ImmN = N->getOperand(N->getNumOperands()-1);
4895 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4898 case X86ISD::PSHUFLW:
4899 ImmN = N->getOperand(N->getNumOperands()-1);
4900 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4903 case X86ISD::VPERMI:
4904 ImmN = N->getOperand(N->getNumOperands()-1);
4905 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4909 case X86ISD::MOVSD: {
4910 // The index 0 always comes from the first element of the second source,
4911 // this is why MOVSS and MOVSD are used in the first place. The other
4912 // elements come from the other positions of the first source vector
4913 Mask.push_back(NumElems);
4914 for (unsigned i = 1; i != NumElems; ++i) {
4919 case X86ISD::VPERM2X128:
4920 ImmN = N->getOperand(N->getNumOperands()-1);
4921 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4922 if (Mask.empty()) return false;
4924 case X86ISD::MOVDDUP:
4925 case X86ISD::MOVLHPD:
4926 case X86ISD::MOVLPD:
4927 case X86ISD::MOVLPS:
4928 case X86ISD::MOVSHDUP:
4929 case X86ISD::MOVSLDUP:
4930 // Not yet implemented
4932 default: llvm_unreachable("unknown target shuffle node");
4938 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4939 /// element of the result of the vector shuffle.
4940 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4943 return SDValue(); // Limit search depth.
4945 SDValue V = SDValue(N, 0);
4946 EVT VT = V.getValueType();
4947 unsigned Opcode = V.getOpcode();
4949 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4950 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4951 int Elt = SV->getMaskElt(Index);
4954 return DAG.getUNDEF(VT.getVectorElementType());
4956 unsigned NumElems = VT.getVectorNumElements();
4957 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4958 : SV->getOperand(1);
4959 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4962 // Recurse into target specific vector shuffles to find scalars.
4963 if (isTargetShuffle(Opcode)) {
4964 MVT ShufVT = V.getSimpleValueType();
4965 unsigned NumElems = ShufVT.getVectorNumElements();
4966 SmallVector<int, 16> ShuffleMask;
4969 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4972 int Elt = ShuffleMask[Index];
4974 return DAG.getUNDEF(ShufVT.getVectorElementType());
4976 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4978 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4982 // Actual nodes that may contain scalar elements
4983 if (Opcode == ISD::BITCAST) {
4984 V = V.getOperand(0);
4985 EVT SrcVT = V.getValueType();
4986 unsigned NumElems = VT.getVectorNumElements();
4988 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4992 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4993 return (Index == 0) ? V.getOperand(0)
4994 : DAG.getUNDEF(VT.getVectorElementType());
4996 if (V.getOpcode() == ISD::BUILD_VECTOR)
4997 return V.getOperand(Index);
5002 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5003 /// shuffle operation which come from a consecutively from a zero. The
5004 /// search can start in two different directions, from left or right.
5005 /// We count undefs as zeros until PreferredNum is reached.
5006 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5007 unsigned NumElems, bool ZerosFromLeft,
5009 unsigned PreferredNum = -1U) {
5010 unsigned NumZeros = 0;
5011 for (unsigned i = 0; i != NumElems; ++i) {
5012 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5013 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5017 if (X86::isZeroNode(Elt))
5019 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5020 NumZeros = std::min(NumZeros + 1, PreferredNum);
5028 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5029 /// correspond consecutively to elements from one of the vector operands,
5030 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5032 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5033 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5034 unsigned NumElems, unsigned &OpNum) {
5035 bool SeenV1 = false;
5036 bool SeenV2 = false;
5038 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5039 int Idx = SVOp->getMaskElt(i);
5040 // Ignore undef indicies
5044 if (Idx < (int)NumElems)
5049 // Only accept consecutive elements from the same vector
5050 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5054 OpNum = SeenV1 ? 0 : 1;
5058 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5059 /// logical left shift of a vector.
5060 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5061 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5063 SVOp->getSimpleValueType(0).getVectorNumElements();
5064 unsigned NumZeros = getNumOfConsecutiveZeros(
5065 SVOp, NumElems, false /* check zeros from right */, DAG,
5066 SVOp->getMaskElt(0));
5072 // Considering the elements in the mask that are not consecutive zeros,
5073 // check if they consecutively come from only one of the source vectors.
5075 // V1 = {X, A, B, C} 0
5077 // vector_shuffle V1, V2 <1, 2, 3, X>
5079 if (!isShuffleMaskConsecutive(SVOp,
5080 0, // Mask Start Index
5081 NumElems-NumZeros, // Mask End Index(exclusive)
5082 NumZeros, // Where to start looking in the src vector
5083 NumElems, // Number of elements in vector
5084 OpSrc)) // Which source operand ?
5089 ShVal = SVOp->getOperand(OpSrc);
5093 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5094 /// logical left shift of a vector.
5095 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5096 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5098 SVOp->getSimpleValueType(0).getVectorNumElements();
5099 unsigned NumZeros = getNumOfConsecutiveZeros(
5100 SVOp, NumElems, true /* check zeros from left */, DAG,
5101 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5107 // Considering the elements in the mask that are not consecutive zeros,
5108 // check if they consecutively come from only one of the source vectors.
5110 // 0 { A, B, X, X } = V2
5112 // vector_shuffle V1, V2 <X, X, 4, 5>
5114 if (!isShuffleMaskConsecutive(SVOp,
5115 NumZeros, // Mask Start Index
5116 NumElems, // Mask End Index(exclusive)
5117 0, // Where to start looking in the src vector
5118 NumElems, // Number of elements in vector
5119 OpSrc)) // Which source operand ?
5124 ShVal = SVOp->getOperand(OpSrc);
5128 /// isVectorShift - Returns true if the shuffle can be implemented as a
5129 /// logical left or right shift of a vector.
5130 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5131 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5132 // Although the logic below support any bitwidth size, there are no
5133 // shift instructions which handle more than 128-bit vectors.
5134 if (!SVOp->getSimpleValueType(0).is128BitVector())
5137 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5138 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5144 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5146 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5147 unsigned NumNonZero, unsigned NumZero,
5149 const X86Subtarget* Subtarget,
5150 const TargetLowering &TLI) {
5157 for (unsigned i = 0; i < 16; ++i) {
5158 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5159 if (ThisIsNonZero && First) {
5161 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5163 V = DAG.getUNDEF(MVT::v8i16);
5168 SDValue ThisElt(0, 0), LastElt(0, 0);
5169 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5170 if (LastIsNonZero) {
5171 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5172 MVT::i16, Op.getOperand(i-1));
5174 if (ThisIsNonZero) {
5175 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5176 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5177 ThisElt, DAG.getConstant(8, MVT::i8));
5179 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5183 if (ThisElt.getNode())
5184 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5185 DAG.getIntPtrConstant(i/2));
5189 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5192 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5194 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5195 unsigned NumNonZero, unsigned NumZero,
5197 const X86Subtarget* Subtarget,
5198 const TargetLowering &TLI) {
5205 for (unsigned i = 0; i < 8; ++i) {
5206 bool isNonZero = (NonZeros & (1 << i)) != 0;
5210 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5212 V = DAG.getUNDEF(MVT::v8i16);
5215 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5216 MVT::v8i16, V, Op.getOperand(i),
5217 DAG.getIntPtrConstant(i));
5224 /// getVShift - Return a vector logical shift node.
5226 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5227 unsigned NumBits, SelectionDAG &DAG,
5228 const TargetLowering &TLI, SDLoc dl) {
5229 assert(VT.is128BitVector() && "Unknown type for VShift");
5230 EVT ShVT = MVT::v2i64;
5231 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5232 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5233 return DAG.getNode(ISD::BITCAST, dl, VT,
5234 DAG.getNode(Opc, dl, ShVT, SrcOp,
5235 DAG.getConstant(NumBits,
5236 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5240 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5241 SelectionDAG &DAG) const {
5243 // Check if the scalar load can be widened into a vector load. And if
5244 // the address is "base + cst" see if the cst can be "absorbed" into
5245 // the shuffle mask.
5246 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5247 SDValue Ptr = LD->getBasePtr();
5248 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5250 EVT PVT = LD->getValueType(0);
5251 if (PVT != MVT::i32 && PVT != MVT::f32)
5256 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5257 FI = FINode->getIndex();
5259 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5260 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5261 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5262 Offset = Ptr.getConstantOperandVal(1);
5263 Ptr = Ptr.getOperand(0);
5268 // FIXME: 256-bit vector instructions don't require a strict alignment,
5269 // improve this code to support it better.
5270 unsigned RequiredAlign = VT.getSizeInBits()/8;
5271 SDValue Chain = LD->getChain();
5272 // Make sure the stack object alignment is at least 16 or 32.
5273 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5274 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5275 if (MFI->isFixedObjectIndex(FI)) {
5276 // Can't change the alignment. FIXME: It's possible to compute
5277 // the exact stack offset and reference FI + adjust offset instead.
5278 // If someone *really* cares about this. That's the way to implement it.
5281 MFI->setObjectAlignment(FI, RequiredAlign);
5285 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5286 // Ptr + (Offset & ~15).
5289 if ((Offset % RequiredAlign) & 3)
5291 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5293 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5294 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5296 int EltNo = (Offset - StartOffset) >> 2;
5297 unsigned NumElems = VT.getVectorNumElements();
5299 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5300 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5301 LD->getPointerInfo().getWithOffset(StartOffset),
5302 false, false, false, 0);
5304 SmallVector<int, 8> Mask;
5305 for (unsigned i = 0; i != NumElems; ++i)
5306 Mask.push_back(EltNo);
5308 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5314 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5315 /// vector of type 'VT', see if the elements can be replaced by a single large
5316 /// load which has the same value as a build_vector whose operands are 'elts'.
5318 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5320 /// FIXME: we'd also like to handle the case where the last elements are zero
5321 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5322 /// There's even a handy isZeroNode for that purpose.
5323 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5324 SDLoc &DL, SelectionDAG &DAG) {
5325 EVT EltVT = VT.getVectorElementType();
5326 unsigned NumElems = Elts.size();
5328 LoadSDNode *LDBase = NULL;
5329 unsigned LastLoadedElt = -1U;
5331 // For each element in the initializer, see if we've found a load or an undef.
5332 // If we don't find an initial load element, or later load elements are
5333 // non-consecutive, bail out.
5334 for (unsigned i = 0; i < NumElems; ++i) {
5335 SDValue Elt = Elts[i];
5337 if (!Elt.getNode() ||
5338 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5341 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5343 LDBase = cast<LoadSDNode>(Elt.getNode());
5347 if (Elt.getOpcode() == ISD::UNDEF)
5350 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5351 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5356 // If we have found an entire vector of loads and undefs, then return a large
5357 // load of the entire vector width starting at the base pointer. If we found
5358 // consecutive loads for the low half, generate a vzext_load node.
5359 if (LastLoadedElt == NumElems - 1) {
5360 SDValue NewLd = SDValue();
5361 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5362 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5363 LDBase->getPointerInfo(),
5364 LDBase->isVolatile(), LDBase->isNonTemporal(),
5365 LDBase->isInvariant(), 0);
5366 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5367 LDBase->getPointerInfo(),
5368 LDBase->isVolatile(), LDBase->isNonTemporal(),
5369 LDBase->isInvariant(), LDBase->getAlignment());
5371 if (LDBase->hasAnyUseOfValue(1)) {
5372 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5374 SDValue(NewLd.getNode(), 1));
5375 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5376 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5377 SDValue(NewLd.getNode(), 1));
5382 if (NumElems == 4 && LastLoadedElt == 1 &&
5383 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5384 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5385 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5387 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5388 array_lengthof(Ops), MVT::i64,
5389 LDBase->getPointerInfo(),
5390 LDBase->getAlignment(),
5391 false/*isVolatile*/, true/*ReadMem*/,
5394 // Make sure the newly-created LOAD is in the same position as LDBase in
5395 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5396 // update uses of LDBase's output chain to use the TokenFactor.
5397 if (LDBase->hasAnyUseOfValue(1)) {
5398 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5399 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5400 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5401 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5402 SDValue(ResNode.getNode(), 1));
5405 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5410 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5411 /// to generate a splat value for the following cases:
5412 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5413 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5414 /// a scalar load, or a constant.
5415 /// The VBROADCAST node is returned when a pattern is found,
5416 /// or SDValue() otherwise.
5417 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5418 SelectionDAG &DAG) {
5419 if (!Subtarget->hasFp256())
5422 MVT VT = Op.getSimpleValueType();
5425 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5426 "Unsupported vector type for broadcast.");
5431 switch (Op.getOpcode()) {
5433 // Unknown pattern found.
5436 case ISD::BUILD_VECTOR: {
5437 // The BUILD_VECTOR node must be a splat.
5438 if (!isSplatVector(Op.getNode()))
5441 Ld = Op.getOperand(0);
5442 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5443 Ld.getOpcode() == ISD::ConstantFP);
5445 // The suspected load node has several users. Make sure that all
5446 // of its users are from the BUILD_VECTOR node.
5447 // Constants may have multiple users.
5448 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5453 case ISD::VECTOR_SHUFFLE: {
5454 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5456 // Shuffles must have a splat mask where the first element is
5458 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5461 SDValue Sc = Op.getOperand(0);
5462 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5463 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5465 if (!Subtarget->hasInt256())
5468 // Use the register form of the broadcast instruction available on AVX2.
5469 if (VT.getSizeInBits() >= 256)
5470 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5471 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5474 Ld = Sc.getOperand(0);
5475 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5476 Ld.getOpcode() == ISD::ConstantFP);
5478 // The scalar_to_vector node and the suspected
5479 // load node must have exactly one user.
5480 // Constants may have multiple users.
5482 // AVX-512 has register version of the broadcast
5483 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5484 Ld.getValueType().getSizeInBits() >= 32;
5485 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5492 bool IsGE256 = (VT.getSizeInBits() >= 256);
5494 // Handle the broadcasting a single constant scalar from the constant pool
5495 // into a vector. On Sandybridge it is still better to load a constant vector
5496 // from the constant pool and not to broadcast it from a scalar.
5497 if (ConstSplatVal && Subtarget->hasInt256()) {
5498 EVT CVT = Ld.getValueType();
5499 assert(!CVT.isVector() && "Must not broadcast a vector type");
5500 unsigned ScalarSize = CVT.getSizeInBits();
5502 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5503 const Constant *C = 0;
5504 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5505 C = CI->getConstantIntValue();
5506 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5507 C = CF->getConstantFPValue();
5509 assert(C && "Invalid constant type");
5511 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5512 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5513 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5514 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5515 MachinePointerInfo::getConstantPool(),
5516 false, false, false, Alignment);
5518 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5522 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5523 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5525 // Handle AVX2 in-register broadcasts.
5526 if (!IsLoad && Subtarget->hasInt256() &&
5527 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5528 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5530 // The scalar source must be a normal load.
5534 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5535 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5537 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5538 // double since there is no vbroadcastsd xmm
5539 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5540 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5541 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5544 // Unsupported broadcast.
5548 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5549 MVT VT = Op.getSimpleValueType();
5551 // Skip if insert_vec_elt is not supported.
5552 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5553 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5557 unsigned NumElems = Op.getNumOperands();
5561 SmallVector<unsigned, 4> InsertIndices;
5562 SmallVector<int, 8> Mask(NumElems, -1);
5564 for (unsigned i = 0; i != NumElems; ++i) {
5565 unsigned Opc = Op.getOperand(i).getOpcode();
5567 if (Opc == ISD::UNDEF)
5570 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5571 // Quit if more than 1 elements need inserting.
5572 if (InsertIndices.size() > 1)
5575 InsertIndices.push_back(i);
5579 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5580 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5582 // Quit if extracted from vector of different type.
5583 if (ExtractedFromVec.getValueType() != VT)
5586 // Quit if non-constant index.
5587 if (!isa<ConstantSDNode>(ExtIdx))
5590 if (VecIn1.getNode() == 0)
5591 VecIn1 = ExtractedFromVec;
5592 else if (VecIn1 != ExtractedFromVec) {
5593 if (VecIn2.getNode() == 0)
5594 VecIn2 = ExtractedFromVec;
5595 else if (VecIn2 != ExtractedFromVec)
5596 // Quit if more than 2 vectors to shuffle
5600 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5602 if (ExtractedFromVec == VecIn1)
5604 else if (ExtractedFromVec == VecIn2)
5605 Mask[i] = Idx + NumElems;
5608 if (VecIn1.getNode() == 0)
5611 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5612 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5613 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5614 unsigned Idx = InsertIndices[i];
5615 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5616 DAG.getIntPtrConstant(Idx));
5622 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5624 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5626 MVT VT = Op.getSimpleValueType();
5627 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5628 "Unexpected type in LowerBUILD_VECTORvXi1!");
5631 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5632 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5633 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5634 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5635 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5636 Ops, VT.getVectorNumElements());
5639 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5640 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5641 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5642 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5643 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5644 Ops, VT.getVectorNumElements());
5647 bool AllContants = true;
5648 uint64_t Immediate = 0;
5649 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5650 SDValue In = Op.getOperand(idx);
5651 if (In.getOpcode() == ISD::UNDEF)
5653 if (!isa<ConstantSDNode>(In)) {
5654 AllContants = false;
5657 if (cast<ConstantSDNode>(In)->getZExtValue())
5658 Immediate |= (1ULL << idx);
5662 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5663 DAG.getConstant(Immediate, MVT::i16));
5664 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5665 DAG.getIntPtrConstant(0));
5668 if (!isSplatVector(Op.getNode()))
5669 llvm_unreachable("Unsupported predicate operation");
5671 SDValue In = Op.getOperand(0);
5672 SDValue EFLAGS, X86CC;
5673 if (In.getOpcode() == ISD::SETCC) {
5674 SDValue Op0 = In.getOperand(0);
5675 SDValue Op1 = In.getOperand(1);
5676 ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5677 bool isFP = Op1.getValueType().isFloatingPoint();
5678 unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5680 assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5682 X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5683 EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5684 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5685 } else if (In.getOpcode() == X86ISD::SETCC) {
5686 X86CC = In.getOperand(0);
5687 EFLAGS = In.getOperand(1);
5696 // res = allOnes ### CMOVNE -1, %res
5699 MVT InVT = In.getSimpleValueType();
5700 SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5701 EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5702 X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5705 if (VT == MVT::v16i1) {
5706 SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5707 SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5708 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5709 Cst0, Cst1, X86CC, EFLAGS);
5710 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5713 if (VT == MVT::v8i1) {
5714 SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5715 SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5716 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5717 Cst0, Cst1, X86CC, EFLAGS);
5718 CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5719 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5721 llvm_unreachable("Unsupported predicate operation");
5725 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5728 MVT VT = Op.getSimpleValueType();
5729 MVT ExtVT = VT.getVectorElementType();
5730 unsigned NumElems = Op.getNumOperands();
5732 // Generate vectors for predicate vectors.
5733 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5734 return LowerBUILD_VECTORvXi1(Op, DAG);
5736 // Vectors containing all zeros can be matched by pxor and xorps later
5737 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5738 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5739 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5740 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5743 return getZeroVector(VT, Subtarget, DAG, dl);
5746 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5747 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5748 // vpcmpeqd on 256-bit vectors.
5749 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5750 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5753 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5756 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5757 if (Broadcast.getNode())
5760 unsigned EVTBits = ExtVT.getSizeInBits();
5762 unsigned NumZero = 0;
5763 unsigned NumNonZero = 0;
5764 unsigned NonZeros = 0;
5765 bool IsAllConstants = true;
5766 SmallSet<SDValue, 8> Values;
5767 for (unsigned i = 0; i < NumElems; ++i) {
5768 SDValue Elt = Op.getOperand(i);
5769 if (Elt.getOpcode() == ISD::UNDEF)
5772 if (Elt.getOpcode() != ISD::Constant &&
5773 Elt.getOpcode() != ISD::ConstantFP)
5774 IsAllConstants = false;
5775 if (X86::isZeroNode(Elt))
5778 NonZeros |= (1 << i);
5783 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5784 if (NumNonZero == 0)
5785 return DAG.getUNDEF(VT);
5787 // Special case for single non-zero, non-undef, element.
5788 if (NumNonZero == 1) {
5789 unsigned Idx = countTrailingZeros(NonZeros);
5790 SDValue Item = Op.getOperand(Idx);
5792 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5793 // the value are obviously zero, truncate the value to i32 and do the
5794 // insertion that way. Only do this if the value is non-constant or if the
5795 // value is a constant being inserted into element 0. It is cheaper to do
5796 // a constant pool load than it is to do a movd + shuffle.
5797 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5798 (!IsAllConstants || Idx == 0)) {
5799 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5801 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5802 EVT VecVT = MVT::v4i32;
5803 unsigned VecElts = 4;
5805 // Truncate the value (which may itself be a constant) to i32, and
5806 // convert it to a vector with movd (S2V+shuffle to zero extend).
5807 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5808 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5809 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5811 // Now we have our 32-bit value zero extended in the low element of
5812 // a vector. If Idx != 0, swizzle it into place.
5814 SmallVector<int, 4> Mask;
5815 Mask.push_back(Idx);
5816 for (unsigned i = 1; i != VecElts; ++i)
5818 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5821 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5825 // If we have a constant or non-constant insertion into the low element of
5826 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5827 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5828 // depending on what the source datatype is.
5831 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5833 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5834 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5835 if (VT.is256BitVector()) {
5836 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5837 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5838 Item, DAG.getIntPtrConstant(0));
5840 assert(VT.is128BitVector() && "Expected an SSE value type!");
5841 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5842 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5843 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5846 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5847 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5848 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5849 if (VT.is256BitVector()) {
5850 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5851 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5853 assert(VT.is128BitVector() && "Expected an SSE value type!");
5854 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5856 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5860 // Is it a vector logical left shift?
5861 if (NumElems == 2 && Idx == 1 &&
5862 X86::isZeroNode(Op.getOperand(0)) &&
5863 !X86::isZeroNode(Op.getOperand(1))) {
5864 unsigned NumBits = VT.getSizeInBits();
5865 return getVShift(true, VT,
5866 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5867 VT, Op.getOperand(1)),
5868 NumBits/2, DAG, *this, dl);
5871 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5874 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5875 // is a non-constant being inserted into an element other than the low one,
5876 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5877 // movd/movss) to move this into the low element, then shuffle it into
5879 if (EVTBits == 32) {
5880 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5882 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5883 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5884 SmallVector<int, 8> MaskVec;
5885 for (unsigned i = 0; i != NumElems; ++i)
5886 MaskVec.push_back(i == Idx ? 0 : 1);
5887 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5891 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5892 if (Values.size() == 1) {
5893 if (EVTBits == 32) {
5894 // Instead of a shuffle like this:
5895 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5896 // Check if it's possible to issue this instead.
5897 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5898 unsigned Idx = countTrailingZeros(NonZeros);
5899 SDValue Item = Op.getOperand(Idx);
5900 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5901 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5906 // A vector full of immediates; various special cases are already
5907 // handled, so this is best done with a single constant-pool load.
5911 // For AVX-length vectors, build the individual 128-bit pieces and use
5912 // shuffles to put them in place.
5913 if (VT.is256BitVector()) {
5914 SmallVector<SDValue, 32> V;
5915 for (unsigned i = 0; i != NumElems; ++i)
5916 V.push_back(Op.getOperand(i));
5918 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5920 // Build both the lower and upper subvector.
5921 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5922 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5925 // Recreate the wider vector with the lower and upper part.
5926 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5929 // Let legalizer expand 2-wide build_vectors.
5930 if (EVTBits == 64) {
5931 if (NumNonZero == 1) {
5932 // One half is zero or undef.
5933 unsigned Idx = countTrailingZeros(NonZeros);
5934 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5935 Op.getOperand(Idx));
5936 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5941 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5942 if (EVTBits == 8 && NumElems == 16) {
5943 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5945 if (V.getNode()) return V;
5948 if (EVTBits == 16 && NumElems == 8) {
5949 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5951 if (V.getNode()) return V;
5954 // If element VT is == 32 bits, turn it into a number of shuffles.
5955 SmallVector<SDValue, 8> V(NumElems);
5956 if (NumElems == 4 && NumZero > 0) {
5957 for (unsigned i = 0; i < 4; ++i) {
5958 bool isZero = !(NonZeros & (1 << i));
5960 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5962 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5965 for (unsigned i = 0; i < 2; ++i) {
5966 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5969 V[i] = V[i*2]; // Must be a zero vector.
5972 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5975 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5978 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5983 bool Reverse1 = (NonZeros & 0x3) == 2;
5984 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5988 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5989 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5991 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5994 if (Values.size() > 1 && VT.is128BitVector()) {
5995 // Check for a build vector of consecutive loads.
5996 for (unsigned i = 0; i < NumElems; ++i)
5997 V[i] = Op.getOperand(i);
5999 // Check for elements which are consecutive loads.
6000 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
6004 // Check for a build vector from mostly shuffle plus few inserting.
6005 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6009 // For SSE 4.1, use insertps to put the high elements into the low element.
6010 if (getSubtarget()->hasSSE41()) {
6012 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6013 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6015 Result = DAG.getUNDEF(VT);
6017 for (unsigned i = 1; i < NumElems; ++i) {
6018 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6019 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6020 Op.getOperand(i), DAG.getIntPtrConstant(i));
6025 // Otherwise, expand into a number of unpckl*, start by extending each of
6026 // our (non-undef) elements to the full vector width with the element in the
6027 // bottom slot of the vector (which generates no code for SSE).
6028 for (unsigned i = 0; i < NumElems; ++i) {
6029 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6030 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6032 V[i] = DAG.getUNDEF(VT);
6035 // Next, we iteratively mix elements, e.g. for v4f32:
6036 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6037 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6038 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6039 unsigned EltStride = NumElems >> 1;
6040 while (EltStride != 0) {
6041 for (unsigned i = 0; i < EltStride; ++i) {
6042 // If V[i+EltStride] is undef and this is the first round of mixing,
6043 // then it is safe to just drop this shuffle: V[i] is already in the
6044 // right place, the one element (since it's the first round) being
6045 // inserted as undef can be dropped. This isn't safe for successive
6046 // rounds because they will permute elements within both vectors.
6047 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6048 EltStride == NumElems/2)
6051 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6060 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6061 // to create 256-bit vectors from two other 128-bit ones.
6062 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6064 MVT ResVT = Op.getSimpleValueType();
6066 assert((ResVT.is256BitVector() ||
6067 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6069 SDValue V1 = Op.getOperand(0);
6070 SDValue V2 = Op.getOperand(1);
6071 unsigned NumElems = ResVT.getVectorNumElements();
6072 if(ResVT.is256BitVector())
6073 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6075 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6078 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6079 assert(Op.getNumOperands() == 2);
6081 // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
6082 // from two other 128-bit ones.
6083 return LowerAVXCONCAT_VECTORS(Op, DAG);
6086 // Try to lower a shuffle node into a simple blend instruction.
6088 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6089 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6090 SDValue V1 = SVOp->getOperand(0);
6091 SDValue V2 = SVOp->getOperand(1);
6093 MVT VT = SVOp->getSimpleValueType(0);
6094 MVT EltVT = VT.getVectorElementType();
6095 unsigned NumElems = VT.getVectorNumElements();
6097 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6099 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6102 // Check the mask for BLEND and build the value.
6103 unsigned MaskValue = 0;
6104 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6105 unsigned NumLanes = (NumElems-1)/8 + 1;
6106 unsigned NumElemsInLane = NumElems / NumLanes;
6108 // Blend for v16i16 should be symetric for the both lanes.
6109 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6111 int SndLaneEltIdx = (NumLanes == 2) ?
6112 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6113 int EltIdx = SVOp->getMaskElt(i);
6115 if ((EltIdx < 0 || EltIdx == (int)i) &&
6116 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6119 if (((unsigned)EltIdx == (i + NumElems)) &&
6120 (SndLaneEltIdx < 0 ||
6121 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6122 MaskValue |= (1<<i);
6127 // Convert i32 vectors to floating point if it is not AVX2.
6128 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6130 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6131 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6133 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6134 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6137 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6138 DAG.getConstant(MaskValue, MVT::i32));
6139 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6142 // v8i16 shuffles - Prefer shuffles in the following order:
6143 // 1. [all] pshuflw, pshufhw, optional move
6144 // 2. [ssse3] 1 x pshufb
6145 // 3. [ssse3] 2 x pshufb + 1 x por
6146 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6148 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6149 SelectionDAG &DAG) {
6150 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6151 SDValue V1 = SVOp->getOperand(0);
6152 SDValue V2 = SVOp->getOperand(1);
6154 SmallVector<int, 8> MaskVals;
6156 // Determine if more than 1 of the words in each of the low and high quadwords
6157 // of the result come from the same quadword of one of the two inputs. Undef
6158 // mask values count as coming from any quadword, for better codegen.
6159 unsigned LoQuad[] = { 0, 0, 0, 0 };
6160 unsigned HiQuad[] = { 0, 0, 0, 0 };
6161 std::bitset<4> InputQuads;
6162 for (unsigned i = 0; i < 8; ++i) {
6163 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6164 int EltIdx = SVOp->getMaskElt(i);
6165 MaskVals.push_back(EltIdx);
6174 InputQuads.set(EltIdx / 4);
6177 int BestLoQuad = -1;
6178 unsigned MaxQuad = 1;
6179 for (unsigned i = 0; i < 4; ++i) {
6180 if (LoQuad[i] > MaxQuad) {
6182 MaxQuad = LoQuad[i];
6186 int BestHiQuad = -1;
6188 for (unsigned i = 0; i < 4; ++i) {
6189 if (HiQuad[i] > MaxQuad) {
6191 MaxQuad = HiQuad[i];
6195 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6196 // of the two input vectors, shuffle them into one input vector so only a
6197 // single pshufb instruction is necessary. If There are more than 2 input
6198 // quads, disable the next transformation since it does not help SSSE3.
6199 bool V1Used = InputQuads[0] || InputQuads[1];
6200 bool V2Used = InputQuads[2] || InputQuads[3];
6201 if (Subtarget->hasSSSE3()) {
6202 if (InputQuads.count() == 2 && V1Used && V2Used) {
6203 BestLoQuad = InputQuads[0] ? 0 : 1;
6204 BestHiQuad = InputQuads[2] ? 2 : 3;
6206 if (InputQuads.count() > 2) {
6212 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6213 // the shuffle mask. If a quad is scored as -1, that means that it contains
6214 // words from all 4 input quadwords.
6216 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6218 BestLoQuad < 0 ? 0 : BestLoQuad,
6219 BestHiQuad < 0 ? 1 : BestHiQuad
6221 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6222 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6223 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6224 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6226 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6227 // source words for the shuffle, to aid later transformations.
6228 bool AllWordsInNewV = true;
6229 bool InOrder[2] = { true, true };
6230 for (unsigned i = 0; i != 8; ++i) {
6231 int idx = MaskVals[i];
6233 InOrder[i/4] = false;
6234 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6236 AllWordsInNewV = false;
6240 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6241 if (AllWordsInNewV) {
6242 for (int i = 0; i != 8; ++i) {
6243 int idx = MaskVals[i];
6246 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6247 if ((idx != i) && idx < 4)
6249 if ((idx != i) && idx > 3)
6258 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6259 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6260 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6261 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6262 unsigned TargetMask = 0;
6263 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6264 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6265 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6266 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6267 getShufflePSHUFLWImmediate(SVOp);
6268 V1 = NewV.getOperand(0);
6269 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6273 // Promote splats to a larger type which usually leads to more efficient code.
6274 // FIXME: Is this true if pshufb is available?
6275 if (SVOp->isSplat())
6276 return PromoteSplat(SVOp, DAG);
6278 // If we have SSSE3, and all words of the result are from 1 input vector,
6279 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6280 // is present, fall back to case 4.
6281 if (Subtarget->hasSSSE3()) {
6282 SmallVector<SDValue,16> pshufbMask;
6284 // If we have elements from both input vectors, set the high bit of the
6285 // shuffle mask element to zero out elements that come from V2 in the V1
6286 // mask, and elements that come from V1 in the V2 mask, so that the two
6287 // results can be OR'd together.
6288 bool TwoInputs = V1Used && V2Used;
6289 for (unsigned i = 0; i != 8; ++i) {
6290 int EltIdx = MaskVals[i] * 2;
6291 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6292 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6293 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6294 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6296 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6297 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6298 DAG.getNode(ISD::BUILD_VECTOR, dl,
6299 MVT::v16i8, &pshufbMask[0], 16));
6301 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6303 // Calculate the shuffle mask for the second input, shuffle it, and
6304 // OR it with the first shuffled input.
6306 for (unsigned i = 0; i != 8; ++i) {
6307 int EltIdx = MaskVals[i] * 2;
6308 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6309 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6310 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6311 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6313 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6314 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6315 DAG.getNode(ISD::BUILD_VECTOR, dl,
6316 MVT::v16i8, &pshufbMask[0], 16));
6317 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6318 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6321 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6322 // and update MaskVals with new element order.
6323 std::bitset<8> InOrder;
6324 if (BestLoQuad >= 0) {
6325 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6326 for (int i = 0; i != 4; ++i) {
6327 int idx = MaskVals[i];
6330 } else if ((idx / 4) == BestLoQuad) {
6335 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6338 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6339 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6340 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6342 getShufflePSHUFLWImmediate(SVOp), DAG);
6346 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6347 // and update MaskVals with the new element order.
6348 if (BestHiQuad >= 0) {
6349 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6350 for (unsigned i = 4; i != 8; ++i) {
6351 int idx = MaskVals[i];
6354 } else if ((idx / 4) == BestHiQuad) {
6355 MaskV[i] = (idx & 3) + 4;
6359 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6362 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6363 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6364 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6366 getShufflePSHUFHWImmediate(SVOp), DAG);
6370 // In case BestHi & BestLo were both -1, which means each quadword has a word
6371 // from each of the four input quadwords, calculate the InOrder bitvector now
6372 // before falling through to the insert/extract cleanup.
6373 if (BestLoQuad == -1 && BestHiQuad == -1) {
6375 for (int i = 0; i != 8; ++i)
6376 if (MaskVals[i] < 0 || MaskVals[i] == i)
6380 // The other elements are put in the right place using pextrw and pinsrw.
6381 for (unsigned i = 0; i != 8; ++i) {
6384 int EltIdx = MaskVals[i];
6387 SDValue ExtOp = (EltIdx < 8) ?
6388 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6389 DAG.getIntPtrConstant(EltIdx)) :
6390 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6391 DAG.getIntPtrConstant(EltIdx - 8));
6392 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6393 DAG.getIntPtrConstant(i));
6398 // v16i8 shuffles - Prefer shuffles in the following order:
6399 // 1. [ssse3] 1 x pshufb
6400 // 2. [ssse3] 2 x pshufb + 1 x por
6401 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6402 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6403 const X86Subtarget* Subtarget,
6404 SelectionDAG &DAG) {
6405 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6406 SDValue V1 = SVOp->getOperand(0);
6407 SDValue V2 = SVOp->getOperand(1);
6409 ArrayRef<int> MaskVals = SVOp->getMask();
6411 // Promote splats to a larger type which usually leads to more efficient code.
6412 // FIXME: Is this true if pshufb is available?
6413 if (SVOp->isSplat())
6414 return PromoteSplat(SVOp, DAG);
6416 // If we have SSSE3, case 1 is generated when all result bytes come from
6417 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6418 // present, fall back to case 3.
6420 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6421 if (Subtarget->hasSSSE3()) {
6422 SmallVector<SDValue,16> pshufbMask;
6424 // If all result elements are from one input vector, then only translate
6425 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6427 // Otherwise, we have elements from both input vectors, and must zero out
6428 // elements that come from V2 in the first mask, and V1 in the second mask
6429 // so that we can OR them together.
6430 for (unsigned i = 0; i != 16; ++i) {
6431 int EltIdx = MaskVals[i];
6432 if (EltIdx < 0 || EltIdx >= 16)
6434 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6436 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6437 DAG.getNode(ISD::BUILD_VECTOR, dl,
6438 MVT::v16i8, &pshufbMask[0], 16));
6440 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6441 // the 2nd operand if it's undefined or zero.
6442 if (V2.getOpcode() == ISD::UNDEF ||
6443 ISD::isBuildVectorAllZeros(V2.getNode()))
6446 // Calculate the shuffle mask for the second input, shuffle it, and
6447 // OR it with the first shuffled input.
6449 for (unsigned i = 0; i != 16; ++i) {
6450 int EltIdx = MaskVals[i];
6451 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6452 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6454 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6455 DAG.getNode(ISD::BUILD_VECTOR, dl,
6456 MVT::v16i8, &pshufbMask[0], 16));
6457 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6460 // No SSSE3 - Calculate in place words and then fix all out of place words
6461 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6462 // the 16 different words that comprise the two doublequadword input vectors.
6463 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6464 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6466 for (int i = 0; i != 8; ++i) {
6467 int Elt0 = MaskVals[i*2];
6468 int Elt1 = MaskVals[i*2+1];
6470 // This word of the result is all undef, skip it.
6471 if (Elt0 < 0 && Elt1 < 0)
6474 // This word of the result is already in the correct place, skip it.
6475 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6478 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6479 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6482 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6483 // using a single extract together, load it and store it.
6484 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6485 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6486 DAG.getIntPtrConstant(Elt1 / 2));
6487 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6488 DAG.getIntPtrConstant(i));
6492 // If Elt1 is defined, extract it from the appropriate source. If the
6493 // source byte is not also odd, shift the extracted word left 8 bits
6494 // otherwise clear the bottom 8 bits if we need to do an or.
6496 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6497 DAG.getIntPtrConstant(Elt1 / 2));
6498 if ((Elt1 & 1) == 0)
6499 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6501 TLI.getShiftAmountTy(InsElt.getValueType())));
6503 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6504 DAG.getConstant(0xFF00, MVT::i16));
6506 // If Elt0 is defined, extract it from the appropriate source. If the
6507 // source byte is not also even, shift the extracted word right 8 bits. If
6508 // Elt1 was also defined, OR the extracted values together before
6509 // inserting them in the result.
6511 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6512 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6513 if ((Elt0 & 1) != 0)
6514 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6516 TLI.getShiftAmountTy(InsElt0.getValueType())));
6518 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6519 DAG.getConstant(0x00FF, MVT::i16));
6520 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6523 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6524 DAG.getIntPtrConstant(i));
6526 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6529 // v32i8 shuffles - Translate to VPSHUFB if possible.
6531 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6532 const X86Subtarget *Subtarget,
6533 SelectionDAG &DAG) {
6534 MVT VT = SVOp->getSimpleValueType(0);
6535 SDValue V1 = SVOp->getOperand(0);
6536 SDValue V2 = SVOp->getOperand(1);
6538 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6540 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6541 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6542 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6544 // VPSHUFB may be generated if
6545 // (1) one of input vector is undefined or zeroinitializer.
6546 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6547 // And (2) the mask indexes don't cross the 128-bit lane.
6548 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6549 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6552 if (V1IsAllZero && !V2IsAllZero) {
6553 CommuteVectorShuffleMask(MaskVals, 32);
6556 SmallVector<SDValue, 32> pshufbMask;
6557 for (unsigned i = 0; i != 32; i++) {
6558 int EltIdx = MaskVals[i];
6559 if (EltIdx < 0 || EltIdx >= 32)
6562 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6563 // Cross lane is not allowed.
6567 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6569 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6570 DAG.getNode(ISD::BUILD_VECTOR, dl,
6571 MVT::v32i8, &pshufbMask[0], 32));
6574 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6575 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6576 /// done when every pair / quad of shuffle mask elements point to elements in
6577 /// the right sequence. e.g.
6578 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6580 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6581 SelectionDAG &DAG) {
6582 MVT VT = SVOp->getSimpleValueType(0);
6584 unsigned NumElems = VT.getVectorNumElements();
6587 switch (VT.SimpleTy) {
6588 default: llvm_unreachable("Unexpected!");
6589 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6590 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6591 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6592 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6593 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6594 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6597 SmallVector<int, 8> MaskVec;
6598 for (unsigned i = 0; i != NumElems; i += Scale) {
6600 for (unsigned j = 0; j != Scale; ++j) {
6601 int EltIdx = SVOp->getMaskElt(i+j);
6605 StartIdx = (EltIdx / Scale);
6606 if (EltIdx != (int)(StartIdx*Scale + j))
6609 MaskVec.push_back(StartIdx);
6612 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6613 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6614 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6617 /// getVZextMovL - Return a zero-extending vector move low node.
6619 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6620 SDValue SrcOp, SelectionDAG &DAG,
6621 const X86Subtarget *Subtarget, SDLoc dl) {
6622 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6623 LoadSDNode *LD = NULL;
6624 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6625 LD = dyn_cast<LoadSDNode>(SrcOp);
6627 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6629 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6630 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6631 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6632 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6633 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6635 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6636 return DAG.getNode(ISD::BITCAST, dl, VT,
6637 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6638 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6646 return DAG.getNode(ISD::BITCAST, dl, VT,
6647 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6648 DAG.getNode(ISD::BITCAST, dl,
6652 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6653 /// which could not be matched by any known target speficic shuffle
6655 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6657 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6658 if (NewOp.getNode())
6661 MVT VT = SVOp->getSimpleValueType(0);
6663 unsigned NumElems = VT.getVectorNumElements();
6664 unsigned NumLaneElems = NumElems / 2;
6667 MVT EltVT = VT.getVectorElementType();
6668 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6671 SmallVector<int, 16> Mask;
6672 for (unsigned l = 0; l < 2; ++l) {
6673 // Build a shuffle mask for the output, discovering on the fly which
6674 // input vectors to use as shuffle operands (recorded in InputUsed).
6675 // If building a suitable shuffle vector proves too hard, then bail
6676 // out with UseBuildVector set.
6677 bool UseBuildVector = false;
6678 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6679 unsigned LaneStart = l * NumLaneElems;
6680 for (unsigned i = 0; i != NumLaneElems; ++i) {
6681 // The mask element. This indexes into the input.
6682 int Idx = SVOp->getMaskElt(i+LaneStart);
6684 // the mask element does not index into any input vector.
6689 // The input vector this mask element indexes into.
6690 int Input = Idx / NumLaneElems;
6692 // Turn the index into an offset from the start of the input vector.
6693 Idx -= Input * NumLaneElems;
6695 // Find or create a shuffle vector operand to hold this input.
6697 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6698 if (InputUsed[OpNo] == Input)
6699 // This input vector is already an operand.
6701 if (InputUsed[OpNo] < 0) {
6702 // Create a new operand for this input vector.
6703 InputUsed[OpNo] = Input;
6708 if (OpNo >= array_lengthof(InputUsed)) {
6709 // More than two input vectors used! Give up on trying to create a
6710 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6711 UseBuildVector = true;
6715 // Add the mask index for the new shuffle vector.
6716 Mask.push_back(Idx + OpNo * NumLaneElems);
6719 if (UseBuildVector) {
6720 SmallVector<SDValue, 16> SVOps;
6721 for (unsigned i = 0; i != NumLaneElems; ++i) {
6722 // The mask element. This indexes into the input.
6723 int Idx = SVOp->getMaskElt(i+LaneStart);
6725 SVOps.push_back(DAG.getUNDEF(EltVT));
6729 // The input vector this mask element indexes into.
6730 int Input = Idx / NumElems;
6732 // Turn the index into an offset from the start of the input vector.
6733 Idx -= Input * NumElems;
6735 // Extract the vector element by hand.
6736 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6737 SVOp->getOperand(Input),
6738 DAG.getIntPtrConstant(Idx)));
6741 // Construct the output using a BUILD_VECTOR.
6742 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6744 } else if (InputUsed[0] < 0) {
6745 // No input vectors were used! The result is undefined.
6746 Output[l] = DAG.getUNDEF(NVT);
6748 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6749 (InputUsed[0] % 2) * NumLaneElems,
6751 // If only one input was used, use an undefined vector for the other.
6752 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6753 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6754 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6755 // At least one input vector was used. Create a new shuffle vector.
6756 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6762 // Concatenate the result back
6763 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6766 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6767 /// 4 elements, and match them with several different shuffle types.
6769 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6770 SDValue V1 = SVOp->getOperand(0);
6771 SDValue V2 = SVOp->getOperand(1);
6773 MVT VT = SVOp->getSimpleValueType(0);
6775 assert(VT.is128BitVector() && "Unsupported vector size");
6777 std::pair<int, int> Locs[4];
6778 int Mask1[] = { -1, -1, -1, -1 };
6779 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6783 for (unsigned i = 0; i != 4; ++i) {
6784 int Idx = PermMask[i];
6786 Locs[i] = std::make_pair(-1, -1);
6788 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6790 Locs[i] = std::make_pair(0, NumLo);
6794 Locs[i] = std::make_pair(1, NumHi);
6796 Mask1[2+NumHi] = Idx;
6802 if (NumLo <= 2 && NumHi <= 2) {
6803 // If no more than two elements come from either vector. This can be
6804 // implemented with two shuffles. First shuffle gather the elements.
6805 // The second shuffle, which takes the first shuffle as both of its
6806 // vector operands, put the elements into the right order.
6807 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6809 int Mask2[] = { -1, -1, -1, -1 };
6811 for (unsigned i = 0; i != 4; ++i)
6812 if (Locs[i].first != -1) {
6813 unsigned Idx = (i < 2) ? 0 : 4;
6814 Idx += Locs[i].first * 2 + Locs[i].second;
6818 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6821 if (NumLo == 3 || NumHi == 3) {
6822 // Otherwise, we must have three elements from one vector, call it X, and
6823 // one element from the other, call it Y. First, use a shufps to build an
6824 // intermediate vector with the one element from Y and the element from X
6825 // that will be in the same half in the final destination (the indexes don't
6826 // matter). Then, use a shufps to build the final vector, taking the half
6827 // containing the element from Y from the intermediate, and the other half
6830 // Normalize it so the 3 elements come from V1.
6831 CommuteVectorShuffleMask(PermMask, 4);
6835 // Find the element from V2.
6837 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6838 int Val = PermMask[HiIndex];
6845 Mask1[0] = PermMask[HiIndex];
6847 Mask1[2] = PermMask[HiIndex^1];
6849 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6852 Mask1[0] = PermMask[0];
6853 Mask1[1] = PermMask[1];
6854 Mask1[2] = HiIndex & 1 ? 6 : 4;
6855 Mask1[3] = HiIndex & 1 ? 4 : 6;
6856 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6859 Mask1[0] = HiIndex & 1 ? 2 : 0;
6860 Mask1[1] = HiIndex & 1 ? 0 : 2;
6861 Mask1[2] = PermMask[2];
6862 Mask1[3] = PermMask[3];
6867 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6870 // Break it into (shuffle shuffle_hi, shuffle_lo).
6871 int LoMask[] = { -1, -1, -1, -1 };
6872 int HiMask[] = { -1, -1, -1, -1 };
6874 int *MaskPtr = LoMask;
6875 unsigned MaskIdx = 0;
6878 for (unsigned i = 0; i != 4; ++i) {
6885 int Idx = PermMask[i];
6887 Locs[i] = std::make_pair(-1, -1);
6888 } else if (Idx < 4) {
6889 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6890 MaskPtr[LoIdx] = Idx;
6893 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6894 MaskPtr[HiIdx] = Idx;
6899 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6900 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6901 int MaskOps[] = { -1, -1, -1, -1 };
6902 for (unsigned i = 0; i != 4; ++i)
6903 if (Locs[i].first != -1)
6904 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6905 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6908 static bool MayFoldVectorLoad(SDValue V) {
6909 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6910 V = V.getOperand(0);
6912 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6913 V = V.getOperand(0);
6914 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6915 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6916 // BUILD_VECTOR (load), undef
6917 V = V.getOperand(0);
6919 return MayFoldLoad(V);
6923 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6924 MVT VT = Op.getSimpleValueType();
6926 // Canonizalize to v2f64.
6927 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6928 return DAG.getNode(ISD::BITCAST, dl, VT,
6929 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6934 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6936 SDValue V1 = Op.getOperand(0);
6937 SDValue V2 = Op.getOperand(1);
6938 MVT VT = Op.getSimpleValueType();
6940 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6942 if (HasSSE2 && VT == MVT::v2f64)
6943 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6945 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6946 return DAG.getNode(ISD::BITCAST, dl, VT,
6947 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6948 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6949 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6953 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6954 SDValue V1 = Op.getOperand(0);
6955 SDValue V2 = Op.getOperand(1);
6956 MVT VT = Op.getSimpleValueType();
6958 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6959 "unsupported shuffle type");
6961 if (V2.getOpcode() == ISD::UNDEF)
6965 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6969 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6970 SDValue V1 = Op.getOperand(0);
6971 SDValue V2 = Op.getOperand(1);
6972 MVT VT = Op.getSimpleValueType();
6973 unsigned NumElems = VT.getVectorNumElements();
6975 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6976 // operand of these instructions is only memory, so check if there's a
6977 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6979 bool CanFoldLoad = false;
6981 // Trivial case, when V2 comes from a load.
6982 if (MayFoldVectorLoad(V2))
6985 // When V1 is a load, it can be folded later into a store in isel, example:
6986 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6988 // (MOVLPSmr addr:$src1, VR128:$src2)
6989 // So, recognize this potential and also use MOVLPS or MOVLPD
6990 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6993 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6995 if (HasSSE2 && NumElems == 2)
6996 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6999 // If we don't care about the second element, proceed to use movss.
7000 if (SVOp->getMaskElt(1) != -1)
7001 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7004 // movl and movlp will both match v2i64, but v2i64 is never matched by
7005 // movl earlier because we make it strict to avoid messing with the movlp load
7006 // folding logic (see the code above getMOVLP call). Match it here then,
7007 // this is horrible, but will stay like this until we move all shuffle
7008 // matching to x86 specific nodes. Note that for the 1st condition all
7009 // types are matched with movsd.
7011 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7012 // as to remove this logic from here, as much as possible
7013 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7014 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7015 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7018 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7020 // Invert the operand order and use SHUFPS to match it.
7021 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7022 getShuffleSHUFImmediate(SVOp), DAG);
7025 // Reduce a vector shuffle to zext.
7026 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7027 SelectionDAG &DAG) {
7028 // PMOVZX is only available from SSE41.
7029 if (!Subtarget->hasSSE41())
7032 MVT VT = Op.getSimpleValueType();
7034 // Only AVX2 support 256-bit vector integer extending.
7035 if (!Subtarget->hasInt256() && VT.is256BitVector())
7038 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7040 SDValue V1 = Op.getOperand(0);
7041 SDValue V2 = Op.getOperand(1);
7042 unsigned NumElems = VT.getVectorNumElements();
7044 // Extending is an unary operation and the element type of the source vector
7045 // won't be equal to or larger than i64.
7046 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7047 VT.getVectorElementType() == MVT::i64)
7050 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7051 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7052 while ((1U << Shift) < NumElems) {
7053 if (SVOp->getMaskElt(1U << Shift) == 1)
7056 // The maximal ratio is 8, i.e. from i8 to i64.
7061 // Check the shuffle mask.
7062 unsigned Mask = (1U << Shift) - 1;
7063 for (unsigned i = 0; i != NumElems; ++i) {
7064 int EltIdx = SVOp->getMaskElt(i);
7065 if ((i & Mask) != 0 && EltIdx != -1)
7067 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7071 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7072 MVT NeVT = MVT::getIntegerVT(NBits);
7073 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7075 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7078 // Simplify the operand as it's prepared to be fed into shuffle.
7079 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7080 if (V1.getOpcode() == ISD::BITCAST &&
7081 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7082 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7083 V1.getOperand(0).getOperand(0)
7084 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7085 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7086 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7087 ConstantSDNode *CIdx =
7088 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7089 // If it's foldable, i.e. normal load with single use, we will let code
7090 // selection to fold it. Otherwise, we will short the conversion sequence.
7091 if (CIdx && CIdx->getZExtValue() == 0 &&
7092 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7093 MVT FullVT = V.getSimpleValueType();
7094 MVT V1VT = V1.getSimpleValueType();
7095 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7096 // The "ext_vec_elt" node is wider than the result node.
7097 // In this case we should extract subvector from V.
7098 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7099 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7100 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7101 FullVT.getVectorNumElements()/Ratio);
7102 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7103 DAG.getIntPtrConstant(0));
7105 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7109 return DAG.getNode(ISD::BITCAST, DL, VT,
7110 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7114 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7115 SelectionDAG &DAG) {
7116 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7117 MVT VT = Op.getSimpleValueType();
7119 SDValue V1 = Op.getOperand(0);
7120 SDValue V2 = Op.getOperand(1);
7122 if (isZeroShuffle(SVOp))
7123 return getZeroVector(VT, Subtarget, DAG, dl);
7125 // Handle splat operations
7126 if (SVOp->isSplat()) {
7127 // Use vbroadcast whenever the splat comes from a foldable load
7128 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7129 if (Broadcast.getNode())
7133 // Check integer expanding shuffles.
7134 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7135 if (NewOp.getNode())
7138 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7140 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7141 VT == MVT::v16i16 || VT == MVT::v32i8) {
7142 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7143 if (NewOp.getNode())
7144 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7145 } else if ((VT == MVT::v4i32 ||
7146 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7147 // FIXME: Figure out a cleaner way to do this.
7148 // Try to make use of movq to zero out the top part.
7149 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7150 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7151 if (NewOp.getNode()) {
7152 MVT NewVT = NewOp.getSimpleValueType();
7153 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7154 NewVT, true, false))
7155 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7156 DAG, Subtarget, dl);
7158 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7159 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7160 if (NewOp.getNode()) {
7161 MVT NewVT = NewOp.getSimpleValueType();
7162 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7163 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7164 DAG, Subtarget, dl);
7172 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7173 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7174 SDValue V1 = Op.getOperand(0);
7175 SDValue V2 = Op.getOperand(1);
7176 MVT VT = Op.getSimpleValueType();
7178 unsigned NumElems = VT.getVectorNumElements();
7179 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7180 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7181 bool V1IsSplat = false;
7182 bool V2IsSplat = false;
7183 bool HasSSE2 = Subtarget->hasSSE2();
7184 bool HasFp256 = Subtarget->hasFp256();
7185 bool HasInt256 = Subtarget->hasInt256();
7186 MachineFunction &MF = DAG.getMachineFunction();
7187 bool OptForSize = MF.getFunction()->getAttributes().
7188 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7190 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7192 if (V1IsUndef && V2IsUndef)
7193 return DAG.getUNDEF(VT);
7195 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7197 // Vector shuffle lowering takes 3 steps:
7199 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7200 // narrowing and commutation of operands should be handled.
7201 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7203 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7204 // so the shuffle can be broken into other shuffles and the legalizer can
7205 // try the lowering again.
7207 // The general idea is that no vector_shuffle operation should be left to
7208 // be matched during isel, all of them must be converted to a target specific
7211 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7212 // narrowing and commutation of operands should be handled. The actual code
7213 // doesn't include all of those, work in progress...
7214 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7215 if (NewOp.getNode())
7218 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7220 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7221 // unpckh_undef). Only use pshufd if speed is more important than size.
7222 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7223 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7224 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7225 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7227 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7228 V2IsUndef && MayFoldVectorLoad(V1))
7229 return getMOVDDup(Op, dl, V1, DAG);
7231 if (isMOVHLPS_v_undef_Mask(M, VT))
7232 return getMOVHighToLow(Op, dl, DAG);
7234 // Use to match splats
7235 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7236 (VT == MVT::v2f64 || VT == MVT::v2i64))
7237 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7239 if (isPSHUFDMask(M, VT)) {
7240 // The actual implementation will match the mask in the if above and then
7241 // during isel it can match several different instructions, not only pshufd
7242 // as its name says, sad but true, emulate the behavior for now...
7243 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7244 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7246 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7248 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7249 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7251 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7252 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7255 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7259 if (isPALIGNRMask(M, VT, Subtarget))
7260 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7261 getShufflePALIGNRImmediate(SVOp),
7264 // Check if this can be converted into a logical shift.
7265 bool isLeft = false;
7268 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7269 if (isShift && ShVal.hasOneUse()) {
7270 // If the shifted value has multiple uses, it may be cheaper to use
7271 // v_set0 + movlhps or movhlps, etc.
7272 MVT EltVT = VT.getVectorElementType();
7273 ShAmt *= EltVT.getSizeInBits();
7274 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7277 if (isMOVLMask(M, VT)) {
7278 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7279 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7280 if (!isMOVLPMask(M, VT)) {
7281 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7282 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7284 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7285 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7289 // FIXME: fold these into legal mask.
7290 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7291 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7293 if (isMOVHLPSMask(M, VT))
7294 return getMOVHighToLow(Op, dl, DAG);
7296 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7297 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7299 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7300 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7302 if (isMOVLPMask(M, VT))
7303 return getMOVLP(Op, dl, DAG, HasSSE2);
7305 if (ShouldXformToMOVHLPS(M, VT) ||
7306 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7307 return CommuteVectorShuffle(SVOp, DAG);
7310 // No better options. Use a vshldq / vsrldq.
7311 MVT EltVT = VT.getVectorElementType();
7312 ShAmt *= EltVT.getSizeInBits();
7313 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7316 bool Commuted = false;
7317 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7318 // 1,1,1,1 -> v8i16 though.
7319 V1IsSplat = isSplatVector(V1.getNode());
7320 V2IsSplat = isSplatVector(V2.getNode());
7322 // Canonicalize the splat or undef, if present, to be on the RHS.
7323 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7324 CommuteVectorShuffleMask(M, NumElems);
7326 std::swap(V1IsSplat, V2IsSplat);
7330 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7331 // Shuffling low element of v1 into undef, just return v1.
7334 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7335 // the instruction selector will not match, so get a canonical MOVL with
7336 // swapped operands to undo the commute.
7337 return getMOVL(DAG, dl, VT, V2, V1);
7340 if (isUNPCKLMask(M, VT, HasInt256))
7341 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7343 if (isUNPCKHMask(M, VT, HasInt256))
7344 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7347 // Normalize mask so all entries that point to V2 points to its first
7348 // element then try to match unpck{h|l} again. If match, return a
7349 // new vector_shuffle with the corrected mask.p
7350 SmallVector<int, 8> NewMask(M.begin(), M.end());
7351 NormalizeMask(NewMask, NumElems);
7352 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7353 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7354 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7355 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7359 // Commute is back and try unpck* again.
7360 // FIXME: this seems wrong.
7361 CommuteVectorShuffleMask(M, NumElems);
7363 std::swap(V1IsSplat, V2IsSplat);
7366 if (isUNPCKLMask(M, VT, HasInt256))
7367 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7369 if (isUNPCKHMask(M, VT, HasInt256))
7370 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7373 // Normalize the node to match x86 shuffle ops if needed
7374 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7375 return CommuteVectorShuffle(SVOp, DAG);
7377 // The checks below are all present in isShuffleMaskLegal, but they are
7378 // inlined here right now to enable us to directly emit target specific
7379 // nodes, and remove one by one until they don't return Op anymore.
7381 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7382 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7383 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7384 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7387 if (isPSHUFHWMask(M, VT, HasInt256))
7388 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7389 getShufflePSHUFHWImmediate(SVOp),
7392 if (isPSHUFLWMask(M, VT, HasInt256))
7393 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7394 getShufflePSHUFLWImmediate(SVOp),
7397 if (isSHUFPMask(M, VT, HasFp256))
7398 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7399 getShuffleSHUFImmediate(SVOp), DAG);
7401 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7402 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7403 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7404 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7406 //===--------------------------------------------------------------------===//
7407 // Generate target specific nodes for 128 or 256-bit shuffles only
7408 // supported in the AVX instruction set.
7411 // Handle VMOVDDUPY permutations
7412 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7413 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7415 // Handle VPERMILPS/D* permutations
7416 if (isVPERMILPMask(M, VT, HasFp256)) {
7417 if (HasInt256 && VT == MVT::v8i32)
7418 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7419 getShuffleSHUFImmediate(SVOp), DAG);
7420 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7421 getShuffleSHUFImmediate(SVOp), DAG);
7424 // Handle VPERM2F128/VPERM2I128 permutations
7425 if (isVPERM2X128Mask(M, VT, HasFp256))
7426 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7427 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7429 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7430 if (BlendOp.getNode())
7434 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7435 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7437 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7438 VT.is512BitVector()) {
7439 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7440 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7441 SmallVector<SDValue, 16> permclMask;
7442 for (unsigned i = 0; i != NumElems; ++i) {
7443 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7446 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7447 &permclMask[0], NumElems);
7449 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7450 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7451 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7452 return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7453 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7456 //===--------------------------------------------------------------------===//
7457 // Since no target specific shuffle was selected for this generic one,
7458 // lower it into other known shuffles. FIXME: this isn't true yet, but
7459 // this is the plan.
7462 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7463 if (VT == MVT::v8i16) {
7464 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7465 if (NewOp.getNode())
7469 if (VT == MVT::v16i8) {
7470 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7471 if (NewOp.getNode())
7475 if (VT == MVT::v32i8) {
7476 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7477 if (NewOp.getNode())
7481 // Handle all 128-bit wide vectors with 4 elements, and match them with
7482 // several different shuffle types.
7483 if (NumElems == 4 && VT.is128BitVector())
7484 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7486 // Handle general 256-bit shuffles
7487 if (VT.is256BitVector())
7488 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7493 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7494 MVT VT = Op.getSimpleValueType();
7497 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7500 if (VT.getSizeInBits() == 8) {
7501 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7502 Op.getOperand(0), Op.getOperand(1));
7503 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7504 DAG.getValueType(VT));
7505 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7508 if (VT.getSizeInBits() == 16) {
7509 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7510 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7512 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7513 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7514 DAG.getNode(ISD::BITCAST, dl,
7518 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7519 Op.getOperand(0), Op.getOperand(1));
7520 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7521 DAG.getValueType(VT));
7522 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7525 if (VT == MVT::f32) {
7526 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7527 // the result back to FR32 register. It's only worth matching if the
7528 // result has a single use which is a store or a bitcast to i32. And in
7529 // the case of a store, it's not worth it if the index is a constant 0,
7530 // because a MOVSSmr can be used instead, which is smaller and faster.
7531 if (!Op.hasOneUse())
7533 SDNode *User = *Op.getNode()->use_begin();
7534 if ((User->getOpcode() != ISD::STORE ||
7535 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7536 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7537 (User->getOpcode() != ISD::BITCAST ||
7538 User->getValueType(0) != MVT::i32))
7540 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7541 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7544 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7547 if (VT == MVT::i32 || VT == MVT::i64) {
7548 // ExtractPS/pextrq works with constant index.
7549 if (isa<ConstantSDNode>(Op.getOperand(1)))
7556 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7557 SelectionDAG &DAG) const {
7559 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7562 SDValue Vec = Op.getOperand(0);
7563 MVT VecVT = Vec.getSimpleValueType();
7565 // If this is a 256-bit vector result, first extract the 128-bit vector and
7566 // then extract the element from the 128-bit vector.
7567 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7568 SDValue Idx = Op.getOperand(1);
7569 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7571 // Get the 128-bit vector.
7572 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7573 MVT EltVT = VecVT.getVectorElementType();
7575 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7577 //if (IdxVal >= NumElems/2)
7578 // IdxVal -= NumElems/2;
7579 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7580 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7581 DAG.getConstant(IdxVal, MVT::i32));
7584 assert(VecVT.is128BitVector() && "Unexpected vector length");
7586 if (Subtarget->hasSSE41()) {
7587 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7592 MVT VT = Op.getSimpleValueType();
7593 // TODO: handle v16i8.
7594 if (VT.getSizeInBits() == 16) {
7595 SDValue Vec = Op.getOperand(0);
7596 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7598 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7599 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7600 DAG.getNode(ISD::BITCAST, dl,
7603 // Transform it so it match pextrw which produces a 32-bit result.
7604 MVT EltVT = MVT::i32;
7605 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7606 Op.getOperand(0), Op.getOperand(1));
7607 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7608 DAG.getValueType(VT));
7609 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7612 if (VT.getSizeInBits() == 32) {
7613 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7617 // SHUFPS the element to the lowest double word, then movss.
7618 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7619 MVT VVT = Op.getOperand(0).getSimpleValueType();
7620 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7621 DAG.getUNDEF(VVT), Mask);
7622 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7623 DAG.getIntPtrConstant(0));
7626 if (VT.getSizeInBits() == 64) {
7627 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7628 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7629 // to match extract_elt for f64.
7630 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7634 // UNPCKHPD the element to the lowest double word, then movsd.
7635 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7636 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7637 int Mask[2] = { 1, -1 };
7638 MVT VVT = Op.getOperand(0).getSimpleValueType();
7639 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7640 DAG.getUNDEF(VVT), Mask);
7641 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7642 DAG.getIntPtrConstant(0));
7648 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7649 MVT VT = Op.getSimpleValueType();
7650 MVT EltVT = VT.getVectorElementType();
7653 SDValue N0 = Op.getOperand(0);
7654 SDValue N1 = Op.getOperand(1);
7655 SDValue N2 = Op.getOperand(2);
7657 if (!VT.is128BitVector())
7660 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7661 isa<ConstantSDNode>(N2)) {
7663 if (VT == MVT::v8i16)
7664 Opc = X86ISD::PINSRW;
7665 else if (VT == MVT::v16i8)
7666 Opc = X86ISD::PINSRB;
7668 Opc = X86ISD::PINSRB;
7670 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7672 if (N1.getValueType() != MVT::i32)
7673 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7674 if (N2.getValueType() != MVT::i32)
7675 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7676 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7679 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7680 // Bits [7:6] of the constant are the source select. This will always be
7681 // zero here. The DAG Combiner may combine an extract_elt index into these
7682 // bits. For example (insert (extract, 3), 2) could be matched by putting
7683 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7684 // Bits [5:4] of the constant are the destination select. This is the
7685 // value of the incoming immediate.
7686 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7687 // combine either bitwise AND or insert of float 0.0 to set these bits.
7688 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7689 // Create this as a scalar to vector..
7690 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7691 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7694 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7695 // PINSR* works with constant index.
7702 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7703 MVT VT = Op.getSimpleValueType();
7704 MVT EltVT = VT.getVectorElementType();
7707 SDValue N0 = Op.getOperand(0);
7708 SDValue N1 = Op.getOperand(1);
7709 SDValue N2 = Op.getOperand(2);
7711 // If this is a 256-bit vector result, first extract the 128-bit vector,
7712 // insert the element into the extracted half and then place it back.
7713 if (VT.is256BitVector() || VT.is512BitVector()) {
7714 if (!isa<ConstantSDNode>(N2))
7717 // Get the desired 128-bit vector half.
7718 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7719 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7721 // Insert the element into the desired half.
7722 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7723 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7725 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7726 DAG.getConstant(IdxIn128, MVT::i32));
7728 // Insert the changed part back to the 256-bit vector
7729 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7732 if (Subtarget->hasSSE41())
7733 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7735 if (EltVT == MVT::i8)
7738 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7739 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7740 // as its second argument.
7741 if (N1.getValueType() != MVT::i32)
7742 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7743 if (N2.getValueType() != MVT::i32)
7744 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7745 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7750 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7752 MVT OpVT = Op.getSimpleValueType();
7754 // If this is a 256-bit vector result, first insert into a 128-bit
7755 // vector and then insert into the 256-bit vector.
7756 if (!OpVT.is128BitVector()) {
7757 // Insert into a 128-bit vector.
7758 unsigned SizeFactor = OpVT.getSizeInBits()/128;
7759 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7760 OpVT.getVectorNumElements() / SizeFactor);
7762 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7764 // Insert the 128-bit vector.
7765 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7768 if (OpVT == MVT::v1i64 &&
7769 Op.getOperand(0).getValueType() == MVT::i64)
7770 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7772 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7773 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7774 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7775 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7778 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7779 // a simple subregister reference or explicit instructions to grab
7780 // upper bits of a vector.
7781 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7782 SelectionDAG &DAG) {
7784 SDValue In = Op.getOperand(0);
7785 SDValue Idx = Op.getOperand(1);
7786 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7787 MVT ResVT = Op.getSimpleValueType();
7788 MVT InVT = In.getSimpleValueType();
7790 if (Subtarget->hasFp256()) {
7791 if (ResVT.is128BitVector() &&
7792 (InVT.is256BitVector() || InVT.is512BitVector()) &&
7793 isa<ConstantSDNode>(Idx)) {
7794 return Extract128BitVector(In, IdxVal, DAG, dl);
7796 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7797 isa<ConstantSDNode>(Idx)) {
7798 return Extract256BitVector(In, IdxVal, DAG, dl);
7804 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7805 // simple superregister reference or explicit instructions to insert
7806 // the upper bits of a vector.
7807 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7808 SelectionDAG &DAG) {
7809 if (Subtarget->hasFp256()) {
7810 SDLoc dl(Op.getNode());
7811 SDValue Vec = Op.getNode()->getOperand(0);
7812 SDValue SubVec = Op.getNode()->getOperand(1);
7813 SDValue Idx = Op.getNode()->getOperand(2);
7815 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
7816 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
7817 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
7818 isa<ConstantSDNode>(Idx)) {
7819 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7820 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7823 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
7824 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
7825 isa<ConstantSDNode>(Idx)) {
7826 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7827 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7833 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7834 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7835 // one of the above mentioned nodes. It has to be wrapped because otherwise
7836 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7837 // be used to form addressing mode. These wrapped nodes will be selected
7840 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7841 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7843 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7845 unsigned char OpFlag = 0;
7846 unsigned WrapperKind = X86ISD::Wrapper;
7847 CodeModel::Model M = getTargetMachine().getCodeModel();
7849 if (Subtarget->isPICStyleRIPRel() &&
7850 (M == CodeModel::Small || M == CodeModel::Kernel))
7851 WrapperKind = X86ISD::WrapperRIP;
7852 else if (Subtarget->isPICStyleGOT())
7853 OpFlag = X86II::MO_GOTOFF;
7854 else if (Subtarget->isPICStyleStubPIC())
7855 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7857 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7859 CP->getOffset(), OpFlag);
7861 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7862 // With PIC, the address is actually $g + Offset.
7864 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7865 DAG.getNode(X86ISD::GlobalBaseReg,
7866 SDLoc(), getPointerTy()),
7873 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7874 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7876 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7878 unsigned char OpFlag = 0;
7879 unsigned WrapperKind = X86ISD::Wrapper;
7880 CodeModel::Model M = getTargetMachine().getCodeModel();
7882 if (Subtarget->isPICStyleRIPRel() &&
7883 (M == CodeModel::Small || M == CodeModel::Kernel))
7884 WrapperKind = X86ISD::WrapperRIP;
7885 else if (Subtarget->isPICStyleGOT())
7886 OpFlag = X86II::MO_GOTOFF;
7887 else if (Subtarget->isPICStyleStubPIC())
7888 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7890 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7893 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7895 // With PIC, the address is actually $g + Offset.
7897 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7898 DAG.getNode(X86ISD::GlobalBaseReg,
7899 SDLoc(), getPointerTy()),
7906 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7907 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7909 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7911 unsigned char OpFlag = 0;
7912 unsigned WrapperKind = X86ISD::Wrapper;
7913 CodeModel::Model M = getTargetMachine().getCodeModel();
7915 if (Subtarget->isPICStyleRIPRel() &&
7916 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7917 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7918 OpFlag = X86II::MO_GOTPCREL;
7919 WrapperKind = X86ISD::WrapperRIP;
7920 } else if (Subtarget->isPICStyleGOT()) {
7921 OpFlag = X86II::MO_GOT;
7922 } else if (Subtarget->isPICStyleStubPIC()) {
7923 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7924 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7925 OpFlag = X86II::MO_DARWIN_NONLAZY;
7928 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7931 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7933 // With PIC, the address is actually $g + Offset.
7934 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7935 !Subtarget->is64Bit()) {
7936 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7937 DAG.getNode(X86ISD::GlobalBaseReg,
7938 SDLoc(), getPointerTy()),
7942 // For symbols that require a load from a stub to get the address, emit the
7944 if (isGlobalStubReference(OpFlag))
7945 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7946 MachinePointerInfo::getGOT(), false, false, false, 0);
7952 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7953 // Create the TargetBlockAddressAddress node.
7954 unsigned char OpFlags =
7955 Subtarget->ClassifyBlockAddressReference();
7956 CodeModel::Model M = getTargetMachine().getCodeModel();
7957 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7958 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7960 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7963 if (Subtarget->isPICStyleRIPRel() &&
7964 (M == CodeModel::Small || M == CodeModel::Kernel))
7965 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7967 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7969 // With PIC, the address is actually $g + Offset.
7970 if (isGlobalRelativeToPICBase(OpFlags)) {
7971 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7972 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7980 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7981 int64_t Offset, SelectionDAG &DAG) const {
7982 // Create the TargetGlobalAddress node, folding in the constant
7983 // offset if it is legal.
7984 unsigned char OpFlags =
7985 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7986 CodeModel::Model M = getTargetMachine().getCodeModel();
7988 if (OpFlags == X86II::MO_NO_FLAG &&
7989 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7990 // A direct static reference to a global.
7991 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7994 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7997 if (Subtarget->isPICStyleRIPRel() &&
7998 (M == CodeModel::Small || M == CodeModel::Kernel))
7999 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8001 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8003 // With PIC, the address is actually $g + Offset.
8004 if (isGlobalRelativeToPICBase(OpFlags)) {
8005 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8006 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8010 // For globals that require a load from a stub to get the address, emit the
8012 if (isGlobalStubReference(OpFlags))
8013 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8014 MachinePointerInfo::getGOT(), false, false, false, 0);
8016 // If there was a non-zero offset that we didn't fold, create an explicit
8019 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8020 DAG.getConstant(Offset, getPointerTy()));
8026 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8027 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8028 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8029 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8033 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8034 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8035 unsigned char OperandFlags, bool LocalDynamic = false) {
8036 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8037 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8039 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8040 GA->getValueType(0),
8044 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8048 SDValue Ops[] = { Chain, TGA, *InFlag };
8049 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8051 SDValue Ops[] = { Chain, TGA };
8052 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8055 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8056 MFI->setAdjustsStack(true);
8058 SDValue Flag = Chain.getValue(1);
8059 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8062 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8064 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8067 SDLoc dl(GA); // ? function entry point might be better
8068 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8069 DAG.getNode(X86ISD::GlobalBaseReg,
8070 SDLoc(), PtrVT), InFlag);
8071 InFlag = Chain.getValue(1);
8073 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8076 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8078 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8080 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8081 X86::RAX, X86II::MO_TLSGD);
8084 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8090 // Get the start address of the TLS block for this module.
8091 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8092 .getInfo<X86MachineFunctionInfo>();
8093 MFI->incNumLocalDynamicTLSAccesses();
8097 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8098 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8101 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8102 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8103 InFlag = Chain.getValue(1);
8104 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8105 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8108 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8112 unsigned char OperandFlags = X86II::MO_DTPOFF;
8113 unsigned WrapperKind = X86ISD::Wrapper;
8114 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8115 GA->getValueType(0),
8116 GA->getOffset(), OperandFlags);
8117 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8119 // Add x@dtpoff with the base.
8120 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8123 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8124 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8125 const EVT PtrVT, TLSModel::Model model,
8126 bool is64Bit, bool isPIC) {
8129 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8130 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8131 is64Bit ? 257 : 256));
8133 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8134 DAG.getIntPtrConstant(0),
8135 MachinePointerInfo(Ptr),
8136 false, false, false, 0);
8138 unsigned char OperandFlags = 0;
8139 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8141 unsigned WrapperKind = X86ISD::Wrapper;
8142 if (model == TLSModel::LocalExec) {
8143 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8144 } else if (model == TLSModel::InitialExec) {
8146 OperandFlags = X86II::MO_GOTTPOFF;
8147 WrapperKind = X86ISD::WrapperRIP;
8149 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8152 llvm_unreachable("Unexpected model");
8155 // emit "addl x@ntpoff,%eax" (local exec)
8156 // or "addl x@indntpoff,%eax" (initial exec)
8157 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8158 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8159 GA->getValueType(0),
8160 GA->getOffset(), OperandFlags);
8161 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8163 if (model == TLSModel::InitialExec) {
8164 if (isPIC && !is64Bit) {
8165 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8166 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8170 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8171 MachinePointerInfo::getGOT(), false, false, false,
8175 // The address of the thread local variable is the add of the thread
8176 // pointer with the offset of the variable.
8177 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8181 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8183 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8184 const GlobalValue *GV = GA->getGlobal();
8186 if (Subtarget->isTargetELF()) {
8187 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8190 case TLSModel::GeneralDynamic:
8191 if (Subtarget->is64Bit())
8192 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8193 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8194 case TLSModel::LocalDynamic:
8195 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8196 Subtarget->is64Bit());
8197 case TLSModel::InitialExec:
8198 case TLSModel::LocalExec:
8199 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8200 Subtarget->is64Bit(),
8201 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8203 llvm_unreachable("Unknown TLS model.");
8206 if (Subtarget->isTargetDarwin()) {
8207 // Darwin only has one model of TLS. Lower to that.
8208 unsigned char OpFlag = 0;
8209 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8210 X86ISD::WrapperRIP : X86ISD::Wrapper;
8212 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8214 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8215 !Subtarget->is64Bit();
8217 OpFlag = X86II::MO_TLVP_PIC_BASE;
8219 OpFlag = X86II::MO_TLVP;
8221 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8222 GA->getValueType(0),
8223 GA->getOffset(), OpFlag);
8224 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8226 // With PIC32, the address is actually $g + Offset.
8228 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8229 DAG.getNode(X86ISD::GlobalBaseReg,
8230 SDLoc(), getPointerTy()),
8233 // Lowering the machine isd will make sure everything is in the right
8235 SDValue Chain = DAG.getEntryNode();
8236 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8237 SDValue Args[] = { Chain, Offset };
8238 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8240 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8241 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8242 MFI->setAdjustsStack(true);
8244 // And our return value (tls address) is in the standard call return value
8246 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8247 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8251 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8252 // Just use the implicit TLS architecture
8253 // Need to generate someting similar to:
8254 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8256 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8257 // mov rcx, qword [rdx+rcx*8]
8258 // mov eax, .tls$:tlsvar
8259 // [rax+rcx] contains the address
8260 // Windows 64bit: gs:0x58
8261 // Windows 32bit: fs:__tls_array
8263 // If GV is an alias then use the aliasee for determining
8264 // thread-localness.
8265 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8266 GV = GA->resolveAliasedGlobal(false);
8268 SDValue Chain = DAG.getEntryNode();
8270 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8271 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8272 // use its literal value of 0x2C.
8273 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8274 ? Type::getInt8PtrTy(*DAG.getContext(),
8276 : Type::getInt32PtrTy(*DAG.getContext(),
8279 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8280 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8281 DAG.getExternalSymbol("_tls_array", getPointerTy()));
8283 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8284 MachinePointerInfo(Ptr),
8285 false, false, false, 0);
8287 // Load the _tls_index variable
8288 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8289 if (Subtarget->is64Bit())
8290 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8291 IDX, MachinePointerInfo(), MVT::i32,
8294 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8295 false, false, false, 0);
8297 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8299 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8301 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8302 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8303 false, false, false, 0);
8305 // Get the offset of start of .tls section
8306 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8307 GA->getValueType(0),
8308 GA->getOffset(), X86II::MO_SECREL);
8309 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8311 // The address of the thread local variable is the add of the thread
8312 // pointer with the offset of the variable.
8313 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8316 llvm_unreachable("TLS not implemented for this target.");
8319 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8320 /// and take a 2 x i32 value to shift plus a shift amount.
8321 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8322 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8323 EVT VT = Op.getValueType();
8324 unsigned VTBits = VT.getSizeInBits();
8326 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8327 SDValue ShOpLo = Op.getOperand(0);
8328 SDValue ShOpHi = Op.getOperand(1);
8329 SDValue ShAmt = Op.getOperand(2);
8330 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8331 DAG.getConstant(VTBits - 1, MVT::i8))
8332 : DAG.getConstant(0, VT);
8335 if (Op.getOpcode() == ISD::SHL_PARTS) {
8336 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8337 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8339 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8340 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8343 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8344 DAG.getConstant(VTBits, MVT::i8));
8345 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8346 AndNode, DAG.getConstant(0, MVT::i8));
8349 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8350 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8351 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8353 if (Op.getOpcode() == ISD::SHL_PARTS) {
8354 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8355 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8357 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8358 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8361 SDValue Ops[2] = { Lo, Hi };
8362 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8365 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8366 SelectionDAG &DAG) const {
8367 EVT SrcVT = Op.getOperand(0).getValueType();
8369 if (SrcVT.isVector())
8372 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8373 "Unknown SINT_TO_FP to lower!");
8375 // These are really Legal; return the operand so the caller accepts it as
8377 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8379 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8380 Subtarget->is64Bit()) {
8385 unsigned Size = SrcVT.getSizeInBits()/8;
8386 MachineFunction &MF = DAG.getMachineFunction();
8387 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8388 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8389 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8391 MachinePointerInfo::getFixedStack(SSFI),
8393 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8396 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8398 SelectionDAG &DAG) const {
8402 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8404 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8406 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8408 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8410 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8411 MachineMemOperand *MMO;
8413 int SSFI = FI->getIndex();
8415 DAG.getMachineFunction()
8416 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8417 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8419 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8420 StackSlot = StackSlot.getOperand(1);
8422 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8423 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8425 Tys, Ops, array_lengthof(Ops),
8429 Chain = Result.getValue(1);
8430 SDValue InFlag = Result.getValue(2);
8432 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8433 // shouldn't be necessary except that RFP cannot be live across
8434 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8435 MachineFunction &MF = DAG.getMachineFunction();
8436 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8437 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8438 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8439 Tys = DAG.getVTList(MVT::Other);
8441 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8443 MachineMemOperand *MMO =
8444 DAG.getMachineFunction()
8445 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8446 MachineMemOperand::MOStore, SSFISize, SSFISize);
8448 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8449 Ops, array_lengthof(Ops),
8450 Op.getValueType(), MMO);
8451 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8452 MachinePointerInfo::getFixedStack(SSFI),
8453 false, false, false, 0);
8459 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8460 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8461 SelectionDAG &DAG) const {
8462 // This algorithm is not obvious. Here it is what we're trying to output:
8465 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8466 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8470 pshufd $0x4e, %xmm0, %xmm1
8476 LLVMContext *Context = DAG.getContext();
8478 // Build some magic constants.
8479 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8480 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8481 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8483 SmallVector<Constant*,2> CV1;
8485 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8486 APInt(64, 0x4330000000000000ULL))));
8488 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8489 APInt(64, 0x4530000000000000ULL))));
8490 Constant *C1 = ConstantVector::get(CV1);
8491 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8493 // Load the 64-bit value into an XMM register.
8494 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8496 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8497 MachinePointerInfo::getConstantPool(),
8498 false, false, false, 16);
8499 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8500 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8503 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8504 MachinePointerInfo::getConstantPool(),
8505 false, false, false, 16);
8506 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8507 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8510 if (Subtarget->hasSSE3()) {
8511 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8512 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8514 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8515 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8517 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8518 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8522 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8523 DAG.getIntPtrConstant(0));
8526 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8527 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8528 SelectionDAG &DAG) const {
8530 // FP constant to bias correct the final result.
8531 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8534 // Load the 32-bit value into an XMM register.
8535 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8538 // Zero out the upper parts of the register.
8539 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8541 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8542 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8543 DAG.getIntPtrConstant(0));
8545 // Or the load with the bias.
8546 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8547 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8548 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8550 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8551 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8552 MVT::v2f64, Bias)));
8553 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8554 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8555 DAG.getIntPtrConstant(0));
8557 // Subtract the bias.
8558 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8560 // Handle final rounding.
8561 EVT DestVT = Op.getValueType();
8563 if (DestVT.bitsLT(MVT::f64))
8564 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8565 DAG.getIntPtrConstant(0));
8566 if (DestVT.bitsGT(MVT::f64))
8567 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8569 // Handle final rounding.
8573 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8574 SelectionDAG &DAG) const {
8575 SDValue N0 = Op.getOperand(0);
8576 EVT SVT = N0.getValueType();
8579 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8580 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8581 "Custom UINT_TO_FP is not supported!");
8583 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8584 SVT.getVectorNumElements());
8585 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8586 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8589 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8590 SelectionDAG &DAG) const {
8591 SDValue N0 = Op.getOperand(0);
8594 if (Op.getValueType().isVector())
8595 return lowerUINT_TO_FP_vec(Op, DAG);
8597 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8598 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8599 // the optimization here.
8600 if (DAG.SignBitIsZero(N0))
8601 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8603 EVT SrcVT = N0.getValueType();
8604 EVT DstVT = Op.getValueType();
8605 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8606 return LowerUINT_TO_FP_i64(Op, DAG);
8607 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8608 return LowerUINT_TO_FP_i32(Op, DAG);
8609 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8612 // Make a 64-bit buffer, and use it to build an FILD.
8613 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8614 if (SrcVT == MVT::i32) {
8615 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8616 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8617 getPointerTy(), StackSlot, WordOff);
8618 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8619 StackSlot, MachinePointerInfo(),
8621 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8622 OffsetSlot, MachinePointerInfo(),
8624 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8628 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8629 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8630 StackSlot, MachinePointerInfo(),
8632 // For i64 source, we need to add the appropriate power of 2 if the input
8633 // was negative. This is the same as the optimization in
8634 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8635 // we must be careful to do the computation in x87 extended precision, not
8636 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8637 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8638 MachineMemOperand *MMO =
8639 DAG.getMachineFunction()
8640 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8641 MachineMemOperand::MOLoad, 8, 8);
8643 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8644 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8645 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8646 array_lengthof(Ops), MVT::i64, MMO);
8648 APInt FF(32, 0x5F800000ULL);
8650 // Check whether the sign bit is set.
8651 SDValue SignSet = DAG.getSetCC(dl,
8652 getSetCCResultType(*DAG.getContext(), MVT::i64),
8653 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8656 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8657 SDValue FudgePtr = DAG.getConstantPool(
8658 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8661 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8662 SDValue Zero = DAG.getIntPtrConstant(0);
8663 SDValue Four = DAG.getIntPtrConstant(4);
8664 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8666 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8668 // Load the value out, extending it from f32 to f80.
8669 // FIXME: Avoid the extend by constructing the right constant pool?
8670 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8671 FudgePtr, MachinePointerInfo::getConstantPool(),
8672 MVT::f32, false, false, 4);
8673 // Extend everything to 80 bits to force it to be done on x87.
8674 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8675 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8678 std::pair<SDValue,SDValue>
8679 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8680 bool IsSigned, bool IsReplace) const {
8683 EVT DstTy = Op.getValueType();
8685 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8686 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8690 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8691 DstTy.getSimpleVT() >= MVT::i16 &&
8692 "Unknown FP_TO_INT to lower!");
8694 // These are really Legal.
8695 if (DstTy == MVT::i32 &&
8696 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8697 return std::make_pair(SDValue(), SDValue());
8698 if (Subtarget->is64Bit() &&
8699 DstTy == MVT::i64 &&
8700 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8701 return std::make_pair(SDValue(), SDValue());
8703 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8704 // stack slot, or into the FTOL runtime function.
8705 MachineFunction &MF = DAG.getMachineFunction();
8706 unsigned MemSize = DstTy.getSizeInBits()/8;
8707 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8708 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8711 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8712 Opc = X86ISD::WIN_FTOL;
8714 switch (DstTy.getSimpleVT().SimpleTy) {
8715 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8716 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8717 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8718 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8721 SDValue Chain = DAG.getEntryNode();
8722 SDValue Value = Op.getOperand(0);
8723 EVT TheVT = Op.getOperand(0).getValueType();
8724 // FIXME This causes a redundant load/store if the SSE-class value is already
8725 // in memory, such as if it is on the callstack.
8726 if (isScalarFPTypeInSSEReg(TheVT)) {
8727 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8728 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8729 MachinePointerInfo::getFixedStack(SSFI),
8731 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8733 Chain, StackSlot, DAG.getValueType(TheVT)
8736 MachineMemOperand *MMO =
8737 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8738 MachineMemOperand::MOLoad, MemSize, MemSize);
8739 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8740 array_lengthof(Ops), DstTy, MMO);
8741 Chain = Value.getValue(1);
8742 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8743 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8746 MachineMemOperand *MMO =
8747 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8748 MachineMemOperand::MOStore, MemSize, MemSize);
8750 if (Opc != X86ISD::WIN_FTOL) {
8751 // Build the FP_TO_INT*_IN_MEM
8752 SDValue Ops[] = { Chain, Value, StackSlot };
8753 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8754 Ops, array_lengthof(Ops), DstTy,
8756 return std::make_pair(FIST, StackSlot);
8758 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8759 DAG.getVTList(MVT::Other, MVT::Glue),
8761 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8762 MVT::i32, ftol.getValue(1));
8763 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8764 MVT::i32, eax.getValue(2));
8765 SDValue Ops[] = { eax, edx };
8766 SDValue pair = IsReplace
8767 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8768 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8769 return std::make_pair(pair, SDValue());
8773 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8774 const X86Subtarget *Subtarget) {
8775 MVT VT = Op->getSimpleValueType(0);
8776 SDValue In = Op->getOperand(0);
8777 MVT InVT = In.getSimpleValueType();
8780 // Optimize vectors in AVX mode:
8783 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8784 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8785 // Concat upper and lower parts.
8788 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8789 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8790 // Concat upper and lower parts.
8793 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8794 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8797 if (Subtarget->hasInt256())
8798 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8800 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8801 SDValue Undef = DAG.getUNDEF(InVT);
8802 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8803 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8804 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8806 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8807 VT.getVectorNumElements()/2);
8809 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8810 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8812 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8815 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8816 SelectionDAG &DAG) const {
8817 if (Subtarget->hasFp256()) {
8818 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8825 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8826 SelectionDAG &DAG) const {
8828 MVT VT = Op.getSimpleValueType();
8829 SDValue In = Op.getOperand(0);
8830 MVT SVT = In.getSimpleValueType();
8832 if (Subtarget->hasFp256()) {
8833 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8838 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8839 VT.getVectorNumElements() != SVT.getVectorNumElements())
8842 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8844 // AVX2 has better support of integer extending.
8845 if (Subtarget->hasInt256())
8846 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8848 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8849 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8850 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8851 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8852 DAG.getUNDEF(MVT::v8i16),
8855 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8858 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8860 MVT VT = Op.getSimpleValueType();
8861 SDValue In = Op.getOperand(0);
8862 MVT SVT = In.getSimpleValueType();
8864 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8865 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8866 if (Subtarget->hasInt256()) {
8867 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8868 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8869 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8871 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8872 DAG.getIntPtrConstant(0));
8875 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8876 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8877 DAG.getIntPtrConstant(0));
8878 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8879 DAG.getIntPtrConstant(2));
8881 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8882 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8885 static const int ShufMask1[] = {0, 2, 0, 0};
8886 SDValue Undef = DAG.getUNDEF(VT);
8887 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8888 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8890 // The MOVLHPS mask:
8891 static const int ShufMask2[] = {0, 1, 4, 5};
8892 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8895 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8896 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8897 if (Subtarget->hasInt256()) {
8898 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8900 SmallVector<SDValue,32> pshufbMask;
8901 for (unsigned i = 0; i < 2; ++i) {
8902 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8903 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8904 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8905 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8906 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8907 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8908 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8909 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8910 for (unsigned j = 0; j < 8; ++j)
8911 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8913 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8914 &pshufbMask[0], 32);
8915 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8916 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8918 static const int ShufMask[] = {0, 2, -1, -1};
8919 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8921 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8922 DAG.getIntPtrConstant(0));
8923 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8926 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8927 DAG.getIntPtrConstant(0));
8929 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8930 DAG.getIntPtrConstant(4));
8932 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8933 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8936 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8937 -1, -1, -1, -1, -1, -1, -1, -1};
8939 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8940 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8941 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8943 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8944 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8946 // The MOVLHPS Mask:
8947 static const int ShufMask2[] = {0, 1, 4, 5};
8948 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8949 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8952 // Handle truncation of V256 to V128 using shuffles.
8953 if (!VT.is128BitVector() || !SVT.is256BitVector())
8956 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8958 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8960 unsigned NumElems = VT.getVectorNumElements();
8961 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8964 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8965 // Prepare truncation shuffle mask
8966 for (unsigned i = 0; i != NumElems; ++i)
8968 SDValue V = DAG.getVectorShuffle(NVT, DL,
8969 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8970 DAG.getUNDEF(NVT), &MaskVec[0]);
8971 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8972 DAG.getIntPtrConstant(0));
8975 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8976 SelectionDAG &DAG) const {
8977 MVT VT = Op.getSimpleValueType();
8978 if (VT.isVector()) {
8979 if (VT == MVT::v8i16)
8980 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8981 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8982 MVT::v8i32, Op.getOperand(0)));
8986 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8987 /*IsSigned=*/ true, /*IsReplace=*/ false);
8988 SDValue FIST = Vals.first, StackSlot = Vals.second;
8989 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8990 if (FIST.getNode() == 0) return Op;
8992 if (StackSlot.getNode())
8994 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8995 FIST, StackSlot, MachinePointerInfo(),
8996 false, false, false, 0);
8998 // The node is the result.
9002 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9003 SelectionDAG &DAG) const {
9004 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9005 /*IsSigned=*/ false, /*IsReplace=*/ false);
9006 SDValue FIST = Vals.first, StackSlot = Vals.second;
9007 assert(FIST.getNode() && "Unexpected failure");
9009 if (StackSlot.getNode())
9011 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9012 FIST, StackSlot, MachinePointerInfo(),
9013 false, false, false, 0);
9015 // The node is the result.
9019 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9021 MVT VT = Op.getSimpleValueType();
9022 SDValue In = Op.getOperand(0);
9023 MVT SVT = In.getSimpleValueType();
9025 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9027 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9028 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9029 In, DAG.getUNDEF(SVT)));
9032 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9033 LLVMContext *Context = DAG.getContext();
9035 MVT VT = Op.getSimpleValueType();
9037 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9038 if (VT.isVector()) {
9039 EltVT = VT.getVectorElementType();
9040 NumElts = VT.getVectorNumElements();
9043 if (EltVT == MVT::f64)
9044 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9045 APInt(64, ~(1ULL << 63))));
9047 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9048 APInt(32, ~(1U << 31))));
9049 C = ConstantVector::getSplat(NumElts, C);
9050 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9051 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9052 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9053 MachinePointerInfo::getConstantPool(),
9054 false, false, false, Alignment);
9055 if (VT.isVector()) {
9056 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9057 return DAG.getNode(ISD::BITCAST, dl, VT,
9058 DAG.getNode(ISD::AND, dl, ANDVT,
9059 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9061 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9063 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9066 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9067 LLVMContext *Context = DAG.getContext();
9069 MVT VT = Op.getSimpleValueType();
9071 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9072 if (VT.isVector()) {
9073 EltVT = VT.getVectorElementType();
9074 NumElts = VT.getVectorNumElements();
9077 if (EltVT == MVT::f64)
9078 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9079 APInt(64, 1ULL << 63)));
9081 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9082 APInt(32, 1U << 31)));
9083 C = ConstantVector::getSplat(NumElts, C);
9084 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9085 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9086 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9087 MachinePointerInfo::getConstantPool(),
9088 false, false, false, Alignment);
9089 if (VT.isVector()) {
9090 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9091 return DAG.getNode(ISD::BITCAST, dl, VT,
9092 DAG.getNode(ISD::XOR, dl, XORVT,
9093 DAG.getNode(ISD::BITCAST, dl, XORVT,
9095 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9098 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9101 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9102 LLVMContext *Context = DAG.getContext();
9103 SDValue Op0 = Op.getOperand(0);
9104 SDValue Op1 = Op.getOperand(1);
9106 MVT VT = Op.getSimpleValueType();
9107 MVT SrcVT = Op1.getSimpleValueType();
9109 // If second operand is smaller, extend it first.
9110 if (SrcVT.bitsLT(VT)) {
9111 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9114 // And if it is bigger, shrink it first.
9115 if (SrcVT.bitsGT(VT)) {
9116 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9120 // At this point the operands and the result should have the same
9121 // type, and that won't be f80 since that is not custom lowered.
9123 // First get the sign bit of second operand.
9124 SmallVector<Constant*,4> CV;
9125 if (SrcVT == MVT::f64) {
9126 const fltSemantics &Sem = APFloat::IEEEdouble;
9127 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9128 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9130 const fltSemantics &Sem = APFloat::IEEEsingle;
9131 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9132 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9133 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9134 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9136 Constant *C = ConstantVector::get(CV);
9137 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9138 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9139 MachinePointerInfo::getConstantPool(),
9140 false, false, false, 16);
9141 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9143 // Shift sign bit right or left if the two operands have different types.
9144 if (SrcVT.bitsGT(VT)) {
9145 // Op0 is MVT::f32, Op1 is MVT::f64.
9146 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9147 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9148 DAG.getConstant(32, MVT::i32));
9149 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9150 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9151 DAG.getIntPtrConstant(0));
9154 // Clear first operand sign bit.
9156 if (VT == MVT::f64) {
9157 const fltSemantics &Sem = APFloat::IEEEdouble;
9158 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9159 APInt(64, ~(1ULL << 63)))));
9160 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9162 const fltSemantics &Sem = APFloat::IEEEsingle;
9163 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9164 APInt(32, ~(1U << 31)))));
9165 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9166 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9167 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9169 C = ConstantVector::get(CV);
9170 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9171 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9172 MachinePointerInfo::getConstantPool(),
9173 false, false, false, 16);
9174 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9176 // Or the value with the sign bit.
9177 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9180 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9181 SDValue N0 = Op.getOperand(0);
9183 MVT VT = Op.getSimpleValueType();
9185 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9186 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9187 DAG.getConstant(1, VT));
9188 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9191 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9193 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9194 SelectionDAG &DAG) {
9195 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9197 if (!Subtarget->hasSSE41())
9200 if (!Op->hasOneUse())
9203 SDNode *N = Op.getNode();
9206 SmallVector<SDValue, 8> Opnds;
9207 DenseMap<SDValue, unsigned> VecInMap;
9208 EVT VT = MVT::Other;
9210 // Recognize a special case where a vector is casted into wide integer to
9212 Opnds.push_back(N->getOperand(0));
9213 Opnds.push_back(N->getOperand(1));
9215 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9216 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9217 // BFS traverse all OR'd operands.
9218 if (I->getOpcode() == ISD::OR) {
9219 Opnds.push_back(I->getOperand(0));
9220 Opnds.push_back(I->getOperand(1));
9221 // Re-evaluate the number of nodes to be traversed.
9222 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9226 // Quit if a non-EXTRACT_VECTOR_ELT
9227 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9230 // Quit if without a constant index.
9231 SDValue Idx = I->getOperand(1);
9232 if (!isa<ConstantSDNode>(Idx))
9235 SDValue ExtractedFromVec = I->getOperand(0);
9236 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9237 if (M == VecInMap.end()) {
9238 VT = ExtractedFromVec.getValueType();
9239 // Quit if not 128/256-bit vector.
9240 if (!VT.is128BitVector() && !VT.is256BitVector())
9242 // Quit if not the same type.
9243 if (VecInMap.begin() != VecInMap.end() &&
9244 VT != VecInMap.begin()->first.getValueType())
9246 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9248 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9251 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9252 "Not extracted from 128-/256-bit vector.");
9254 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9255 SmallVector<SDValue, 8> VecIns;
9257 for (DenseMap<SDValue, unsigned>::const_iterator
9258 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9259 // Quit if not all elements are used.
9260 if (I->second != FullMask)
9262 VecIns.push_back(I->first);
9265 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9267 // Cast all vectors into TestVT for PTEST.
9268 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9269 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9271 // If more than one full vectors are evaluated, OR them first before PTEST.
9272 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9273 // Each iteration will OR 2 nodes and append the result until there is only
9274 // 1 node left, i.e. the final OR'd value of all vectors.
9275 SDValue LHS = VecIns[Slot];
9276 SDValue RHS = VecIns[Slot + 1];
9277 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9280 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9281 VecIns.back(), VecIns.back());
9284 /// Emit nodes that will be selected as "test Op0,Op0", or something
9286 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9287 SelectionDAG &DAG) const {
9290 // CF and OF aren't always set the way we want. Determine which
9291 // of these we need.
9292 bool NeedCF = false;
9293 bool NeedOF = false;
9296 case X86::COND_A: case X86::COND_AE:
9297 case X86::COND_B: case X86::COND_BE:
9300 case X86::COND_G: case X86::COND_GE:
9301 case X86::COND_L: case X86::COND_LE:
9302 case X86::COND_O: case X86::COND_NO:
9307 // See if we can use the EFLAGS value from the operand instead of
9308 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9309 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9310 if (Op.getResNo() != 0 || NeedOF || NeedCF)
9311 // Emit a CMP with 0, which is the TEST pattern.
9312 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9313 DAG.getConstant(0, Op.getValueType()));
9315 unsigned Opcode = 0;
9316 unsigned NumOperands = 0;
9318 // Truncate operations may prevent the merge of the SETCC instruction
9319 // and the arithmetic intruction before it. Attempt to truncate the operands
9320 // of the arithmetic instruction and use a reduced bit-width instruction.
9321 bool NeedTruncation = false;
9322 SDValue ArithOp = Op;
9323 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9324 SDValue Arith = Op->getOperand(0);
9325 // Both the trunc and the arithmetic op need to have one user each.
9326 if (Arith->hasOneUse())
9327 switch (Arith.getOpcode()) {
9334 NeedTruncation = true;
9340 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9341 // which may be the result of a CAST. We use the variable 'Op', which is the
9342 // non-casted variable when we check for possible users.
9343 switch (ArithOp.getOpcode()) {
9345 // Due to an isel shortcoming, be conservative if this add is likely to be
9346 // selected as part of a load-modify-store instruction. When the root node
9347 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9348 // uses of other nodes in the match, such as the ADD in this case. This
9349 // leads to the ADD being left around and reselected, with the result being
9350 // two adds in the output. Alas, even if none our users are stores, that
9351 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9352 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9353 // climbing the DAG back to the root, and it doesn't seem to be worth the
9355 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9356 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9357 if (UI->getOpcode() != ISD::CopyToReg &&
9358 UI->getOpcode() != ISD::SETCC &&
9359 UI->getOpcode() != ISD::STORE)
9362 if (ConstantSDNode *C =
9363 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9364 // An add of one will be selected as an INC.
9365 if (C->getAPIntValue() == 1) {
9366 Opcode = X86ISD::INC;
9371 // An add of negative one (subtract of one) will be selected as a DEC.
9372 if (C->getAPIntValue().isAllOnesValue()) {
9373 Opcode = X86ISD::DEC;
9379 // Otherwise use a regular EFLAGS-setting add.
9380 Opcode = X86ISD::ADD;
9384 // If the primary and result isn't used, don't bother using X86ISD::AND,
9385 // because a TEST instruction will be better.
9386 bool NonFlagUse = false;
9387 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9388 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9390 unsigned UOpNo = UI.getOperandNo();
9391 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9392 // Look pass truncate.
9393 UOpNo = User->use_begin().getOperandNo();
9394 User = *User->use_begin();
9397 if (User->getOpcode() != ISD::BRCOND &&
9398 User->getOpcode() != ISD::SETCC &&
9399 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9412 // Due to the ISEL shortcoming noted above, be conservative if this op is
9413 // likely to be selected as part of a load-modify-store instruction.
9414 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9415 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9416 if (UI->getOpcode() == ISD::STORE)
9419 // Otherwise use a regular EFLAGS-setting instruction.
9420 switch (ArithOp.getOpcode()) {
9421 default: llvm_unreachable("unexpected operator!");
9422 case ISD::SUB: Opcode = X86ISD::SUB; break;
9423 case ISD::XOR: Opcode = X86ISD::XOR; break;
9424 case ISD::AND: Opcode = X86ISD::AND; break;
9426 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9427 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9428 if (EFLAGS.getNode())
9431 Opcode = X86ISD::OR;
9445 return SDValue(Op.getNode(), 1);
9451 // If we found that truncation is beneficial, perform the truncation and
9453 if (NeedTruncation) {
9454 EVT VT = Op.getValueType();
9455 SDValue WideVal = Op->getOperand(0);
9456 EVT WideVT = WideVal.getValueType();
9457 unsigned ConvertedOp = 0;
9458 // Use a target machine opcode to prevent further DAGCombine
9459 // optimizations that may separate the arithmetic operations
9460 // from the setcc node.
9461 switch (WideVal.getOpcode()) {
9463 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9464 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9465 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9466 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9467 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9471 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9472 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9473 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9474 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9475 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9481 // Emit a CMP with 0, which is the TEST pattern.
9482 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9483 DAG.getConstant(0, Op.getValueType()));
9485 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9486 SmallVector<SDValue, 4> Ops;
9487 for (unsigned i = 0; i != NumOperands; ++i)
9488 Ops.push_back(Op.getOperand(i));
9490 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9491 DAG.ReplaceAllUsesWith(Op, New);
9492 return SDValue(New.getNode(), 1);
9495 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9497 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9498 SelectionDAG &DAG) const {
9499 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9500 if (C->getAPIntValue() == 0)
9501 return EmitTest(Op0, X86CC, DAG);
9504 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9505 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9506 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9507 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9508 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9510 return SDValue(Sub.getNode(), 1);
9512 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9515 /// Convert a comparison if required by the subtarget.
9516 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9517 SelectionDAG &DAG) const {
9518 // If the subtarget does not support the FUCOMI instruction, floating-point
9519 // comparisons have to be converted.
9520 if (Subtarget->hasCMov() ||
9521 Cmp.getOpcode() != X86ISD::CMP ||
9522 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9523 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9526 // The instruction selector will select an FUCOM instruction instead of
9527 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9528 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9529 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9531 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9532 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9533 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9534 DAG.getConstant(8, MVT::i8));
9535 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9536 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9539 static bool isAllOnes(SDValue V) {
9540 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9541 return C && C->isAllOnesValue();
9544 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9545 /// if it's possible.
9546 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9547 SDLoc dl, SelectionDAG &DAG) const {
9548 SDValue Op0 = And.getOperand(0);
9549 SDValue Op1 = And.getOperand(1);
9550 if (Op0.getOpcode() == ISD::TRUNCATE)
9551 Op0 = Op0.getOperand(0);
9552 if (Op1.getOpcode() == ISD::TRUNCATE)
9553 Op1 = Op1.getOperand(0);
9556 if (Op1.getOpcode() == ISD::SHL)
9557 std::swap(Op0, Op1);
9558 if (Op0.getOpcode() == ISD::SHL) {
9559 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9560 if (And00C->getZExtValue() == 1) {
9561 // If we looked past a truncate, check that it's only truncating away
9563 unsigned BitWidth = Op0.getValueSizeInBits();
9564 unsigned AndBitWidth = And.getValueSizeInBits();
9565 if (BitWidth > AndBitWidth) {
9567 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9568 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9572 RHS = Op0.getOperand(1);
9574 } else if (Op1.getOpcode() == ISD::Constant) {
9575 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9576 uint64_t AndRHSVal = AndRHS->getZExtValue();
9577 SDValue AndLHS = Op0;
9579 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9580 LHS = AndLHS.getOperand(0);
9581 RHS = AndLHS.getOperand(1);
9584 // Use BT if the immediate can't be encoded in a TEST instruction.
9585 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9587 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9591 if (LHS.getNode()) {
9592 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9593 // instruction. Since the shift amount is in-range-or-undefined, we know
9594 // that doing a bittest on the i32 value is ok. We extend to i32 because
9595 // the encoding for the i16 version is larger than the i32 version.
9596 // Also promote i16 to i32 for performance / code size reason.
9597 if (LHS.getValueType() == MVT::i8 ||
9598 LHS.getValueType() == MVT::i16)
9599 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9601 // If the operand types disagree, extend the shift amount to match. Since
9602 // BT ignores high bits (like shifts) we can use anyextend.
9603 if (LHS.getValueType() != RHS.getValueType())
9604 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9606 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9607 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9608 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9609 DAG.getConstant(Cond, MVT::i8), BT);
9615 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9617 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9622 // SSE Condition code mapping:
9631 switch (SetCCOpcode) {
9632 default: llvm_unreachable("Unexpected SETCC condition");
9634 case ISD::SETEQ: SSECC = 0; break;
9636 case ISD::SETGT: Swap = true; // Fallthrough
9638 case ISD::SETOLT: SSECC = 1; break;
9640 case ISD::SETGE: Swap = true; // Fallthrough
9642 case ISD::SETOLE: SSECC = 2; break;
9643 case ISD::SETUO: SSECC = 3; break;
9645 case ISD::SETNE: SSECC = 4; break;
9646 case ISD::SETULE: Swap = true; // Fallthrough
9647 case ISD::SETUGE: SSECC = 5; break;
9648 case ISD::SETULT: Swap = true; // Fallthrough
9649 case ISD::SETUGT: SSECC = 6; break;
9650 case ISD::SETO: SSECC = 7; break;
9652 case ISD::SETONE: SSECC = 8; break;
9655 std::swap(Op0, Op1);
9660 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9661 // ones, and then concatenate the result back.
9662 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9663 MVT VT = Op.getSimpleValueType();
9665 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9666 "Unsupported value type for operation");
9668 unsigned NumElems = VT.getVectorNumElements();
9670 SDValue CC = Op.getOperand(2);
9672 // Extract the LHS vectors
9673 SDValue LHS = Op.getOperand(0);
9674 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9675 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9677 // Extract the RHS vectors
9678 SDValue RHS = Op.getOperand(1);
9679 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9680 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9682 // Issue the operation on the smaller types and concatenate the result back
9683 MVT EltVT = VT.getVectorElementType();
9684 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9685 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9686 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9687 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9690 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9692 SDValue Op0 = Op.getOperand(0);
9693 SDValue Op1 = Op.getOperand(1);
9694 SDValue CC = Op.getOperand(2);
9695 MVT VT = Op.getSimpleValueType();
9697 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9698 Op.getValueType().getScalarType() == MVT::i1 &&
9699 "Cannot set masked compare for this operation");
9701 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9704 bool Unsigned = false;
9706 switch (SetCCOpcode) {
9707 default: llvm_unreachable("Unexpected SETCC condition");
9708 case ISD::SETNE: SSECC = 4; break;
9709 case ISD::SETEQ: SSECC = 0; break;
9710 case ISD::SETUGT: Unsigned = true;
9711 case ISD::SETGT: SSECC = 6; break; // NLE
9712 case ISD::SETULT: Unsigned = true;
9713 case ISD::SETLT: SSECC = 1; break;
9714 case ISD::SETUGE: Unsigned = true;
9715 case ISD::SETGE: SSECC = 5; break; // NLT
9716 case ISD::SETULE: Unsigned = true;
9717 case ISD::SETLE: SSECC = 2; break;
9719 unsigned Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9720 return DAG.getNode(Opc, dl, VT, Op0, Op1,
9721 DAG.getConstant(SSECC, MVT::i8));
9725 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9726 SelectionDAG &DAG) {
9728 SDValue Op0 = Op.getOperand(0);
9729 SDValue Op1 = Op.getOperand(1);
9730 SDValue CC = Op.getOperand(2);
9731 MVT VT = Op.getSimpleValueType();
9732 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9733 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
9738 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
9739 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9742 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9743 unsigned Opc = X86ISD::CMPP;
9744 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
9745 assert(VT.getVectorNumElements() <= 16);
9748 // In the two special cases we can't handle, emit two comparisons.
9751 unsigned CombineOpc;
9752 if (SetCCOpcode == ISD::SETUEQ) {
9753 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9755 assert(SetCCOpcode == ISD::SETONE);
9756 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9759 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9760 DAG.getConstant(CC0, MVT::i8));
9761 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9762 DAG.getConstant(CC1, MVT::i8));
9763 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9765 // Handle all other FP comparisons here.
9766 return DAG.getNode(Opc, dl, VT, Op0, Op1,
9767 DAG.getConstant(SSECC, MVT::i8));
9770 // Break 256-bit integer vector compare into smaller ones.
9771 if (VT.is256BitVector() && !Subtarget->hasInt256())
9772 return Lower256IntVSETCC(Op, DAG);
9774 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
9775 EVT OpVT = Op1.getValueType();
9776 if (Subtarget->hasAVX512()) {
9777 if (Op1.getValueType().is512BitVector() ||
9778 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
9779 return LowerIntVSETCC_AVX512(Op, DAG);
9781 // In AVX-512 architecture setcc returns mask with i1 elements,
9782 // But there is no compare instruction for i8 and i16 elements.
9783 // We are not talking about 512-bit operands in this case, these
9784 // types are illegal.
9786 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
9787 OpVT.getVectorElementType().getSizeInBits() >= 8))
9788 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9789 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
9792 // We are handling one of the integer comparisons here. Since SSE only has
9793 // GT and EQ comparisons for integer, swapping operands and multiple
9794 // operations may be required for some comparisons.
9796 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9798 switch (SetCCOpcode) {
9799 default: llvm_unreachable("Unexpected SETCC condition");
9800 case ISD::SETNE: Invert = true;
9801 case ISD::SETEQ: Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
9802 case ISD::SETLT: Swap = true;
9803 case ISD::SETGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
9804 case ISD::SETGE: Swap = true;
9805 case ISD::SETLE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9806 Invert = true; break;
9807 case ISD::SETULT: Swap = true;
9808 case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9809 FlipSigns = true; break;
9810 case ISD::SETUGE: Swap = true;
9811 case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9812 FlipSigns = true; Invert = true; break;
9815 // Special case: Use min/max operations for SETULE/SETUGE
9816 MVT VET = VT.getVectorElementType();
9818 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9819 || (Subtarget->hasSSE2() && (VET == MVT::i8));
9822 switch (SetCCOpcode) {
9824 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9825 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9828 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9832 std::swap(Op0, Op1);
9834 // Check that the operation in question is available (most are plain SSE2,
9835 // but PCMPGTQ and PCMPEQQ have different requirements).
9836 if (VT == MVT::v2i64) {
9837 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9838 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9840 // First cast everything to the right type.
9841 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9842 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9844 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9845 // bits of the inputs before performing those operations. The lower
9846 // compare is always unsigned.
9849 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9851 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9852 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9853 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9854 Sign, Zero, Sign, Zero);
9856 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9857 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9859 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9860 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9861 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9863 // Create masks for only the low parts/high parts of the 64 bit integers.
9864 static const int MaskHi[] = { 1, 1, 3, 3 };
9865 static const int MaskLo[] = { 0, 0, 2, 2 };
9866 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9867 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9868 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9870 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9871 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9874 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9876 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9879 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9880 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9881 // pcmpeqd + pshufd + pand.
9882 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9884 // First cast everything to the right type.
9885 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9886 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9889 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9891 // Make sure the lower and upper halves are both all-ones.
9892 static const int Mask[] = { 1, 0, 3, 2 };
9893 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9894 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9897 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9899 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9903 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9904 // bits of the inputs before performing those operations.
9906 EVT EltVT = VT.getVectorElementType();
9907 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9908 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9909 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9912 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9914 // If the logical-not of the result is required, perform that now.
9916 Result = DAG.getNOT(dl, Result, VT);
9919 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9924 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9926 MVT VT = Op.getSimpleValueType();
9928 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9930 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9931 SDValue Op0 = Op.getOperand(0);
9932 SDValue Op1 = Op.getOperand(1);
9934 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9936 // Optimize to BT if possible.
9937 // Lower (X & (1 << N)) == 0 to BT(X, N).
9938 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9939 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9940 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9941 Op1.getOpcode() == ISD::Constant &&
9942 cast<ConstantSDNode>(Op1)->isNullValue() &&
9943 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9944 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9945 if (NewSetCC.getNode())
9949 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9951 if (Op1.getOpcode() == ISD::Constant &&
9952 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9953 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9954 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9956 // If the input is a setcc, then reuse the input setcc or use a new one with
9957 // the inverted condition.
9958 if (Op0.getOpcode() == X86ISD::SETCC) {
9959 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9960 bool Invert = (CC == ISD::SETNE) ^
9961 cast<ConstantSDNode>(Op1)->isNullValue();
9962 if (!Invert) return Op0;
9964 CCode = X86::GetOppositeBranchCondition(CCode);
9965 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9966 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9970 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
9971 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9972 if (X86CC == X86::COND_INVALID)
9975 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9976 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9977 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9978 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9981 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9982 static bool isX86LogicalCmp(SDValue Op) {
9983 unsigned Opc = Op.getNode()->getOpcode();
9984 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9985 Opc == X86ISD::SAHF)
9987 if (Op.getResNo() == 1 &&
9988 (Opc == X86ISD::ADD ||
9989 Opc == X86ISD::SUB ||
9990 Opc == X86ISD::ADC ||
9991 Opc == X86ISD::SBB ||
9992 Opc == X86ISD::SMUL ||
9993 Opc == X86ISD::UMUL ||
9994 Opc == X86ISD::INC ||
9995 Opc == X86ISD::DEC ||
9996 Opc == X86ISD::OR ||
9997 Opc == X86ISD::XOR ||
9998 Opc == X86ISD::AND))
10001 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10007 static bool isZero(SDValue V) {
10008 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10009 return C && C->isNullValue();
10012 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10013 if (V.getOpcode() != ISD::TRUNCATE)
10016 SDValue VOp0 = V.getOperand(0);
10017 unsigned InBits = VOp0.getValueSizeInBits();
10018 unsigned Bits = V.getValueSizeInBits();
10019 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10022 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10023 bool addTest = true;
10024 SDValue Cond = Op.getOperand(0);
10025 SDValue Op1 = Op.getOperand(1);
10026 SDValue Op2 = Op.getOperand(2);
10028 EVT VT = Op1.getValueType();
10031 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10032 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10033 // sequence later on.
10034 if (Cond.getOpcode() == ISD::SETCC &&
10035 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10036 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10037 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10038 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10039 int SSECC = translateX86FSETCC(
10040 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10043 unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
10044 SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
10045 DAG.getConstant(SSECC, MVT::i8));
10046 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10047 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10048 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10052 if (Cond.getOpcode() == ISD::SETCC) {
10053 SDValue NewCond = LowerSETCC(Cond, DAG);
10054 if (NewCond.getNode())
10058 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10059 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10060 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10061 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10062 if (Cond.getOpcode() == X86ISD::SETCC &&
10063 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10064 isZero(Cond.getOperand(1).getOperand(1))) {
10065 SDValue Cmp = Cond.getOperand(1);
10067 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10069 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10070 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10071 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10073 SDValue CmpOp0 = Cmp.getOperand(0);
10074 // Apply further optimizations for special cases
10075 // (select (x != 0), -1, 0) -> neg & sbb
10076 // (select (x == 0), 0, -1) -> neg & sbb
10077 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10078 if (YC->isNullValue() &&
10079 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10080 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10081 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10082 DAG.getConstant(0, CmpOp0.getValueType()),
10084 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10085 DAG.getConstant(X86::COND_B, MVT::i8),
10086 SDValue(Neg.getNode(), 1));
10090 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10091 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10092 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10094 SDValue Res = // Res = 0 or -1.
10095 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10096 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10098 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10099 Res = DAG.getNOT(DL, Res, Res.getValueType());
10101 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10102 if (N2C == 0 || !N2C->isNullValue())
10103 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10108 // Look past (and (setcc_carry (cmp ...)), 1).
10109 if (Cond.getOpcode() == ISD::AND &&
10110 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10111 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10112 if (C && C->getAPIntValue() == 1)
10113 Cond = Cond.getOperand(0);
10116 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10117 // setting operand in place of the X86ISD::SETCC.
10118 unsigned CondOpcode = Cond.getOpcode();
10119 if (CondOpcode == X86ISD::SETCC ||
10120 CondOpcode == X86ISD::SETCC_CARRY) {
10121 CC = Cond.getOperand(0);
10123 SDValue Cmp = Cond.getOperand(1);
10124 unsigned Opc = Cmp.getOpcode();
10125 MVT VT = Op.getSimpleValueType();
10127 bool IllegalFPCMov = false;
10128 if (VT.isFloatingPoint() && !VT.isVector() &&
10129 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10130 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10132 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10133 Opc == X86ISD::BT) { // FIXME
10137 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10138 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10139 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10140 Cond.getOperand(0).getValueType() != MVT::i8)) {
10141 SDValue LHS = Cond.getOperand(0);
10142 SDValue RHS = Cond.getOperand(1);
10143 unsigned X86Opcode;
10146 switch (CondOpcode) {
10147 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10148 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10149 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10150 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10151 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10152 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10153 default: llvm_unreachable("unexpected overflowing operator");
10155 if (CondOpcode == ISD::UMULO)
10156 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10159 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10161 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10163 if (CondOpcode == ISD::UMULO)
10164 Cond = X86Op.getValue(2);
10166 Cond = X86Op.getValue(1);
10168 CC = DAG.getConstant(X86Cond, MVT::i8);
10173 // Look pass the truncate if the high bits are known zero.
10174 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10175 Cond = Cond.getOperand(0);
10177 // We know the result of AND is compared against zero. Try to match
10179 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10180 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10181 if (NewSetCC.getNode()) {
10182 CC = NewSetCC.getOperand(0);
10183 Cond = NewSetCC.getOperand(1);
10190 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10191 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10194 // a < b ? -1 : 0 -> RES = ~setcc_carry
10195 // a < b ? 0 : -1 -> RES = setcc_carry
10196 // a >= b ? -1 : 0 -> RES = setcc_carry
10197 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10198 if (Cond.getOpcode() == X86ISD::SUB) {
10199 Cond = ConvertCmpIfNecessary(Cond, DAG);
10200 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10202 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10203 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10204 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10205 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10206 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10207 return DAG.getNOT(DL, Res, Res.getValueType());
10212 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10213 // widen the cmov and push the truncate through. This avoids introducing a new
10214 // branch during isel and doesn't add any extensions.
10215 if (Op.getValueType() == MVT::i8 &&
10216 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10217 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10218 if (T1.getValueType() == T2.getValueType() &&
10219 // Blacklist CopyFromReg to avoid partial register stalls.
10220 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10221 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10222 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10223 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10227 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10228 // condition is true.
10229 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10230 SDValue Ops[] = { Op2, Op1, CC, Cond };
10231 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10234 SDValue X86TargetLowering::LowerSIGN_EXTEND_AVX512(SDValue Op,
10235 SelectionDAG &DAG) const {
10236 EVT VT = Op->getValueType(0);
10237 SDValue In = Op->getOperand(0);
10238 EVT InVT = In.getValueType();
10241 if (InVT.getVectorElementType().getSizeInBits() >=8 &&
10242 VT.getVectorElementType().getSizeInBits() >= 32)
10243 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10245 if (InVT.getVectorElementType() == MVT::i1) {
10246 unsigned int NumElts = InVT.getVectorNumElements();
10247 assert ((NumElts == 8 || NumElts == 16) &&
10248 "Unsupported SIGN_EXTEND operation");
10249 if (VT.getVectorElementType().getSizeInBits() >= 32) {
10251 ConstantInt::get(*DAG.getContext(),
10252 (NumElts == 8)? APInt(64, ~0ULL): APInt(32, ~0U));
10253 SDValue CP = DAG.getConstantPool(C, getPointerTy());
10254 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10255 SDValue Ld = DAG.getLoad(VT.getScalarType(), dl, DAG.getEntryNode(), CP,
10256 MachinePointerInfo::getConstantPool(),
10257 false, false, false, Alignment);
10258 return DAG.getNode(X86ISD::VBROADCASTM, dl, VT, In, Ld);
10264 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10265 SelectionDAG &DAG) const {
10266 MVT VT = Op->getSimpleValueType(0);
10267 SDValue In = Op->getOperand(0);
10268 MVT InVT = In.getSimpleValueType();
10271 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10272 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10274 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10275 (VT != MVT::v8i32 || InVT != MVT::v8i16))
10278 if (Subtarget->hasInt256())
10279 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10281 // Optimize vectors in AVX mode
10282 // Sign extend v8i16 to v8i32 and
10285 // Divide input vector into two parts
10286 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10287 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10288 // concat the vectors to original VT
10290 unsigned NumElems = InVT.getVectorNumElements();
10291 SDValue Undef = DAG.getUNDEF(InVT);
10293 SmallVector<int,8> ShufMask1(NumElems, -1);
10294 for (unsigned i = 0; i != NumElems/2; ++i)
10297 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10299 SmallVector<int,8> ShufMask2(NumElems, -1);
10300 for (unsigned i = 0; i != NumElems/2; ++i)
10301 ShufMask2[i] = i + NumElems/2;
10303 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10305 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10306 VT.getVectorNumElements()/2);
10308 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10309 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10311 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10314 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10315 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10316 // from the AND / OR.
10317 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10318 Opc = Op.getOpcode();
10319 if (Opc != ISD::OR && Opc != ISD::AND)
10321 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10322 Op.getOperand(0).hasOneUse() &&
10323 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10324 Op.getOperand(1).hasOneUse());
10327 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10328 // 1 and that the SETCC node has a single use.
10329 static bool isXor1OfSetCC(SDValue Op) {
10330 if (Op.getOpcode() != ISD::XOR)
10332 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10333 if (N1C && N1C->getAPIntValue() == 1) {
10334 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10335 Op.getOperand(0).hasOneUse();
10340 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10341 bool addTest = true;
10342 SDValue Chain = Op.getOperand(0);
10343 SDValue Cond = Op.getOperand(1);
10344 SDValue Dest = Op.getOperand(2);
10347 bool Inverted = false;
10349 if (Cond.getOpcode() == ISD::SETCC) {
10350 // Check for setcc([su]{add,sub,mul}o == 0).
10351 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10352 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10353 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10354 Cond.getOperand(0).getResNo() == 1 &&
10355 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10356 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10357 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10358 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10359 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10360 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10362 Cond = Cond.getOperand(0);
10364 SDValue NewCond = LowerSETCC(Cond, DAG);
10365 if (NewCond.getNode())
10370 // FIXME: LowerXALUO doesn't handle these!!
10371 else if (Cond.getOpcode() == X86ISD::ADD ||
10372 Cond.getOpcode() == X86ISD::SUB ||
10373 Cond.getOpcode() == X86ISD::SMUL ||
10374 Cond.getOpcode() == X86ISD::UMUL)
10375 Cond = LowerXALUO(Cond, DAG);
10378 // Look pass (and (setcc_carry (cmp ...)), 1).
10379 if (Cond.getOpcode() == ISD::AND &&
10380 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10381 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10382 if (C && C->getAPIntValue() == 1)
10383 Cond = Cond.getOperand(0);
10386 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10387 // setting operand in place of the X86ISD::SETCC.
10388 unsigned CondOpcode = Cond.getOpcode();
10389 if (CondOpcode == X86ISD::SETCC ||
10390 CondOpcode == X86ISD::SETCC_CARRY) {
10391 CC = Cond.getOperand(0);
10393 SDValue Cmp = Cond.getOperand(1);
10394 unsigned Opc = Cmp.getOpcode();
10395 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10396 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10400 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10404 // These can only come from an arithmetic instruction with overflow,
10405 // e.g. SADDO, UADDO.
10406 Cond = Cond.getNode()->getOperand(1);
10412 CondOpcode = Cond.getOpcode();
10413 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10414 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10415 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10416 Cond.getOperand(0).getValueType() != MVT::i8)) {
10417 SDValue LHS = Cond.getOperand(0);
10418 SDValue RHS = Cond.getOperand(1);
10419 unsigned X86Opcode;
10422 switch (CondOpcode) {
10423 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10424 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10425 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10426 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10427 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10428 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10429 default: llvm_unreachable("unexpected overflowing operator");
10432 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10433 if (CondOpcode == ISD::UMULO)
10434 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10437 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10439 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10441 if (CondOpcode == ISD::UMULO)
10442 Cond = X86Op.getValue(2);
10444 Cond = X86Op.getValue(1);
10446 CC = DAG.getConstant(X86Cond, MVT::i8);
10450 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10451 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10452 if (CondOpc == ISD::OR) {
10453 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10454 // two branches instead of an explicit OR instruction with a
10456 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10457 isX86LogicalCmp(Cmp)) {
10458 CC = Cond.getOperand(0).getOperand(0);
10459 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10460 Chain, Dest, CC, Cmp);
10461 CC = Cond.getOperand(1).getOperand(0);
10465 } else { // ISD::AND
10466 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10467 // two branches instead of an explicit AND instruction with a
10468 // separate test. However, we only do this if this block doesn't
10469 // have a fall-through edge, because this requires an explicit
10470 // jmp when the condition is false.
10471 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10472 isX86LogicalCmp(Cmp) &&
10473 Op.getNode()->hasOneUse()) {
10474 X86::CondCode CCode =
10475 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10476 CCode = X86::GetOppositeBranchCondition(CCode);
10477 CC = DAG.getConstant(CCode, MVT::i8);
10478 SDNode *User = *Op.getNode()->use_begin();
10479 // Look for an unconditional branch following this conditional branch.
10480 // We need this because we need to reverse the successors in order
10481 // to implement FCMP_OEQ.
10482 if (User->getOpcode() == ISD::BR) {
10483 SDValue FalseBB = User->getOperand(1);
10485 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10486 assert(NewBR == User);
10490 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10491 Chain, Dest, CC, Cmp);
10492 X86::CondCode CCode =
10493 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10494 CCode = X86::GetOppositeBranchCondition(CCode);
10495 CC = DAG.getConstant(CCode, MVT::i8);
10501 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10502 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10503 // It should be transformed during dag combiner except when the condition
10504 // is set by a arithmetics with overflow node.
10505 X86::CondCode CCode =
10506 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10507 CCode = X86::GetOppositeBranchCondition(CCode);
10508 CC = DAG.getConstant(CCode, MVT::i8);
10509 Cond = Cond.getOperand(0).getOperand(1);
10511 } else if (Cond.getOpcode() == ISD::SETCC &&
10512 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10513 // For FCMP_OEQ, we can emit
10514 // two branches instead of an explicit AND instruction with a
10515 // separate test. However, we only do this if this block doesn't
10516 // have a fall-through edge, because this requires an explicit
10517 // jmp when the condition is false.
10518 if (Op.getNode()->hasOneUse()) {
10519 SDNode *User = *Op.getNode()->use_begin();
10520 // Look for an unconditional branch following this conditional branch.
10521 // We need this because we need to reverse the successors in order
10522 // to implement FCMP_OEQ.
10523 if (User->getOpcode() == ISD::BR) {
10524 SDValue FalseBB = User->getOperand(1);
10526 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10527 assert(NewBR == User);
10531 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10532 Cond.getOperand(0), Cond.getOperand(1));
10533 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10534 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10535 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10536 Chain, Dest, CC, Cmp);
10537 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10542 } else if (Cond.getOpcode() == ISD::SETCC &&
10543 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10544 // For FCMP_UNE, we can emit
10545 // two branches instead of an explicit AND instruction with a
10546 // separate test. However, we only do this if this block doesn't
10547 // have a fall-through edge, because this requires an explicit
10548 // jmp when the condition is false.
10549 if (Op.getNode()->hasOneUse()) {
10550 SDNode *User = *Op.getNode()->use_begin();
10551 // Look for an unconditional branch following this conditional branch.
10552 // We need this because we need to reverse the successors in order
10553 // to implement FCMP_UNE.
10554 if (User->getOpcode() == ISD::BR) {
10555 SDValue FalseBB = User->getOperand(1);
10557 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10558 assert(NewBR == User);
10561 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10562 Cond.getOperand(0), Cond.getOperand(1));
10563 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10564 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10565 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10566 Chain, Dest, CC, Cmp);
10567 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10577 // Look pass the truncate if the high bits are known zero.
10578 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10579 Cond = Cond.getOperand(0);
10581 // We know the result of AND is compared against zero. Try to match
10583 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10584 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10585 if (NewSetCC.getNode()) {
10586 CC = NewSetCC.getOperand(0);
10587 Cond = NewSetCC.getOperand(1);
10594 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10595 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10597 Cond = ConvertCmpIfNecessary(Cond, DAG);
10598 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10599 Chain, Dest, CC, Cond);
10602 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10603 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10604 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10605 // that the guard pages used by the OS virtual memory manager are allocated in
10606 // correct sequence.
10608 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10609 SelectionDAG &DAG) const {
10610 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10611 getTargetMachine().Options.EnableSegmentedStacks) &&
10612 "This should be used only on Windows targets or when segmented stacks "
10614 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10618 SDValue Chain = Op.getOperand(0);
10619 SDValue Size = Op.getOperand(1);
10620 // FIXME: Ensure alignment here
10622 bool Is64Bit = Subtarget->is64Bit();
10623 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10625 if (getTargetMachine().Options.EnableSegmentedStacks) {
10626 MachineFunction &MF = DAG.getMachineFunction();
10627 MachineRegisterInfo &MRI = MF.getRegInfo();
10630 // The 64 bit implementation of segmented stacks needs to clobber both r10
10631 // r11. This makes it impossible to use it along with nested parameters.
10632 const Function *F = MF.getFunction();
10634 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10636 if (I->hasNestAttr())
10637 report_fatal_error("Cannot use segmented stacks with functions that "
10638 "have nested arguments.");
10641 const TargetRegisterClass *AddrRegClass =
10642 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10643 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10644 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10645 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10646 DAG.getRegister(Vreg, SPTy));
10647 SDValue Ops1[2] = { Value, Chain };
10648 return DAG.getMergeValues(Ops1, 2, dl);
10651 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10653 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10654 Flag = Chain.getValue(1);
10655 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10657 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10658 Flag = Chain.getValue(1);
10660 const X86RegisterInfo *RegInfo =
10661 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10662 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10665 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10666 return DAG.getMergeValues(Ops1, 2, dl);
10670 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10671 MachineFunction &MF = DAG.getMachineFunction();
10672 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10674 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10677 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10678 // vastart just stores the address of the VarArgsFrameIndex slot into the
10679 // memory location argument.
10680 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10682 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10683 MachinePointerInfo(SV), false, false, 0);
10687 // gp_offset (0 - 6 * 8)
10688 // fp_offset (48 - 48 + 8 * 16)
10689 // overflow_arg_area (point to parameters coming in memory).
10691 SmallVector<SDValue, 8> MemOps;
10692 SDValue FIN = Op.getOperand(1);
10694 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10695 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10697 FIN, MachinePointerInfo(SV), false, false, 0);
10698 MemOps.push_back(Store);
10701 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10702 FIN, DAG.getIntPtrConstant(4));
10703 Store = DAG.getStore(Op.getOperand(0), DL,
10704 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10706 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10707 MemOps.push_back(Store);
10709 // Store ptr to overflow_arg_area
10710 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10711 FIN, DAG.getIntPtrConstant(4));
10712 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10714 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10715 MachinePointerInfo(SV, 8),
10717 MemOps.push_back(Store);
10719 // Store ptr to reg_save_area.
10720 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10721 FIN, DAG.getIntPtrConstant(8));
10722 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10724 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10725 MachinePointerInfo(SV, 16), false, false, 0);
10726 MemOps.push_back(Store);
10727 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10728 &MemOps[0], MemOps.size());
10731 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10732 assert(Subtarget->is64Bit() &&
10733 "LowerVAARG only handles 64-bit va_arg!");
10734 assert((Subtarget->isTargetLinux() ||
10735 Subtarget->isTargetDarwin()) &&
10736 "Unhandled target in LowerVAARG");
10737 assert(Op.getNode()->getNumOperands() == 4);
10738 SDValue Chain = Op.getOperand(0);
10739 SDValue SrcPtr = Op.getOperand(1);
10740 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10741 unsigned Align = Op.getConstantOperandVal(3);
10744 EVT ArgVT = Op.getNode()->getValueType(0);
10745 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10746 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10749 // Decide which area this value should be read from.
10750 // TODO: Implement the AMD64 ABI in its entirety. This simple
10751 // selection mechanism works only for the basic types.
10752 if (ArgVT == MVT::f80) {
10753 llvm_unreachable("va_arg for f80 not yet implemented");
10754 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10755 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10756 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10757 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10759 llvm_unreachable("Unhandled argument type in LowerVAARG");
10762 if (ArgMode == 2) {
10763 // Sanity Check: Make sure using fp_offset makes sense.
10764 assert(!getTargetMachine().Options.UseSoftFloat &&
10765 !(DAG.getMachineFunction()
10766 .getFunction()->getAttributes()
10767 .hasAttribute(AttributeSet::FunctionIndex,
10768 Attribute::NoImplicitFloat)) &&
10769 Subtarget->hasSSE1());
10772 // Insert VAARG_64 node into the DAG
10773 // VAARG_64 returns two values: Variable Argument Address, Chain
10774 SmallVector<SDValue, 11> InstOps;
10775 InstOps.push_back(Chain);
10776 InstOps.push_back(SrcPtr);
10777 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10778 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10779 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10780 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10781 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10782 VTs, &InstOps[0], InstOps.size(),
10784 MachinePointerInfo(SV),
10786 /*Volatile=*/false,
10788 /*WriteMem=*/true);
10789 Chain = VAARG.getValue(1);
10791 // Load the next argument and return it
10792 return DAG.getLoad(ArgVT, dl,
10795 MachinePointerInfo(),
10796 false, false, false, 0);
10799 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10800 SelectionDAG &DAG) {
10801 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10802 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10803 SDValue Chain = Op.getOperand(0);
10804 SDValue DstPtr = Op.getOperand(1);
10805 SDValue SrcPtr = Op.getOperand(2);
10806 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10807 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10810 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10811 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10813 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10816 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10817 // may or may not be a constant. Takes immediate version of shift as input.
10818 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10819 SDValue SrcOp, SDValue ShAmt,
10820 SelectionDAG &DAG) {
10821 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10823 if (isa<ConstantSDNode>(ShAmt)) {
10824 // Constant may be a TargetConstant. Use a regular constant.
10825 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10827 default: llvm_unreachable("Unknown target vector shift node");
10828 case X86ISD::VSHLI:
10829 case X86ISD::VSRLI:
10830 case X86ISD::VSRAI:
10831 return DAG.getNode(Opc, dl, VT, SrcOp,
10832 DAG.getConstant(ShiftAmt, MVT::i32));
10836 // Change opcode to non-immediate version
10838 default: llvm_unreachable("Unknown target vector shift node");
10839 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10840 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10841 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10844 // Need to build a vector containing shift amount
10845 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10848 ShOps[1] = DAG.getConstant(0, MVT::i32);
10849 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10850 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10852 // The return type has to be a 128-bit type with the same element
10853 // type as the input type.
10854 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10855 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10857 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10858 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10861 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10863 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10865 default: return SDValue(); // Don't custom lower most intrinsics.
10866 // Comparison intrinsics.
10867 case Intrinsic::x86_sse_comieq_ss:
10868 case Intrinsic::x86_sse_comilt_ss:
10869 case Intrinsic::x86_sse_comile_ss:
10870 case Intrinsic::x86_sse_comigt_ss:
10871 case Intrinsic::x86_sse_comige_ss:
10872 case Intrinsic::x86_sse_comineq_ss:
10873 case Intrinsic::x86_sse_ucomieq_ss:
10874 case Intrinsic::x86_sse_ucomilt_ss:
10875 case Intrinsic::x86_sse_ucomile_ss:
10876 case Intrinsic::x86_sse_ucomigt_ss:
10877 case Intrinsic::x86_sse_ucomige_ss:
10878 case Intrinsic::x86_sse_ucomineq_ss:
10879 case Intrinsic::x86_sse2_comieq_sd:
10880 case Intrinsic::x86_sse2_comilt_sd:
10881 case Intrinsic::x86_sse2_comile_sd:
10882 case Intrinsic::x86_sse2_comigt_sd:
10883 case Intrinsic::x86_sse2_comige_sd:
10884 case Intrinsic::x86_sse2_comineq_sd:
10885 case Intrinsic::x86_sse2_ucomieq_sd:
10886 case Intrinsic::x86_sse2_ucomilt_sd:
10887 case Intrinsic::x86_sse2_ucomile_sd:
10888 case Intrinsic::x86_sse2_ucomigt_sd:
10889 case Intrinsic::x86_sse2_ucomige_sd:
10890 case Intrinsic::x86_sse2_ucomineq_sd: {
10894 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10895 case Intrinsic::x86_sse_comieq_ss:
10896 case Intrinsic::x86_sse2_comieq_sd:
10897 Opc = X86ISD::COMI;
10900 case Intrinsic::x86_sse_comilt_ss:
10901 case Intrinsic::x86_sse2_comilt_sd:
10902 Opc = X86ISD::COMI;
10905 case Intrinsic::x86_sse_comile_ss:
10906 case Intrinsic::x86_sse2_comile_sd:
10907 Opc = X86ISD::COMI;
10910 case Intrinsic::x86_sse_comigt_ss:
10911 case Intrinsic::x86_sse2_comigt_sd:
10912 Opc = X86ISD::COMI;
10915 case Intrinsic::x86_sse_comige_ss:
10916 case Intrinsic::x86_sse2_comige_sd:
10917 Opc = X86ISD::COMI;
10920 case Intrinsic::x86_sse_comineq_ss:
10921 case Intrinsic::x86_sse2_comineq_sd:
10922 Opc = X86ISD::COMI;
10925 case Intrinsic::x86_sse_ucomieq_ss:
10926 case Intrinsic::x86_sse2_ucomieq_sd:
10927 Opc = X86ISD::UCOMI;
10930 case Intrinsic::x86_sse_ucomilt_ss:
10931 case Intrinsic::x86_sse2_ucomilt_sd:
10932 Opc = X86ISD::UCOMI;
10935 case Intrinsic::x86_sse_ucomile_ss:
10936 case Intrinsic::x86_sse2_ucomile_sd:
10937 Opc = X86ISD::UCOMI;
10940 case Intrinsic::x86_sse_ucomigt_ss:
10941 case Intrinsic::x86_sse2_ucomigt_sd:
10942 Opc = X86ISD::UCOMI;
10945 case Intrinsic::x86_sse_ucomige_ss:
10946 case Intrinsic::x86_sse2_ucomige_sd:
10947 Opc = X86ISD::UCOMI;
10950 case Intrinsic::x86_sse_ucomineq_ss:
10951 case Intrinsic::x86_sse2_ucomineq_sd:
10952 Opc = X86ISD::UCOMI;
10957 SDValue LHS = Op.getOperand(1);
10958 SDValue RHS = Op.getOperand(2);
10959 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10960 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10961 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10962 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10963 DAG.getConstant(X86CC, MVT::i8), Cond);
10964 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10967 // Arithmetic intrinsics.
10968 case Intrinsic::x86_sse2_pmulu_dq:
10969 case Intrinsic::x86_avx2_pmulu_dq:
10970 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10971 Op.getOperand(1), Op.getOperand(2));
10973 // SSE2/AVX2 sub with unsigned saturation intrinsics
10974 case Intrinsic::x86_sse2_psubus_b:
10975 case Intrinsic::x86_sse2_psubus_w:
10976 case Intrinsic::x86_avx2_psubus_b:
10977 case Intrinsic::x86_avx2_psubus_w:
10978 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10979 Op.getOperand(1), Op.getOperand(2));
10981 // SSE3/AVX horizontal add/sub intrinsics
10982 case Intrinsic::x86_sse3_hadd_ps:
10983 case Intrinsic::x86_sse3_hadd_pd:
10984 case Intrinsic::x86_avx_hadd_ps_256:
10985 case Intrinsic::x86_avx_hadd_pd_256:
10986 case Intrinsic::x86_sse3_hsub_ps:
10987 case Intrinsic::x86_sse3_hsub_pd:
10988 case Intrinsic::x86_avx_hsub_ps_256:
10989 case Intrinsic::x86_avx_hsub_pd_256:
10990 case Intrinsic::x86_ssse3_phadd_w_128:
10991 case Intrinsic::x86_ssse3_phadd_d_128:
10992 case Intrinsic::x86_avx2_phadd_w:
10993 case Intrinsic::x86_avx2_phadd_d:
10994 case Intrinsic::x86_ssse3_phsub_w_128:
10995 case Intrinsic::x86_ssse3_phsub_d_128:
10996 case Intrinsic::x86_avx2_phsub_w:
10997 case Intrinsic::x86_avx2_phsub_d: {
11000 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11001 case Intrinsic::x86_sse3_hadd_ps:
11002 case Intrinsic::x86_sse3_hadd_pd:
11003 case Intrinsic::x86_avx_hadd_ps_256:
11004 case Intrinsic::x86_avx_hadd_pd_256:
11005 Opcode = X86ISD::FHADD;
11007 case Intrinsic::x86_sse3_hsub_ps:
11008 case Intrinsic::x86_sse3_hsub_pd:
11009 case Intrinsic::x86_avx_hsub_ps_256:
11010 case Intrinsic::x86_avx_hsub_pd_256:
11011 Opcode = X86ISD::FHSUB;
11013 case Intrinsic::x86_ssse3_phadd_w_128:
11014 case Intrinsic::x86_ssse3_phadd_d_128:
11015 case Intrinsic::x86_avx2_phadd_w:
11016 case Intrinsic::x86_avx2_phadd_d:
11017 Opcode = X86ISD::HADD;
11019 case Intrinsic::x86_ssse3_phsub_w_128:
11020 case Intrinsic::x86_ssse3_phsub_d_128:
11021 case Intrinsic::x86_avx2_phsub_w:
11022 case Intrinsic::x86_avx2_phsub_d:
11023 Opcode = X86ISD::HSUB;
11026 return DAG.getNode(Opcode, dl, Op.getValueType(),
11027 Op.getOperand(1), Op.getOperand(2));
11030 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11031 case Intrinsic::x86_sse2_pmaxu_b:
11032 case Intrinsic::x86_sse41_pmaxuw:
11033 case Intrinsic::x86_sse41_pmaxud:
11034 case Intrinsic::x86_avx2_pmaxu_b:
11035 case Intrinsic::x86_avx2_pmaxu_w:
11036 case Intrinsic::x86_avx2_pmaxu_d:
11037 case Intrinsic::x86_sse2_pminu_b:
11038 case Intrinsic::x86_sse41_pminuw:
11039 case Intrinsic::x86_sse41_pminud:
11040 case Intrinsic::x86_avx2_pminu_b:
11041 case Intrinsic::x86_avx2_pminu_w:
11042 case Intrinsic::x86_avx2_pminu_d:
11043 case Intrinsic::x86_sse41_pmaxsb:
11044 case Intrinsic::x86_sse2_pmaxs_w:
11045 case Intrinsic::x86_sse41_pmaxsd:
11046 case Intrinsic::x86_avx2_pmaxs_b:
11047 case Intrinsic::x86_avx2_pmaxs_w:
11048 case Intrinsic::x86_avx2_pmaxs_d:
11049 case Intrinsic::x86_sse41_pminsb:
11050 case Intrinsic::x86_sse2_pmins_w:
11051 case Intrinsic::x86_sse41_pminsd:
11052 case Intrinsic::x86_avx2_pmins_b:
11053 case Intrinsic::x86_avx2_pmins_w:
11054 case Intrinsic::x86_avx2_pmins_d: {
11057 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11058 case Intrinsic::x86_sse2_pmaxu_b:
11059 case Intrinsic::x86_sse41_pmaxuw:
11060 case Intrinsic::x86_sse41_pmaxud:
11061 case Intrinsic::x86_avx2_pmaxu_b:
11062 case Intrinsic::x86_avx2_pmaxu_w:
11063 case Intrinsic::x86_avx2_pmaxu_d:
11064 Opcode = X86ISD::UMAX;
11066 case Intrinsic::x86_sse2_pminu_b:
11067 case Intrinsic::x86_sse41_pminuw:
11068 case Intrinsic::x86_sse41_pminud:
11069 case Intrinsic::x86_avx2_pminu_b:
11070 case Intrinsic::x86_avx2_pminu_w:
11071 case Intrinsic::x86_avx2_pminu_d:
11072 Opcode = X86ISD::UMIN;
11074 case Intrinsic::x86_sse41_pmaxsb:
11075 case Intrinsic::x86_sse2_pmaxs_w:
11076 case Intrinsic::x86_sse41_pmaxsd:
11077 case Intrinsic::x86_avx2_pmaxs_b:
11078 case Intrinsic::x86_avx2_pmaxs_w:
11079 case Intrinsic::x86_avx2_pmaxs_d:
11080 Opcode = X86ISD::SMAX;
11082 case Intrinsic::x86_sse41_pminsb:
11083 case Intrinsic::x86_sse2_pmins_w:
11084 case Intrinsic::x86_sse41_pminsd:
11085 case Intrinsic::x86_avx2_pmins_b:
11086 case Intrinsic::x86_avx2_pmins_w:
11087 case Intrinsic::x86_avx2_pmins_d:
11088 Opcode = X86ISD::SMIN;
11091 return DAG.getNode(Opcode, dl, Op.getValueType(),
11092 Op.getOperand(1), Op.getOperand(2));
11095 // SSE/SSE2/AVX floating point max/min intrinsics.
11096 case Intrinsic::x86_sse_max_ps:
11097 case Intrinsic::x86_sse2_max_pd:
11098 case Intrinsic::x86_avx_max_ps_256:
11099 case Intrinsic::x86_avx_max_pd_256:
11100 case Intrinsic::x86_sse_min_ps:
11101 case Intrinsic::x86_sse2_min_pd:
11102 case Intrinsic::x86_avx_min_ps_256:
11103 case Intrinsic::x86_avx_min_pd_256: {
11106 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11107 case Intrinsic::x86_sse_max_ps:
11108 case Intrinsic::x86_sse2_max_pd:
11109 case Intrinsic::x86_avx_max_ps_256:
11110 case Intrinsic::x86_avx_max_pd_256:
11111 Opcode = X86ISD::FMAX;
11113 case Intrinsic::x86_sse_min_ps:
11114 case Intrinsic::x86_sse2_min_pd:
11115 case Intrinsic::x86_avx_min_ps_256:
11116 case Intrinsic::x86_avx_min_pd_256:
11117 Opcode = X86ISD::FMIN;
11120 return DAG.getNode(Opcode, dl, Op.getValueType(),
11121 Op.getOperand(1), Op.getOperand(2));
11124 // AVX2 variable shift intrinsics
11125 case Intrinsic::x86_avx2_psllv_d:
11126 case Intrinsic::x86_avx2_psllv_q:
11127 case Intrinsic::x86_avx2_psllv_d_256:
11128 case Intrinsic::x86_avx2_psllv_q_256:
11129 case Intrinsic::x86_avx2_psrlv_d:
11130 case Intrinsic::x86_avx2_psrlv_q:
11131 case Intrinsic::x86_avx2_psrlv_d_256:
11132 case Intrinsic::x86_avx2_psrlv_q_256:
11133 case Intrinsic::x86_avx2_psrav_d:
11134 case Intrinsic::x86_avx2_psrav_d_256: {
11137 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11138 case Intrinsic::x86_avx2_psllv_d:
11139 case Intrinsic::x86_avx2_psllv_q:
11140 case Intrinsic::x86_avx2_psllv_d_256:
11141 case Intrinsic::x86_avx2_psllv_q_256:
11144 case Intrinsic::x86_avx2_psrlv_d:
11145 case Intrinsic::x86_avx2_psrlv_q:
11146 case Intrinsic::x86_avx2_psrlv_d_256:
11147 case Intrinsic::x86_avx2_psrlv_q_256:
11150 case Intrinsic::x86_avx2_psrav_d:
11151 case Intrinsic::x86_avx2_psrav_d_256:
11155 return DAG.getNode(Opcode, dl, Op.getValueType(),
11156 Op.getOperand(1), Op.getOperand(2));
11159 case Intrinsic::x86_ssse3_pshuf_b_128:
11160 case Intrinsic::x86_avx2_pshuf_b:
11161 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11162 Op.getOperand(1), Op.getOperand(2));
11164 case Intrinsic::x86_ssse3_psign_b_128:
11165 case Intrinsic::x86_ssse3_psign_w_128:
11166 case Intrinsic::x86_ssse3_psign_d_128:
11167 case Intrinsic::x86_avx2_psign_b:
11168 case Intrinsic::x86_avx2_psign_w:
11169 case Intrinsic::x86_avx2_psign_d:
11170 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11171 Op.getOperand(1), Op.getOperand(2));
11173 case Intrinsic::x86_sse41_insertps:
11174 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11175 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11177 case Intrinsic::x86_avx_vperm2f128_ps_256:
11178 case Intrinsic::x86_avx_vperm2f128_pd_256:
11179 case Intrinsic::x86_avx_vperm2f128_si_256:
11180 case Intrinsic::x86_avx2_vperm2i128:
11181 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11182 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11184 case Intrinsic::x86_avx2_permd:
11185 case Intrinsic::x86_avx2_permps:
11186 // Operands intentionally swapped. Mask is last operand to intrinsic,
11187 // but second operand for node/intruction.
11188 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11189 Op.getOperand(2), Op.getOperand(1));
11191 case Intrinsic::x86_sse_sqrt_ps:
11192 case Intrinsic::x86_sse2_sqrt_pd:
11193 case Intrinsic::x86_avx_sqrt_ps_256:
11194 case Intrinsic::x86_avx_sqrt_pd_256:
11195 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11197 // ptest and testp intrinsics. The intrinsic these come from are designed to
11198 // return an integer value, not just an instruction so lower it to the ptest
11199 // or testp pattern and a setcc for the result.
11200 case Intrinsic::x86_sse41_ptestz:
11201 case Intrinsic::x86_sse41_ptestc:
11202 case Intrinsic::x86_sse41_ptestnzc:
11203 case Intrinsic::x86_avx_ptestz_256:
11204 case Intrinsic::x86_avx_ptestc_256:
11205 case Intrinsic::x86_avx_ptestnzc_256:
11206 case Intrinsic::x86_avx_vtestz_ps:
11207 case Intrinsic::x86_avx_vtestc_ps:
11208 case Intrinsic::x86_avx_vtestnzc_ps:
11209 case Intrinsic::x86_avx_vtestz_pd:
11210 case Intrinsic::x86_avx_vtestc_pd:
11211 case Intrinsic::x86_avx_vtestnzc_pd:
11212 case Intrinsic::x86_avx_vtestz_ps_256:
11213 case Intrinsic::x86_avx_vtestc_ps_256:
11214 case Intrinsic::x86_avx_vtestnzc_ps_256:
11215 case Intrinsic::x86_avx_vtestz_pd_256:
11216 case Intrinsic::x86_avx_vtestc_pd_256:
11217 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11218 bool IsTestPacked = false;
11221 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11222 case Intrinsic::x86_avx_vtestz_ps:
11223 case Intrinsic::x86_avx_vtestz_pd:
11224 case Intrinsic::x86_avx_vtestz_ps_256:
11225 case Intrinsic::x86_avx_vtestz_pd_256:
11226 IsTestPacked = true; // Fallthrough
11227 case Intrinsic::x86_sse41_ptestz:
11228 case Intrinsic::x86_avx_ptestz_256:
11230 X86CC = X86::COND_E;
11232 case Intrinsic::x86_avx_vtestc_ps:
11233 case Intrinsic::x86_avx_vtestc_pd:
11234 case Intrinsic::x86_avx_vtestc_ps_256:
11235 case Intrinsic::x86_avx_vtestc_pd_256:
11236 IsTestPacked = true; // Fallthrough
11237 case Intrinsic::x86_sse41_ptestc:
11238 case Intrinsic::x86_avx_ptestc_256:
11240 X86CC = X86::COND_B;
11242 case Intrinsic::x86_avx_vtestnzc_ps:
11243 case Intrinsic::x86_avx_vtestnzc_pd:
11244 case Intrinsic::x86_avx_vtestnzc_ps_256:
11245 case Intrinsic::x86_avx_vtestnzc_pd_256:
11246 IsTestPacked = true; // Fallthrough
11247 case Intrinsic::x86_sse41_ptestnzc:
11248 case Intrinsic::x86_avx_ptestnzc_256:
11250 X86CC = X86::COND_A;
11254 SDValue LHS = Op.getOperand(1);
11255 SDValue RHS = Op.getOperand(2);
11256 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11257 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11258 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11259 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11260 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11263 // SSE/AVX shift intrinsics
11264 case Intrinsic::x86_sse2_psll_w:
11265 case Intrinsic::x86_sse2_psll_d:
11266 case Intrinsic::x86_sse2_psll_q:
11267 case Intrinsic::x86_avx2_psll_w:
11268 case Intrinsic::x86_avx2_psll_d:
11269 case Intrinsic::x86_avx2_psll_q:
11270 case Intrinsic::x86_sse2_psrl_w:
11271 case Intrinsic::x86_sse2_psrl_d:
11272 case Intrinsic::x86_sse2_psrl_q:
11273 case Intrinsic::x86_avx2_psrl_w:
11274 case Intrinsic::x86_avx2_psrl_d:
11275 case Intrinsic::x86_avx2_psrl_q:
11276 case Intrinsic::x86_sse2_psra_w:
11277 case Intrinsic::x86_sse2_psra_d:
11278 case Intrinsic::x86_avx2_psra_w:
11279 case Intrinsic::x86_avx2_psra_d: {
11282 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11283 case Intrinsic::x86_sse2_psll_w:
11284 case Intrinsic::x86_sse2_psll_d:
11285 case Intrinsic::x86_sse2_psll_q:
11286 case Intrinsic::x86_avx2_psll_w:
11287 case Intrinsic::x86_avx2_psll_d:
11288 case Intrinsic::x86_avx2_psll_q:
11289 Opcode = X86ISD::VSHL;
11291 case Intrinsic::x86_sse2_psrl_w:
11292 case Intrinsic::x86_sse2_psrl_d:
11293 case Intrinsic::x86_sse2_psrl_q:
11294 case Intrinsic::x86_avx2_psrl_w:
11295 case Intrinsic::x86_avx2_psrl_d:
11296 case Intrinsic::x86_avx2_psrl_q:
11297 Opcode = X86ISD::VSRL;
11299 case Intrinsic::x86_sse2_psra_w:
11300 case Intrinsic::x86_sse2_psra_d:
11301 case Intrinsic::x86_avx2_psra_w:
11302 case Intrinsic::x86_avx2_psra_d:
11303 Opcode = X86ISD::VSRA;
11306 return DAG.getNode(Opcode, dl, Op.getValueType(),
11307 Op.getOperand(1), Op.getOperand(2));
11310 // SSE/AVX immediate shift intrinsics
11311 case Intrinsic::x86_sse2_pslli_w:
11312 case Intrinsic::x86_sse2_pslli_d:
11313 case Intrinsic::x86_sse2_pslli_q:
11314 case Intrinsic::x86_avx2_pslli_w:
11315 case Intrinsic::x86_avx2_pslli_d:
11316 case Intrinsic::x86_avx2_pslli_q:
11317 case Intrinsic::x86_sse2_psrli_w:
11318 case Intrinsic::x86_sse2_psrli_d:
11319 case Intrinsic::x86_sse2_psrli_q:
11320 case Intrinsic::x86_avx2_psrli_w:
11321 case Intrinsic::x86_avx2_psrli_d:
11322 case Intrinsic::x86_avx2_psrli_q:
11323 case Intrinsic::x86_sse2_psrai_w:
11324 case Intrinsic::x86_sse2_psrai_d:
11325 case Intrinsic::x86_avx2_psrai_w:
11326 case Intrinsic::x86_avx2_psrai_d: {
11329 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11330 case Intrinsic::x86_sse2_pslli_w:
11331 case Intrinsic::x86_sse2_pslli_d:
11332 case Intrinsic::x86_sse2_pslli_q:
11333 case Intrinsic::x86_avx2_pslli_w:
11334 case Intrinsic::x86_avx2_pslli_d:
11335 case Intrinsic::x86_avx2_pslli_q:
11336 Opcode = X86ISD::VSHLI;
11338 case Intrinsic::x86_sse2_psrli_w:
11339 case Intrinsic::x86_sse2_psrli_d:
11340 case Intrinsic::x86_sse2_psrli_q:
11341 case Intrinsic::x86_avx2_psrli_w:
11342 case Intrinsic::x86_avx2_psrli_d:
11343 case Intrinsic::x86_avx2_psrli_q:
11344 Opcode = X86ISD::VSRLI;
11346 case Intrinsic::x86_sse2_psrai_w:
11347 case Intrinsic::x86_sse2_psrai_d:
11348 case Intrinsic::x86_avx2_psrai_w:
11349 case Intrinsic::x86_avx2_psrai_d:
11350 Opcode = X86ISD::VSRAI;
11353 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11354 Op.getOperand(1), Op.getOperand(2), DAG);
11357 case Intrinsic::x86_sse42_pcmpistria128:
11358 case Intrinsic::x86_sse42_pcmpestria128:
11359 case Intrinsic::x86_sse42_pcmpistric128:
11360 case Intrinsic::x86_sse42_pcmpestric128:
11361 case Intrinsic::x86_sse42_pcmpistrio128:
11362 case Intrinsic::x86_sse42_pcmpestrio128:
11363 case Intrinsic::x86_sse42_pcmpistris128:
11364 case Intrinsic::x86_sse42_pcmpestris128:
11365 case Intrinsic::x86_sse42_pcmpistriz128:
11366 case Intrinsic::x86_sse42_pcmpestriz128: {
11370 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11371 case Intrinsic::x86_sse42_pcmpistria128:
11372 Opcode = X86ISD::PCMPISTRI;
11373 X86CC = X86::COND_A;
11375 case Intrinsic::x86_sse42_pcmpestria128:
11376 Opcode = X86ISD::PCMPESTRI;
11377 X86CC = X86::COND_A;
11379 case Intrinsic::x86_sse42_pcmpistric128:
11380 Opcode = X86ISD::PCMPISTRI;
11381 X86CC = X86::COND_B;
11383 case Intrinsic::x86_sse42_pcmpestric128:
11384 Opcode = X86ISD::PCMPESTRI;
11385 X86CC = X86::COND_B;
11387 case Intrinsic::x86_sse42_pcmpistrio128:
11388 Opcode = X86ISD::PCMPISTRI;
11389 X86CC = X86::COND_O;
11391 case Intrinsic::x86_sse42_pcmpestrio128:
11392 Opcode = X86ISD::PCMPESTRI;
11393 X86CC = X86::COND_O;
11395 case Intrinsic::x86_sse42_pcmpistris128:
11396 Opcode = X86ISD::PCMPISTRI;
11397 X86CC = X86::COND_S;
11399 case Intrinsic::x86_sse42_pcmpestris128:
11400 Opcode = X86ISD::PCMPESTRI;
11401 X86CC = X86::COND_S;
11403 case Intrinsic::x86_sse42_pcmpistriz128:
11404 Opcode = X86ISD::PCMPISTRI;
11405 X86CC = X86::COND_E;
11407 case Intrinsic::x86_sse42_pcmpestriz128:
11408 Opcode = X86ISD::PCMPESTRI;
11409 X86CC = X86::COND_E;
11412 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11413 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11414 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11415 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11416 DAG.getConstant(X86CC, MVT::i8),
11417 SDValue(PCMP.getNode(), 1));
11418 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11421 case Intrinsic::x86_sse42_pcmpistri128:
11422 case Intrinsic::x86_sse42_pcmpestri128: {
11424 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11425 Opcode = X86ISD::PCMPISTRI;
11427 Opcode = X86ISD::PCMPESTRI;
11429 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11430 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11431 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11433 case Intrinsic::x86_fma_vfmadd_ps:
11434 case Intrinsic::x86_fma_vfmadd_pd:
11435 case Intrinsic::x86_fma_vfmsub_ps:
11436 case Intrinsic::x86_fma_vfmsub_pd:
11437 case Intrinsic::x86_fma_vfnmadd_ps:
11438 case Intrinsic::x86_fma_vfnmadd_pd:
11439 case Intrinsic::x86_fma_vfnmsub_ps:
11440 case Intrinsic::x86_fma_vfnmsub_pd:
11441 case Intrinsic::x86_fma_vfmaddsub_ps:
11442 case Intrinsic::x86_fma_vfmaddsub_pd:
11443 case Intrinsic::x86_fma_vfmsubadd_ps:
11444 case Intrinsic::x86_fma_vfmsubadd_pd:
11445 case Intrinsic::x86_fma_vfmadd_ps_256:
11446 case Intrinsic::x86_fma_vfmadd_pd_256:
11447 case Intrinsic::x86_fma_vfmsub_ps_256:
11448 case Intrinsic::x86_fma_vfmsub_pd_256:
11449 case Intrinsic::x86_fma_vfnmadd_ps_256:
11450 case Intrinsic::x86_fma_vfnmadd_pd_256:
11451 case Intrinsic::x86_fma_vfnmsub_ps_256:
11452 case Intrinsic::x86_fma_vfnmsub_pd_256:
11453 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11454 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11455 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11456 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11459 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11460 case Intrinsic::x86_fma_vfmadd_ps:
11461 case Intrinsic::x86_fma_vfmadd_pd:
11462 case Intrinsic::x86_fma_vfmadd_ps_256:
11463 case Intrinsic::x86_fma_vfmadd_pd_256:
11464 Opc = X86ISD::FMADD;
11466 case Intrinsic::x86_fma_vfmsub_ps:
11467 case Intrinsic::x86_fma_vfmsub_pd:
11468 case Intrinsic::x86_fma_vfmsub_ps_256:
11469 case Intrinsic::x86_fma_vfmsub_pd_256:
11470 Opc = X86ISD::FMSUB;
11472 case Intrinsic::x86_fma_vfnmadd_ps:
11473 case Intrinsic::x86_fma_vfnmadd_pd:
11474 case Intrinsic::x86_fma_vfnmadd_ps_256:
11475 case Intrinsic::x86_fma_vfnmadd_pd_256:
11476 Opc = X86ISD::FNMADD;
11478 case Intrinsic::x86_fma_vfnmsub_ps:
11479 case Intrinsic::x86_fma_vfnmsub_pd:
11480 case Intrinsic::x86_fma_vfnmsub_ps_256:
11481 case Intrinsic::x86_fma_vfnmsub_pd_256:
11482 Opc = X86ISD::FNMSUB;
11484 case Intrinsic::x86_fma_vfmaddsub_ps:
11485 case Intrinsic::x86_fma_vfmaddsub_pd:
11486 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11487 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11488 Opc = X86ISD::FMADDSUB;
11490 case Intrinsic::x86_fma_vfmsubadd_ps:
11491 case Intrinsic::x86_fma_vfmsubadd_pd:
11492 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11493 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11494 Opc = X86ISD::FMSUBADD;
11498 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11499 Op.getOperand(2), Op.getOperand(3));
11504 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11506 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11508 default: return SDValue(); // Don't custom lower most intrinsics.
11510 // RDRAND/RDSEED intrinsics.
11511 case Intrinsic::x86_rdrand_16:
11512 case Intrinsic::x86_rdrand_32:
11513 case Intrinsic::x86_rdrand_64:
11514 case Intrinsic::x86_rdseed_16:
11515 case Intrinsic::x86_rdseed_32:
11516 case Intrinsic::x86_rdseed_64: {
11517 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11518 IntNo == Intrinsic::x86_rdseed_32 ||
11519 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11521 // Emit the node with the right value type.
11522 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11523 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11525 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11526 // Otherwise return the value from Rand, which is always 0, casted to i32.
11527 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11528 DAG.getConstant(1, Op->getValueType(1)),
11529 DAG.getConstant(X86::COND_B, MVT::i32),
11530 SDValue(Result.getNode(), 1) };
11531 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11532 DAG.getVTList(Op->getValueType(1), MVT::Glue),
11533 Ops, array_lengthof(Ops));
11535 // Return { result, isValid, chain }.
11536 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11537 SDValue(Result.getNode(), 2));
11540 // XTEST intrinsics.
11541 case Intrinsic::x86_xtest: {
11542 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11543 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11544 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11545 DAG.getConstant(X86::COND_NE, MVT::i8),
11547 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11548 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11549 Ret, SDValue(InTrans.getNode(), 1));
11554 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11555 SelectionDAG &DAG) const {
11556 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11557 MFI->setReturnAddressIsTaken(true);
11559 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11561 EVT PtrVT = getPointerTy();
11564 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11565 const X86RegisterInfo *RegInfo =
11566 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11567 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11568 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11569 DAG.getNode(ISD::ADD, dl, PtrVT,
11570 FrameAddr, Offset),
11571 MachinePointerInfo(), false, false, false, 0);
11574 // Just load the return address.
11575 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11576 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11577 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11580 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11581 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11582 MFI->setFrameAddressIsTaken(true);
11584 EVT VT = Op.getValueType();
11585 SDLoc dl(Op); // FIXME probably not meaningful
11586 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11587 const X86RegisterInfo *RegInfo =
11588 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11589 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11590 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11591 (FrameReg == X86::EBP && VT == MVT::i32)) &&
11592 "Invalid Frame Register!");
11593 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11595 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11596 MachinePointerInfo(),
11597 false, false, false, 0);
11601 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11602 SelectionDAG &DAG) const {
11603 const X86RegisterInfo *RegInfo =
11604 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11605 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11608 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11609 SDValue Chain = Op.getOperand(0);
11610 SDValue Offset = Op.getOperand(1);
11611 SDValue Handler = Op.getOperand(2);
11614 EVT PtrVT = getPointerTy();
11615 const X86RegisterInfo *RegInfo =
11616 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11617 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11618 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11619 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11620 "Invalid Frame Register!");
11621 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11622 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11624 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11625 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11626 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11627 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11629 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11631 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11632 DAG.getRegister(StoreAddrReg, PtrVT));
11635 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11636 SelectionDAG &DAG) const {
11638 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11639 DAG.getVTList(MVT::i32, MVT::Other),
11640 Op.getOperand(0), Op.getOperand(1));
11643 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11644 SelectionDAG &DAG) const {
11646 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11647 Op.getOperand(0), Op.getOperand(1));
11650 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11651 return Op.getOperand(0);
11654 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11655 SelectionDAG &DAG) const {
11656 SDValue Root = Op.getOperand(0);
11657 SDValue Trmp = Op.getOperand(1); // trampoline
11658 SDValue FPtr = Op.getOperand(2); // nested function
11659 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11662 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11663 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11665 if (Subtarget->is64Bit()) {
11666 SDValue OutChains[6];
11668 // Large code-model.
11669 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11670 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11672 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11673 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11675 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11677 // Load the pointer to the nested function into R11.
11678 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11679 SDValue Addr = Trmp;
11680 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11681 Addr, MachinePointerInfo(TrmpAddr),
11684 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11685 DAG.getConstant(2, MVT::i64));
11686 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11687 MachinePointerInfo(TrmpAddr, 2),
11690 // Load the 'nest' parameter value into R10.
11691 // R10 is specified in X86CallingConv.td
11692 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11693 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11694 DAG.getConstant(10, MVT::i64));
11695 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11696 Addr, MachinePointerInfo(TrmpAddr, 10),
11699 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11700 DAG.getConstant(12, MVT::i64));
11701 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11702 MachinePointerInfo(TrmpAddr, 12),
11705 // Jump to the nested function.
11706 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11707 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11708 DAG.getConstant(20, MVT::i64));
11709 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11710 Addr, MachinePointerInfo(TrmpAddr, 20),
11713 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11714 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11715 DAG.getConstant(22, MVT::i64));
11716 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11717 MachinePointerInfo(TrmpAddr, 22),
11720 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11722 const Function *Func =
11723 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11724 CallingConv::ID CC = Func->getCallingConv();
11729 llvm_unreachable("Unsupported calling convention");
11730 case CallingConv::C:
11731 case CallingConv::X86_StdCall: {
11732 // Pass 'nest' parameter in ECX.
11733 // Must be kept in sync with X86CallingConv.td
11734 NestReg = X86::ECX;
11736 // Check that ECX wasn't needed by an 'inreg' parameter.
11737 FunctionType *FTy = Func->getFunctionType();
11738 const AttributeSet &Attrs = Func->getAttributes();
11740 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11741 unsigned InRegCount = 0;
11744 for (FunctionType::param_iterator I = FTy->param_begin(),
11745 E = FTy->param_end(); I != E; ++I, ++Idx)
11746 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11747 // FIXME: should only count parameters that are lowered to integers.
11748 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11750 if (InRegCount > 2) {
11751 report_fatal_error("Nest register in use - reduce number of inreg"
11757 case CallingConv::X86_FastCall:
11758 case CallingConv::X86_ThisCall:
11759 case CallingConv::Fast:
11760 // Pass 'nest' parameter in EAX.
11761 // Must be kept in sync with X86CallingConv.td
11762 NestReg = X86::EAX;
11766 SDValue OutChains[4];
11767 SDValue Addr, Disp;
11769 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11770 DAG.getConstant(10, MVT::i32));
11771 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11773 // This is storing the opcode for MOV32ri.
11774 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11775 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11776 OutChains[0] = DAG.getStore(Root, dl,
11777 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11778 Trmp, MachinePointerInfo(TrmpAddr),
11781 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11782 DAG.getConstant(1, MVT::i32));
11783 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11784 MachinePointerInfo(TrmpAddr, 1),
11787 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11788 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11789 DAG.getConstant(5, MVT::i32));
11790 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11791 MachinePointerInfo(TrmpAddr, 5),
11794 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11795 DAG.getConstant(6, MVT::i32));
11796 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11797 MachinePointerInfo(TrmpAddr, 6),
11800 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11804 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11805 SelectionDAG &DAG) const {
11807 The rounding mode is in bits 11:10 of FPSR, and has the following
11809 00 Round to nearest
11814 FLT_ROUNDS, on the other hand, expects the following:
11821 To perform the conversion, we do:
11822 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11825 MachineFunction &MF = DAG.getMachineFunction();
11826 const TargetMachine &TM = MF.getTarget();
11827 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11828 unsigned StackAlignment = TFI.getStackAlignment();
11829 EVT VT = Op.getValueType();
11832 // Save FP Control Word to stack slot
11833 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11834 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11836 MachineMemOperand *MMO =
11837 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11838 MachineMemOperand::MOStore, 2, 2);
11840 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11841 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11842 DAG.getVTList(MVT::Other),
11843 Ops, array_lengthof(Ops), MVT::i16,
11846 // Load FP Control Word from stack slot
11847 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11848 MachinePointerInfo(), false, false, false, 0);
11850 // Transform as necessary
11852 DAG.getNode(ISD::SRL, DL, MVT::i16,
11853 DAG.getNode(ISD::AND, DL, MVT::i16,
11854 CWD, DAG.getConstant(0x800, MVT::i16)),
11855 DAG.getConstant(11, MVT::i8));
11857 DAG.getNode(ISD::SRL, DL, MVT::i16,
11858 DAG.getNode(ISD::AND, DL, MVT::i16,
11859 CWD, DAG.getConstant(0x400, MVT::i16)),
11860 DAG.getConstant(9, MVT::i8));
11863 DAG.getNode(ISD::AND, DL, MVT::i16,
11864 DAG.getNode(ISD::ADD, DL, MVT::i16,
11865 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11866 DAG.getConstant(1, MVT::i16)),
11867 DAG.getConstant(3, MVT::i16));
11869 return DAG.getNode((VT.getSizeInBits() < 16 ?
11870 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11873 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11874 EVT VT = Op.getValueType();
11876 unsigned NumBits = VT.getSizeInBits();
11879 Op = Op.getOperand(0);
11880 if (VT == MVT::i8) {
11881 // Zero extend to i32 since there is not an i8 bsr.
11883 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11886 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11887 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11888 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11890 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11893 DAG.getConstant(NumBits+NumBits-1, OpVT),
11894 DAG.getConstant(X86::COND_E, MVT::i8),
11897 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11899 // Finally xor with NumBits-1.
11900 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11903 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11907 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11908 EVT VT = Op.getValueType();
11910 unsigned NumBits = VT.getSizeInBits();
11913 Op = Op.getOperand(0);
11914 if (VT == MVT::i8) {
11915 // Zero extend to i32 since there is not an i8 bsr.
11917 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11920 // Issue a bsr (scan bits in reverse).
11921 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11922 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11924 // And xor with NumBits-1.
11925 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11928 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11932 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11933 EVT VT = Op.getValueType();
11934 unsigned NumBits = VT.getSizeInBits();
11936 Op = Op.getOperand(0);
11938 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11939 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11940 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11942 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11945 DAG.getConstant(NumBits, VT),
11946 DAG.getConstant(X86::COND_E, MVT::i8),
11949 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11952 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11953 // ones, and then concatenate the result back.
11954 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11955 EVT VT = Op.getValueType();
11957 assert(VT.is256BitVector() && VT.isInteger() &&
11958 "Unsupported value type for operation");
11960 unsigned NumElems = VT.getVectorNumElements();
11963 // Extract the LHS vectors
11964 SDValue LHS = Op.getOperand(0);
11965 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11966 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11968 // Extract the RHS vectors
11969 SDValue RHS = Op.getOperand(1);
11970 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11971 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11973 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11974 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11976 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11977 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11978 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11981 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11982 assert(Op.getValueType().is256BitVector() &&
11983 Op.getValueType().isInteger() &&
11984 "Only handle AVX 256-bit vector integer operation");
11985 return Lower256IntArith(Op, DAG);
11988 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11989 assert(Op.getValueType().is256BitVector() &&
11990 Op.getValueType().isInteger() &&
11991 "Only handle AVX 256-bit vector integer operation");
11992 return Lower256IntArith(Op, DAG);
11995 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11996 SelectionDAG &DAG) {
11998 EVT VT = Op.getValueType();
12000 // Decompose 256-bit ops into smaller 128-bit ops.
12001 if (VT.is256BitVector() && !Subtarget->hasInt256())
12002 return Lower256IntArith(Op, DAG);
12004 SDValue A = Op.getOperand(0);
12005 SDValue B = Op.getOperand(1);
12007 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12008 if (VT == MVT::v4i32) {
12009 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12010 "Should not custom lower when pmuldq is available!");
12012 // Extract the odd parts.
12013 static const int UnpackMask[] = { 1, -1, 3, -1 };
12014 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12015 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12017 // Multiply the even parts.
12018 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12019 // Now multiply odd parts.
12020 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12022 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12023 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12025 // Merge the two vectors back together with a shuffle. This expands into 2
12027 static const int ShufMask[] = { 0, 4, 2, 6 };
12028 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12031 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
12032 "Only know how to lower V2I64/V4I64 multiply");
12034 // Ahi = psrlqi(a, 32);
12035 // Bhi = psrlqi(b, 32);
12037 // AloBlo = pmuludq(a, b);
12038 // AloBhi = pmuludq(a, Bhi);
12039 // AhiBlo = pmuludq(Ahi, b);
12041 // AloBhi = psllqi(AloBhi, 32);
12042 // AhiBlo = psllqi(AhiBlo, 32);
12043 // return AloBlo + AloBhi + AhiBlo;
12045 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
12047 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
12048 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
12050 // Bit cast to 32-bit vectors for MULUDQ
12051 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
12052 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12053 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12054 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12055 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12057 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12058 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12059 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12061 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
12062 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
12064 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12065 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12068 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12069 EVT VT = Op.getValueType();
12070 EVT EltTy = VT.getVectorElementType();
12071 unsigned NumElts = VT.getVectorNumElements();
12072 SDValue N0 = Op.getOperand(0);
12075 // Lower sdiv X, pow2-const.
12076 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12080 APInt SplatValue, SplatUndef;
12081 unsigned SplatBitSize;
12083 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12085 EltTy.getSizeInBits() < SplatBitSize)
12088 if ((SplatValue != 0) &&
12089 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12090 unsigned lg2 = SplatValue.countTrailingZeros();
12091 // Splat the sign bit.
12092 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
12093 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
12094 // Add (N0 < 0) ? abs2 - 1 : 0;
12095 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
12096 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
12097 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12098 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
12099 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
12101 // If we're dividing by a positive value, we're done. Otherwise, we must
12102 // negate the result.
12103 if (SplatValue.isNonNegative())
12106 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12107 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12108 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12113 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12114 const X86Subtarget *Subtarget) {
12115 EVT VT = Op.getValueType();
12117 SDValue R = Op.getOperand(0);
12118 SDValue Amt = Op.getOperand(1);
12120 // Optimize shl/srl/sra with constant shift amount.
12121 if (isSplatVector(Amt.getNode())) {
12122 SDValue SclrAmt = Amt->getOperand(0);
12123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12124 uint64_t ShiftAmt = C->getZExtValue();
12126 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12127 (Subtarget->hasInt256() &&
12128 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
12129 if (Op.getOpcode() == ISD::SHL)
12130 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12131 DAG.getConstant(ShiftAmt, MVT::i32));
12132 if (Op.getOpcode() == ISD::SRL)
12133 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12134 DAG.getConstant(ShiftAmt, MVT::i32));
12135 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12136 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12137 DAG.getConstant(ShiftAmt, MVT::i32));
12140 if (VT == MVT::v16i8) {
12141 if (Op.getOpcode() == ISD::SHL) {
12142 // Make a large shift.
12143 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
12144 DAG.getConstant(ShiftAmt, MVT::i32));
12145 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12146 // Zero out the rightmost bits.
12147 SmallVector<SDValue, 16> V(16,
12148 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12150 return DAG.getNode(ISD::AND, dl, VT, SHL,
12151 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12153 if (Op.getOpcode() == ISD::SRL) {
12154 // Make a large shift.
12155 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
12156 DAG.getConstant(ShiftAmt, MVT::i32));
12157 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12158 // Zero out the leftmost bits.
12159 SmallVector<SDValue, 16> V(16,
12160 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12162 return DAG.getNode(ISD::AND, dl, VT, SRL,
12163 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12165 if (Op.getOpcode() == ISD::SRA) {
12166 if (ShiftAmt == 7) {
12167 // R s>> 7 === R s< 0
12168 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12169 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12172 // R s>> a === ((R u>> a) ^ m) - m
12173 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12174 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12176 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12177 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12178 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12181 llvm_unreachable("Unknown shift opcode.");
12184 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12185 if (Op.getOpcode() == ISD::SHL) {
12186 // Make a large shift.
12187 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
12188 DAG.getConstant(ShiftAmt, MVT::i32));
12189 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12190 // Zero out the rightmost bits.
12191 SmallVector<SDValue, 32> V(32,
12192 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12194 return DAG.getNode(ISD::AND, dl, VT, SHL,
12195 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12197 if (Op.getOpcode() == ISD::SRL) {
12198 // Make a large shift.
12199 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
12200 DAG.getConstant(ShiftAmt, MVT::i32));
12201 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12202 // Zero out the leftmost bits.
12203 SmallVector<SDValue, 32> V(32,
12204 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12206 return DAG.getNode(ISD::AND, dl, VT, SRL,
12207 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12209 if (Op.getOpcode() == ISD::SRA) {
12210 if (ShiftAmt == 7) {
12211 // R s>> 7 === R s< 0
12212 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12213 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12216 // R s>> a === ((R u>> a) ^ m) - m
12217 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12218 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12220 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12221 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12222 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12225 llvm_unreachable("Unknown shift opcode.");
12230 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12231 if (!Subtarget->is64Bit() &&
12232 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12233 Amt.getOpcode() == ISD::BITCAST &&
12234 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12235 Amt = Amt.getOperand(0);
12236 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12237 VT.getVectorNumElements();
12238 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12239 uint64_t ShiftAmt = 0;
12240 for (unsigned i = 0; i != Ratio; ++i) {
12241 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12245 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12247 // Check remaining shift amounts.
12248 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12249 uint64_t ShAmt = 0;
12250 for (unsigned j = 0; j != Ratio; ++j) {
12251 ConstantSDNode *C =
12252 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12256 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12258 if (ShAmt != ShiftAmt)
12261 switch (Op.getOpcode()) {
12263 llvm_unreachable("Unknown shift opcode!");
12265 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12266 DAG.getConstant(ShiftAmt, MVT::i32));
12268 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12269 DAG.getConstant(ShiftAmt, MVT::i32));
12271 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12272 DAG.getConstant(ShiftAmt, MVT::i32));
12279 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12280 const X86Subtarget* Subtarget) {
12281 EVT VT = Op.getValueType();
12283 SDValue R = Op.getOperand(0);
12284 SDValue Amt = Op.getOperand(1);
12286 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12287 VT == MVT::v4i32 || VT == MVT::v8i16 ||
12288 (Subtarget->hasInt256() &&
12289 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12290 VT == MVT::v8i32 || VT == MVT::v16i16))) {
12292 EVT EltVT = VT.getVectorElementType();
12294 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12295 unsigned NumElts = VT.getVectorNumElements();
12297 for (i = 0; i != NumElts; ++i) {
12298 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12302 for (j = i; j != NumElts; ++j) {
12303 SDValue Arg = Amt.getOperand(j);
12304 if (Arg.getOpcode() == ISD::UNDEF) continue;
12305 if (Arg != Amt.getOperand(i))
12308 if (i != NumElts && j == NumElts)
12309 BaseShAmt = Amt.getOperand(i);
12311 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12312 Amt = Amt.getOperand(0);
12313 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12314 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12315 SDValue InVec = Amt.getOperand(0);
12316 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12317 unsigned NumElts = InVec.getValueType().getVectorNumElements();
12319 for (; i != NumElts; ++i) {
12320 SDValue Arg = InVec.getOperand(i);
12321 if (Arg.getOpcode() == ISD::UNDEF) continue;
12325 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12326 if (ConstantSDNode *C =
12327 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12328 unsigned SplatIdx =
12329 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12330 if (C->getZExtValue() == SplatIdx)
12331 BaseShAmt = InVec.getOperand(1);
12334 if (BaseShAmt.getNode() == 0)
12335 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12336 DAG.getIntPtrConstant(0));
12340 if (BaseShAmt.getNode()) {
12341 if (EltVT.bitsGT(MVT::i32))
12342 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12343 else if (EltVT.bitsLT(MVT::i32))
12344 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12346 switch (Op.getOpcode()) {
12348 llvm_unreachable("Unknown shift opcode!");
12350 switch (VT.getSimpleVT().SimpleTy) {
12351 default: return SDValue();
12358 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12361 switch (VT.getSimpleVT().SimpleTy) {
12362 default: return SDValue();
12367 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12370 switch (VT.getSimpleVT().SimpleTy) {
12371 default: return SDValue();
12378 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12384 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12385 if (!Subtarget->is64Bit() &&
12386 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12387 Amt.getOpcode() == ISD::BITCAST &&
12388 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12389 Amt = Amt.getOperand(0);
12390 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12391 VT.getVectorNumElements();
12392 std::vector<SDValue> Vals(Ratio);
12393 for (unsigned i = 0; i != Ratio; ++i)
12394 Vals[i] = Amt.getOperand(i);
12395 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12396 for (unsigned j = 0; j != Ratio; ++j)
12397 if (Vals[j] != Amt.getOperand(i + j))
12400 switch (Op.getOpcode()) {
12402 llvm_unreachable("Unknown shift opcode!");
12404 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12406 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12408 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12415 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
12416 SelectionDAG &DAG) {
12418 EVT VT = Op.getValueType();
12420 SDValue R = Op.getOperand(0);
12421 SDValue Amt = Op.getOperand(1);
12424 if (!Subtarget->hasSSE2())
12427 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12431 V = LowerScalarVariableShift(Op, DAG, Subtarget);
12435 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12436 if (Subtarget->hasInt256()) {
12437 if (Op.getOpcode() == ISD::SRL &&
12438 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12439 VT == MVT::v4i64 || VT == MVT::v8i32))
12441 if (Op.getOpcode() == ISD::SHL &&
12442 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12443 VT == MVT::v4i64 || VT == MVT::v8i32))
12445 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12449 // Lower SHL with variable shift amount.
12450 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12451 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12453 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12454 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12455 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12456 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12458 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12459 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12462 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12463 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12465 // Turn 'a' into a mask suitable for VSELECT
12466 SDValue VSelM = DAG.getConstant(0x80, VT);
12467 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12468 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12470 SDValue CM1 = DAG.getConstant(0x0f, VT);
12471 SDValue CM2 = DAG.getConstant(0x3f, VT);
12473 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12474 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12475 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12476 DAG.getConstant(4, MVT::i32), DAG);
12477 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12478 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12481 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12482 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12483 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12485 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12486 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12487 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12488 DAG.getConstant(2, MVT::i32), DAG);
12489 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12490 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12493 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12494 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12495 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12497 // return VSELECT(r, r+r, a);
12498 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12499 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12503 // Decompose 256-bit shifts into smaller 128-bit shifts.
12504 if (VT.is256BitVector()) {
12505 unsigned NumElems = VT.getVectorNumElements();
12506 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12507 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12509 // Extract the two vectors
12510 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12511 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12513 // Recreate the shift amount vectors
12514 SDValue Amt1, Amt2;
12515 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12516 // Constant shift amount
12517 SmallVector<SDValue, 4> Amt1Csts;
12518 SmallVector<SDValue, 4> Amt2Csts;
12519 for (unsigned i = 0; i != NumElems/2; ++i)
12520 Amt1Csts.push_back(Amt->getOperand(i));
12521 for (unsigned i = NumElems/2; i != NumElems; ++i)
12522 Amt2Csts.push_back(Amt->getOperand(i));
12524 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12525 &Amt1Csts[0], NumElems/2);
12526 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12527 &Amt2Csts[0], NumElems/2);
12529 // Variable shift amount
12530 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12531 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12534 // Issue new vector shifts for the smaller types
12535 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12536 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12538 // Concatenate the result back
12539 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12545 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12546 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12547 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12548 // looks for this combo and may remove the "setcc" instruction if the "setcc"
12549 // has only one use.
12550 SDNode *N = Op.getNode();
12551 SDValue LHS = N->getOperand(0);
12552 SDValue RHS = N->getOperand(1);
12553 unsigned BaseOp = 0;
12556 switch (Op.getOpcode()) {
12557 default: llvm_unreachable("Unknown ovf instruction!");
12559 // A subtract of one will be selected as a INC. Note that INC doesn't
12560 // set CF, so we can't do this for UADDO.
12561 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12563 BaseOp = X86ISD::INC;
12564 Cond = X86::COND_O;
12567 BaseOp = X86ISD::ADD;
12568 Cond = X86::COND_O;
12571 BaseOp = X86ISD::ADD;
12572 Cond = X86::COND_B;
12575 // A subtract of one will be selected as a DEC. Note that DEC doesn't
12576 // set CF, so we can't do this for USUBO.
12577 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12579 BaseOp = X86ISD::DEC;
12580 Cond = X86::COND_O;
12583 BaseOp = X86ISD::SUB;
12584 Cond = X86::COND_O;
12587 BaseOp = X86ISD::SUB;
12588 Cond = X86::COND_B;
12591 BaseOp = X86ISD::SMUL;
12592 Cond = X86::COND_O;
12594 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12595 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12597 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12600 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12601 DAG.getConstant(X86::COND_O, MVT::i32),
12602 SDValue(Sum.getNode(), 2));
12604 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12608 // Also sets EFLAGS.
12609 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12610 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12613 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12614 DAG.getConstant(Cond, MVT::i32),
12615 SDValue(Sum.getNode(), 1));
12617 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12620 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12621 SelectionDAG &DAG) const {
12623 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12624 EVT VT = Op.getValueType();
12626 if (!Subtarget->hasSSE2() || !VT.isVector())
12629 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12630 ExtraVT.getScalarType().getSizeInBits();
12631 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12633 switch (VT.getSimpleVT().SimpleTy) {
12634 default: return SDValue();
12637 if (!Subtarget->hasFp256())
12639 if (!Subtarget->hasInt256()) {
12640 // needs to be split
12641 unsigned NumElems = VT.getVectorNumElements();
12643 // Extract the LHS vectors
12644 SDValue LHS = Op.getOperand(0);
12645 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12646 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12648 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12649 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12651 EVT ExtraEltVT = ExtraVT.getVectorElementType();
12652 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12653 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12655 SDValue Extra = DAG.getValueType(ExtraVT);
12657 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12658 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12660 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12665 // (sext (vzext x)) -> (vsext x)
12666 SDValue Op0 = Op.getOperand(0);
12667 SDValue Op00 = Op0.getOperand(0);
12669 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12670 if (Op0.getOpcode() == ISD::BITCAST &&
12671 Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12672 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
12673 if (Tmp1.getNode()) {
12674 SDValue Tmp1Op0 = Tmp1.getOperand(0);
12675 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12676 "This optimization is invalid without a VZEXT.");
12677 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12680 // If the above didn't work, then just use Shift-Left + Shift-Right.
12681 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12682 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12687 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12688 SelectionDAG &DAG) {
12690 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12691 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12692 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12693 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12695 // The only fence that needs an instruction is a sequentially-consistent
12696 // cross-thread fence.
12697 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12698 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12699 // no-sse2). There isn't any reason to disable it if the target processor
12701 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12702 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12704 SDValue Chain = Op.getOperand(0);
12705 SDValue Zero = DAG.getConstant(0, MVT::i32);
12707 DAG.getRegister(X86::ESP, MVT::i32), // Base
12708 DAG.getTargetConstant(1, MVT::i8), // Scale
12709 DAG.getRegister(0, MVT::i32), // Index
12710 DAG.getTargetConstant(0, MVT::i32), // Disp
12711 DAG.getRegister(0, MVT::i32), // Segment.
12715 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12716 return SDValue(Res, 0);
12719 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12720 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12723 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12724 SelectionDAG &DAG) {
12725 EVT T = Op.getValueType();
12729 switch(T.getSimpleVT().SimpleTy) {
12730 default: llvm_unreachable("Invalid value type!");
12731 case MVT::i8: Reg = X86::AL; size = 1; break;
12732 case MVT::i16: Reg = X86::AX; size = 2; break;
12733 case MVT::i32: Reg = X86::EAX; size = 4; break;
12735 assert(Subtarget->is64Bit() && "Node not type legal!");
12736 Reg = X86::RAX; size = 8;
12739 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12740 Op.getOperand(2), SDValue());
12741 SDValue Ops[] = { cpIn.getValue(0),
12744 DAG.getTargetConstant(size, MVT::i8),
12745 cpIn.getValue(1) };
12746 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12747 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12748 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12749 Ops, array_lengthof(Ops), T, MMO);
12751 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12755 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12756 SelectionDAG &DAG) {
12757 assert(Subtarget->is64Bit() && "Result not type legalized?");
12758 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12759 SDValue TheChain = Op.getOperand(0);
12761 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12762 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12763 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12765 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12766 DAG.getConstant(32, MVT::i8));
12768 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12771 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12774 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
12775 SelectionDAG &DAG) {
12776 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
12777 MVT DstVT = Op.getSimpleValueType();
12778 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12779 Subtarget->hasMMX() && "Unexpected custom BITCAST");
12780 assert((DstVT == MVT::i64 ||
12781 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12782 "Unexpected custom BITCAST");
12783 // i64 <=> MMX conversions are Legal.
12784 if (SrcVT==MVT::i64 && DstVT.isVector())
12786 if (DstVT==MVT::i64 && SrcVT.isVector())
12788 // MMX <=> MMX conversions are Legal.
12789 if (SrcVT.isVector() && DstVT.isVector())
12791 // All other conversions need to be expanded.
12795 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12796 SDNode *Node = Op.getNode();
12798 EVT T = Node->getValueType(0);
12799 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12800 DAG.getConstant(0, T), Node->getOperand(2));
12801 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12802 cast<AtomicSDNode>(Node)->getMemoryVT(),
12803 Node->getOperand(0),
12804 Node->getOperand(1), negOp,
12805 cast<AtomicSDNode>(Node)->getSrcValue(),
12806 cast<AtomicSDNode>(Node)->getAlignment(),
12807 cast<AtomicSDNode>(Node)->getOrdering(),
12808 cast<AtomicSDNode>(Node)->getSynchScope());
12811 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12812 SDNode *Node = Op.getNode();
12814 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12816 // Convert seq_cst store -> xchg
12817 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12818 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12819 // (The only way to get a 16-byte store is cmpxchg16b)
12820 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12821 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12822 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12823 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12824 cast<AtomicSDNode>(Node)->getMemoryVT(),
12825 Node->getOperand(0),
12826 Node->getOperand(1), Node->getOperand(2),
12827 cast<AtomicSDNode>(Node)->getMemOperand(),
12828 cast<AtomicSDNode>(Node)->getOrdering(),
12829 cast<AtomicSDNode>(Node)->getSynchScope());
12830 return Swap.getValue(1);
12832 // Other atomic stores have a simple pattern.
12836 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12837 EVT VT = Op.getNode()->getValueType(0);
12839 // Let legalize expand this if it isn't a legal type yet.
12840 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12843 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12846 bool ExtraOp = false;
12847 switch (Op.getOpcode()) {
12848 default: llvm_unreachable("Invalid code");
12849 case ISD::ADDC: Opc = X86ISD::ADD; break;
12850 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12851 case ISD::SUBC: Opc = X86ISD::SUB; break;
12852 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12856 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12858 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12859 Op.getOperand(1), Op.getOperand(2));
12862 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
12863 SelectionDAG &DAG) {
12864 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12866 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12867 // which returns the values as { float, float } (in XMM0) or
12868 // { double, double } (which is returned in XMM0, XMM1).
12870 SDValue Arg = Op.getOperand(0);
12871 EVT ArgVT = Arg.getValueType();
12872 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12874 TargetLowering::ArgListTy Args;
12875 TargetLowering::ArgListEntry Entry;
12879 Entry.isSExt = false;
12880 Entry.isZExt = false;
12881 Args.push_back(Entry);
12883 bool isF64 = ArgVT == MVT::f64;
12884 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12885 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12886 // the results are returned via SRet in memory.
12887 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
12888 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12889 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
12891 Type *RetTy = isF64
12892 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12893 : (Type*)VectorType::get(ArgTy, 4);
12895 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12896 false, false, false, false, 0,
12897 CallingConv::C, /*isTaillCall=*/false,
12898 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12899 Callee, Args, DAG, dl);
12900 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
12903 // Returned in xmm0 and xmm1.
12904 return CallResult.first;
12906 // Returned in bits 0:31 and 32:64 xmm0.
12907 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12908 CallResult.first, DAG.getIntPtrConstant(0));
12909 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12910 CallResult.first, DAG.getIntPtrConstant(1));
12911 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12912 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12915 /// LowerOperation - Provide custom lowering hooks for some operations.
12917 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12918 switch (Op.getOpcode()) {
12919 default: llvm_unreachable("Should not custom lower this!");
12920 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12921 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12922 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12923 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12924 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12925 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12926 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12927 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12928 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12929 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12930 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12931 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12932 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12933 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12934 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12935 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12936 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12937 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12938 case ISD::SHL_PARTS:
12939 case ISD::SRA_PARTS:
12940 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12941 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12942 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12943 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12944 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12945 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12946 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12947 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12948 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12949 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12950 case ISD::FABS: return LowerFABS(Op, DAG);
12951 case ISD::FNEG: return LowerFNEG(Op, DAG);
12952 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12953 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12954 case ISD::SETCC: return LowerSETCC(Op, DAG);
12955 case ISD::SELECT: return LowerSELECT(Op, DAG);
12956 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12957 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12958 case ISD::VASTART: return LowerVASTART(Op, DAG);
12959 case ISD::VAARG: return LowerVAARG(Op, DAG);
12960 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12961 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12962 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12963 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12964 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12965 case ISD::FRAME_TO_ARGS_OFFSET:
12966 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12967 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12968 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12969 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12970 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12971 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12972 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12973 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12974 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12975 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12976 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12977 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12980 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
12986 case ISD::UMULO: return LowerXALUO(Op, DAG);
12987 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12988 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
12992 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12993 case ISD::ADD: return LowerADD(Op, DAG);
12994 case ISD::SUB: return LowerSUB(Op, DAG);
12995 case ISD::SDIV: return LowerSDIV(Op, DAG);
12996 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
13000 static void ReplaceATOMIC_LOAD(SDNode *Node,
13001 SmallVectorImpl<SDValue> &Results,
13002 SelectionDAG &DAG) {
13004 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13006 // Convert wide load -> cmpxchg8b/cmpxchg16b
13007 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13008 // (The only way to get a 16-byte load is cmpxchg16b)
13009 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13010 SDValue Zero = DAG.getConstant(0, VT);
13011 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13012 Node->getOperand(0),
13013 Node->getOperand(1), Zero, Zero,
13014 cast<AtomicSDNode>(Node)->getMemOperand(),
13015 cast<AtomicSDNode>(Node)->getOrdering(),
13016 cast<AtomicSDNode>(Node)->getSynchScope());
13017 Results.push_back(Swap.getValue(0));
13018 Results.push_back(Swap.getValue(1));
13022 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13023 SelectionDAG &DAG, unsigned NewOp) {
13025 assert (Node->getValueType(0) == MVT::i64 &&
13026 "Only know how to expand i64 atomics");
13028 SDValue Chain = Node->getOperand(0);
13029 SDValue In1 = Node->getOperand(1);
13030 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13031 Node->getOperand(2), DAG.getIntPtrConstant(0));
13032 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13033 Node->getOperand(2), DAG.getIntPtrConstant(1));
13034 SDValue Ops[] = { Chain, In1, In2L, In2H };
13035 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13037 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13038 cast<MemSDNode>(Node)->getMemOperand());
13039 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13040 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13041 Results.push_back(Result.getValue(2));
13044 /// ReplaceNodeResults - Replace a node with an illegal result type
13045 /// with a new node built out of custom code.
13046 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13047 SmallVectorImpl<SDValue>&Results,
13048 SelectionDAG &DAG) const {
13050 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13051 switch (N->getOpcode()) {
13053 llvm_unreachable("Do not know how to custom type legalize this operation!");
13054 case ISD::SIGN_EXTEND_INREG:
13059 // We don't want to expand or promote these.
13061 case ISD::FP_TO_SINT:
13062 case ISD::FP_TO_UINT: {
13063 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13065 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13068 std::pair<SDValue,SDValue> Vals =
13069 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13070 SDValue FIST = Vals.first, StackSlot = Vals.second;
13071 if (FIST.getNode() != 0) {
13072 EVT VT = N->getValueType(0);
13073 // Return a load from the stack slot.
13074 if (StackSlot.getNode() != 0)
13075 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13076 MachinePointerInfo(),
13077 false, false, false, 0));
13079 Results.push_back(FIST);
13083 case ISD::UINT_TO_FP: {
13084 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13085 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13086 N->getValueType(0) != MVT::v2f32)
13088 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13090 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13092 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13093 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13094 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13095 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13096 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13097 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13100 case ISD::FP_ROUND: {
13101 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13103 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13104 Results.push_back(V);
13107 case ISD::READCYCLECOUNTER: {
13108 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13109 SDValue TheChain = N->getOperand(0);
13110 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13111 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13113 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13115 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13116 SDValue Ops[] = { eax, edx };
13117 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13118 array_lengthof(Ops)));
13119 Results.push_back(edx.getValue(1));
13122 case ISD::ATOMIC_CMP_SWAP: {
13123 EVT T = N->getValueType(0);
13124 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13125 bool Regs64bit = T == MVT::i128;
13126 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13127 SDValue cpInL, cpInH;
13128 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13129 DAG.getConstant(0, HalfT));
13130 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13131 DAG.getConstant(1, HalfT));
13132 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13133 Regs64bit ? X86::RAX : X86::EAX,
13135 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13136 Regs64bit ? X86::RDX : X86::EDX,
13137 cpInH, cpInL.getValue(1));
13138 SDValue swapInL, swapInH;
13139 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13140 DAG.getConstant(0, HalfT));
13141 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13142 DAG.getConstant(1, HalfT));
13143 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13144 Regs64bit ? X86::RBX : X86::EBX,
13145 swapInL, cpInH.getValue(1));
13146 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13147 Regs64bit ? X86::RCX : X86::ECX,
13148 swapInH, swapInL.getValue(1));
13149 SDValue Ops[] = { swapInH.getValue(0),
13151 swapInH.getValue(1) };
13152 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13153 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13154 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13155 X86ISD::LCMPXCHG8_DAG;
13156 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13157 Ops, array_lengthof(Ops), T, MMO);
13158 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13159 Regs64bit ? X86::RAX : X86::EAX,
13160 HalfT, Result.getValue(1));
13161 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13162 Regs64bit ? X86::RDX : X86::EDX,
13163 HalfT, cpOutL.getValue(2));
13164 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13165 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13166 Results.push_back(cpOutH.getValue(1));
13169 case ISD::ATOMIC_LOAD_ADD:
13170 case ISD::ATOMIC_LOAD_AND:
13171 case ISD::ATOMIC_LOAD_NAND:
13172 case ISD::ATOMIC_LOAD_OR:
13173 case ISD::ATOMIC_LOAD_SUB:
13174 case ISD::ATOMIC_LOAD_XOR:
13175 case ISD::ATOMIC_LOAD_MAX:
13176 case ISD::ATOMIC_LOAD_MIN:
13177 case ISD::ATOMIC_LOAD_UMAX:
13178 case ISD::ATOMIC_LOAD_UMIN:
13179 case ISD::ATOMIC_SWAP: {
13181 switch (N->getOpcode()) {
13182 default: llvm_unreachable("Unexpected opcode");
13183 case ISD::ATOMIC_LOAD_ADD:
13184 Opc = X86ISD::ATOMADD64_DAG;
13186 case ISD::ATOMIC_LOAD_AND:
13187 Opc = X86ISD::ATOMAND64_DAG;
13189 case ISD::ATOMIC_LOAD_NAND:
13190 Opc = X86ISD::ATOMNAND64_DAG;
13192 case ISD::ATOMIC_LOAD_OR:
13193 Opc = X86ISD::ATOMOR64_DAG;
13195 case ISD::ATOMIC_LOAD_SUB:
13196 Opc = X86ISD::ATOMSUB64_DAG;
13198 case ISD::ATOMIC_LOAD_XOR:
13199 Opc = X86ISD::ATOMXOR64_DAG;
13201 case ISD::ATOMIC_LOAD_MAX:
13202 Opc = X86ISD::ATOMMAX64_DAG;
13204 case ISD::ATOMIC_LOAD_MIN:
13205 Opc = X86ISD::ATOMMIN64_DAG;
13207 case ISD::ATOMIC_LOAD_UMAX:
13208 Opc = X86ISD::ATOMUMAX64_DAG;
13210 case ISD::ATOMIC_LOAD_UMIN:
13211 Opc = X86ISD::ATOMUMIN64_DAG;
13213 case ISD::ATOMIC_SWAP:
13214 Opc = X86ISD::ATOMSWAP64_DAG;
13217 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13220 case ISD::ATOMIC_LOAD:
13221 ReplaceATOMIC_LOAD(N, Results, DAG);
13225 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13227 default: return NULL;
13228 case X86ISD::BSF: return "X86ISD::BSF";
13229 case X86ISD::BSR: return "X86ISD::BSR";
13230 case X86ISD::SHLD: return "X86ISD::SHLD";
13231 case X86ISD::SHRD: return "X86ISD::SHRD";
13232 case X86ISD::FAND: return "X86ISD::FAND";
13233 case X86ISD::FANDN: return "X86ISD::FANDN";
13234 case X86ISD::FOR: return "X86ISD::FOR";
13235 case X86ISD::FXOR: return "X86ISD::FXOR";
13236 case X86ISD::FSRL: return "X86ISD::FSRL";
13237 case X86ISD::FILD: return "X86ISD::FILD";
13238 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
13239 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13240 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13241 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13242 case X86ISD::FLD: return "X86ISD::FLD";
13243 case X86ISD::FST: return "X86ISD::FST";
13244 case X86ISD::CALL: return "X86ISD::CALL";
13245 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
13246 case X86ISD::BT: return "X86ISD::BT";
13247 case X86ISD::CMP: return "X86ISD::CMP";
13248 case X86ISD::COMI: return "X86ISD::COMI";
13249 case X86ISD::UCOMI: return "X86ISD::UCOMI";
13250 case X86ISD::CMPM: return "X86ISD::CMPM";
13251 case X86ISD::CMPMU: return "X86ISD::CMPMU";
13252 case X86ISD::SETCC: return "X86ISD::SETCC";
13253 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
13254 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
13255 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
13256 case X86ISD::CMOV: return "X86ISD::CMOV";
13257 case X86ISD::BRCOND: return "X86ISD::BRCOND";
13258 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
13259 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
13260 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
13261 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
13262 case X86ISD::Wrapper: return "X86ISD::Wrapper";
13263 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
13264 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
13265 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
13266 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
13267 case X86ISD::PINSRB: return "X86ISD::PINSRB";
13268 case X86ISD::PINSRW: return "X86ISD::PINSRW";
13269 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
13270 case X86ISD::ANDNP: return "X86ISD::ANDNP";
13271 case X86ISD::PSIGN: return "X86ISD::PSIGN";
13272 case X86ISD::BLENDV: return "X86ISD::BLENDV";
13273 case X86ISD::BLENDI: return "X86ISD::BLENDI";
13274 case X86ISD::SUBUS: return "X86ISD::SUBUS";
13275 case X86ISD::HADD: return "X86ISD::HADD";
13276 case X86ISD::HSUB: return "X86ISD::HSUB";
13277 case X86ISD::FHADD: return "X86ISD::FHADD";
13278 case X86ISD::FHSUB: return "X86ISD::FHSUB";
13279 case X86ISD::UMAX: return "X86ISD::UMAX";
13280 case X86ISD::UMIN: return "X86ISD::UMIN";
13281 case X86ISD::SMAX: return "X86ISD::SMAX";
13282 case X86ISD::SMIN: return "X86ISD::SMIN";
13283 case X86ISD::FMAX: return "X86ISD::FMAX";
13284 case X86ISD::FMIN: return "X86ISD::FMIN";
13285 case X86ISD::FMAXC: return "X86ISD::FMAXC";
13286 case X86ISD::FMINC: return "X86ISD::FMINC";
13287 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
13288 case X86ISD::FRCP: return "X86ISD::FRCP";
13289 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
13290 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
13291 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
13292 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
13293 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
13294 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
13295 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
13296 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
13297 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
13298 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
13299 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
13300 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
13301 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
13302 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
13303 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
13304 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
13305 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
13306 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
13307 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
13308 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
13309 case X86ISD::VZEXT: return "X86ISD::VZEXT";
13310 case X86ISD::VSEXT: return "X86ISD::VSEXT";
13311 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
13312 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
13313 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
13314 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
13315 case X86ISD::VSHL: return "X86ISD::VSHL";
13316 case X86ISD::VSRL: return "X86ISD::VSRL";
13317 case X86ISD::VSRA: return "X86ISD::VSRA";
13318 case X86ISD::VSHLI: return "X86ISD::VSHLI";
13319 case X86ISD::VSRLI: return "X86ISD::VSRLI";
13320 case X86ISD::VSRAI: return "X86ISD::VSRAI";
13321 case X86ISD::CMPP: return "X86ISD::CMPP";
13322 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
13323 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
13324 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
13325 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
13326 case X86ISD::ADD: return "X86ISD::ADD";
13327 case X86ISD::SUB: return "X86ISD::SUB";
13328 case X86ISD::ADC: return "X86ISD::ADC";
13329 case X86ISD::SBB: return "X86ISD::SBB";
13330 case X86ISD::SMUL: return "X86ISD::SMUL";
13331 case X86ISD::UMUL: return "X86ISD::UMUL";
13332 case X86ISD::INC: return "X86ISD::INC";
13333 case X86ISD::DEC: return "X86ISD::DEC";
13334 case X86ISD::OR: return "X86ISD::OR";
13335 case X86ISD::XOR: return "X86ISD::XOR";
13336 case X86ISD::AND: return "X86ISD::AND";
13337 case X86ISD::BLSI: return "X86ISD::BLSI";
13338 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
13339 case X86ISD::BLSR: return "X86ISD::BLSR";
13340 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
13341 case X86ISD::PTEST: return "X86ISD::PTEST";
13342 case X86ISD::TESTP: return "X86ISD::TESTP";
13343 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
13344 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
13345 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
13346 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
13347 case X86ISD::SHUFP: return "X86ISD::SHUFP";
13348 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
13349 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
13350 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
13351 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
13352 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
13353 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
13354 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
13355 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
13356 case X86ISD::MOVSD: return "X86ISD::MOVSD";
13357 case X86ISD::MOVSS: return "X86ISD::MOVSS";
13358 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
13359 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
13360 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
13361 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
13362 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
13363 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
13364 case X86ISD::VPERMV: return "X86ISD::VPERMV";
13365 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
13366 case X86ISD::VPERMI: return "X86ISD::VPERMI";
13367 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
13368 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13369 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
13370 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
13371 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
13372 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
13373 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
13374 case X86ISD::SAHF: return "X86ISD::SAHF";
13375 case X86ISD::RDRAND: return "X86ISD::RDRAND";
13376 case X86ISD::RDSEED: return "X86ISD::RDSEED";
13377 case X86ISD::FMADD: return "X86ISD::FMADD";
13378 case X86ISD::FMSUB: return "X86ISD::FMSUB";
13379 case X86ISD::FNMADD: return "X86ISD::FNMADD";
13380 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
13381 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
13382 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
13383 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
13384 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
13385 case X86ISD::XTEST: return "X86ISD::XTEST";
13389 // isLegalAddressingMode - Return true if the addressing mode represented
13390 // by AM is legal for this target, for a load/store of the specified type.
13391 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13393 // X86 supports extremely general addressing modes.
13394 CodeModel::Model M = getTargetMachine().getCodeModel();
13395 Reloc::Model R = getTargetMachine().getRelocationModel();
13397 // X86 allows a sign-extended 32-bit immediate field as a displacement.
13398 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13403 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13405 // If a reference to this global requires an extra load, we can't fold it.
13406 if (isGlobalStubReference(GVFlags))
13409 // If BaseGV requires a register for the PIC base, we cannot also have a
13410 // BaseReg specified.
13411 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13414 // If lower 4G is not available, then we must use rip-relative addressing.
13415 if ((M != CodeModel::Small || R != Reloc::Static) &&
13416 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13420 switch (AM.Scale) {
13426 // These scales always work.
13431 // These scales are formed with basereg+scalereg. Only accept if there is
13436 default: // Other stuff never works.
13443 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13444 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13446 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13447 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13448 return NumBits1 > NumBits2;
13451 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13452 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13455 if (!isTypeLegal(EVT::getEVT(Ty1)))
13458 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13460 // Assuming the caller doesn't have a zeroext or signext return parameter,
13461 // truncation all the way down to i1 is valid.
13465 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13466 return isInt<32>(Imm);
13469 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13470 // Can also use sub to handle negated immediates.
13471 return isInt<32>(Imm);
13474 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13475 if (!VT1.isInteger() || !VT2.isInteger())
13477 unsigned NumBits1 = VT1.getSizeInBits();
13478 unsigned NumBits2 = VT2.getSizeInBits();
13479 return NumBits1 > NumBits2;
13482 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13483 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13484 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13487 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13488 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13489 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13492 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13493 EVT VT1 = Val.getValueType();
13494 if (isZExtFree(VT1, VT2))
13497 if (Val.getOpcode() != ISD::LOAD)
13500 if (!VT1.isSimple() || !VT1.isInteger() ||
13501 !VT2.isSimple() || !VT2.isInteger())
13504 switch (VT1.getSimpleVT().SimpleTy) {
13509 // X86 has 8, 16, and 32-bit zero-extending loads.
13517 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13518 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13521 VT = VT.getScalarType();
13523 if (!VT.isSimple())
13526 switch (VT.getSimpleVT().SimpleTy) {
13537 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13538 // i16 instructions are longer (0x66 prefix) and potentially slower.
13539 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13542 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13543 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13544 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13545 /// are assumed to be legal.
13547 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13549 if (!VT.isSimple())
13552 MVT SVT = VT.getSimpleVT();
13554 // Very little shuffling can be done for 64-bit vectors right now.
13555 if (VT.getSizeInBits() == 64)
13558 // FIXME: pshufb, blends, shifts.
13559 return (SVT.getVectorNumElements() == 2 ||
13560 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13561 isMOVLMask(M, SVT) ||
13562 isSHUFPMask(M, SVT, Subtarget->hasFp256()) ||
13563 isPSHUFDMask(M, SVT) ||
13564 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
13565 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
13566 isPALIGNRMask(M, SVT, Subtarget) ||
13567 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
13568 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
13569 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
13570 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
13574 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13576 if (!VT.isSimple())
13579 MVT SVT = VT.getSimpleVT();
13580 unsigned NumElts = SVT.getVectorNumElements();
13581 // FIXME: This collection of masks seems suspect.
13584 if (NumElts == 4 && SVT.is128BitVector()) {
13585 return (isMOVLMask(Mask, SVT) ||
13586 isCommutedMOVLMask(Mask, SVT, true) ||
13587 isSHUFPMask(Mask, SVT, Subtarget->hasFp256()) ||
13588 isSHUFPMask(Mask, SVT, Subtarget->hasFp256(), /* Commuted */ true));
13593 //===----------------------------------------------------------------------===//
13594 // X86 Scheduler Hooks
13595 //===----------------------------------------------------------------------===//
13597 /// Utility function to emit xbegin specifying the start of an RTM region.
13598 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13599 const TargetInstrInfo *TII) {
13600 DebugLoc DL = MI->getDebugLoc();
13602 const BasicBlock *BB = MBB->getBasicBlock();
13603 MachineFunction::iterator I = MBB;
13606 // For the v = xbegin(), we generate
13617 MachineBasicBlock *thisMBB = MBB;
13618 MachineFunction *MF = MBB->getParent();
13619 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13620 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13621 MF->insert(I, mainMBB);
13622 MF->insert(I, sinkMBB);
13624 // Transfer the remainder of BB and its successor edges to sinkMBB.
13625 sinkMBB->splice(sinkMBB->begin(), MBB,
13626 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13627 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13631 // # fallthrough to mainMBB
13632 // # abortion to sinkMBB
13633 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13634 thisMBB->addSuccessor(mainMBB);
13635 thisMBB->addSuccessor(sinkMBB);
13639 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13640 mainMBB->addSuccessor(sinkMBB);
13643 // EAX is live into the sinkMBB
13644 sinkMBB->addLiveIn(X86::EAX);
13645 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13646 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13649 MI->eraseFromParent();
13653 // Get CMPXCHG opcode for the specified data type.
13654 static unsigned getCmpXChgOpcode(EVT VT) {
13655 switch (VT.getSimpleVT().SimpleTy) {
13656 case MVT::i8: return X86::LCMPXCHG8;
13657 case MVT::i16: return X86::LCMPXCHG16;
13658 case MVT::i32: return X86::LCMPXCHG32;
13659 case MVT::i64: return X86::LCMPXCHG64;
13663 llvm_unreachable("Invalid operand size!");
13666 // Get LOAD opcode for the specified data type.
13667 static unsigned getLoadOpcode(EVT VT) {
13668 switch (VT.getSimpleVT().SimpleTy) {
13669 case MVT::i8: return X86::MOV8rm;
13670 case MVT::i16: return X86::MOV16rm;
13671 case MVT::i32: return X86::MOV32rm;
13672 case MVT::i64: return X86::MOV64rm;
13676 llvm_unreachable("Invalid operand size!");
13679 // Get opcode of the non-atomic one from the specified atomic instruction.
13680 static unsigned getNonAtomicOpcode(unsigned Opc) {
13682 case X86::ATOMAND8: return X86::AND8rr;
13683 case X86::ATOMAND16: return X86::AND16rr;
13684 case X86::ATOMAND32: return X86::AND32rr;
13685 case X86::ATOMAND64: return X86::AND64rr;
13686 case X86::ATOMOR8: return X86::OR8rr;
13687 case X86::ATOMOR16: return X86::OR16rr;
13688 case X86::ATOMOR32: return X86::OR32rr;
13689 case X86::ATOMOR64: return X86::OR64rr;
13690 case X86::ATOMXOR8: return X86::XOR8rr;
13691 case X86::ATOMXOR16: return X86::XOR16rr;
13692 case X86::ATOMXOR32: return X86::XOR32rr;
13693 case X86::ATOMXOR64: return X86::XOR64rr;
13695 llvm_unreachable("Unhandled atomic-load-op opcode!");
13698 // Get opcode of the non-atomic one from the specified atomic instruction with
13700 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13701 unsigned &ExtraOpc) {
13703 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
13704 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
13705 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
13706 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
13707 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
13708 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13709 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13710 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13711 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
13712 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13713 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13714 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13715 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
13716 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13717 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13718 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13719 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
13720 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13721 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13722 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13724 llvm_unreachable("Unhandled atomic-load-op opcode!");
13727 // Get opcode of the non-atomic one from the specified atomic instruction for
13728 // 64-bit data type on 32-bit target.
13729 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13731 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
13732 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
13733 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
13734 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
13735 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
13736 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13737 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
13738 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
13739 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
13740 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
13742 llvm_unreachable("Unhandled atomic-load-op opcode!");
13745 // Get opcode of the non-atomic one from the specified atomic instruction for
13746 // 64-bit data type on 32-bit target with extra opcode.
13747 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13749 unsigned &ExtraOpc) {
13751 case X86::ATOMNAND6432:
13752 ExtraOpc = X86::NOT32r;
13753 HiOpc = X86::AND32rr;
13754 return X86::AND32rr;
13756 llvm_unreachable("Unhandled atomic-load-op opcode!");
13759 // Get pseudo CMOV opcode from the specified data type.
13760 static unsigned getPseudoCMOVOpc(EVT VT) {
13761 switch (VT.getSimpleVT().SimpleTy) {
13762 case MVT::i8: return X86::CMOV_GR8;
13763 case MVT::i16: return X86::CMOV_GR16;
13764 case MVT::i32: return X86::CMOV_GR32;
13768 llvm_unreachable("Unknown CMOV opcode!");
13771 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13772 // They will be translated into a spin-loop or compare-exchange loop from
13775 // dst = atomic-fetch-op MI.addr, MI.val
13781 // t1 = LOAD MI.addr
13783 // t4 = phi(t1, t3 / loop)
13784 // t2 = OP MI.val, t4
13786 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13792 MachineBasicBlock *
13793 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13794 MachineBasicBlock *MBB) const {
13795 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13796 DebugLoc DL = MI->getDebugLoc();
13798 MachineFunction *MF = MBB->getParent();
13799 MachineRegisterInfo &MRI = MF->getRegInfo();
13801 const BasicBlock *BB = MBB->getBasicBlock();
13802 MachineFunction::iterator I = MBB;
13805 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13806 "Unexpected number of operands");
13808 assert(MI->hasOneMemOperand() &&
13809 "Expected atomic-load-op to have one memoperand");
13811 // Memory Reference
13812 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13813 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13815 unsigned DstReg, SrcReg;
13816 unsigned MemOpndSlot;
13818 unsigned CurOp = 0;
13820 DstReg = MI->getOperand(CurOp++).getReg();
13821 MemOpndSlot = CurOp;
13822 CurOp += X86::AddrNumOperands;
13823 SrcReg = MI->getOperand(CurOp++).getReg();
13825 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13826 MVT::SimpleValueType VT = *RC->vt_begin();
13827 unsigned t1 = MRI.createVirtualRegister(RC);
13828 unsigned t2 = MRI.createVirtualRegister(RC);
13829 unsigned t3 = MRI.createVirtualRegister(RC);
13830 unsigned t4 = MRI.createVirtualRegister(RC);
13831 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13833 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13834 unsigned LOADOpc = getLoadOpcode(VT);
13836 // For the atomic load-arith operator, we generate
13839 // t1 = LOAD [MI.addr]
13841 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
13842 // t1 = OP MI.val, EAX
13844 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13850 MachineBasicBlock *thisMBB = MBB;
13851 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13852 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13853 MF->insert(I, mainMBB);
13854 MF->insert(I, sinkMBB);
13856 MachineInstrBuilder MIB;
13858 // Transfer the remainder of BB and its successor edges to sinkMBB.
13859 sinkMBB->splice(sinkMBB->begin(), MBB,
13860 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13861 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13864 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13865 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13866 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13868 NewMO.setIsKill(false);
13869 MIB.addOperand(NewMO);
13871 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13872 unsigned flags = (*MMOI)->getFlags();
13873 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13874 MachineMemOperand *MMO =
13875 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13876 (*MMOI)->getSize(),
13877 (*MMOI)->getBaseAlignment(),
13878 (*MMOI)->getTBAAInfo(),
13879 (*MMOI)->getRanges());
13880 MIB.addMemOperand(MMO);
13883 thisMBB->addSuccessor(mainMBB);
13886 MachineBasicBlock *origMainMBB = mainMBB;
13889 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13890 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13892 unsigned Opc = MI->getOpcode();
13895 llvm_unreachable("Unhandled atomic-load-op opcode!");
13896 case X86::ATOMAND8:
13897 case X86::ATOMAND16:
13898 case X86::ATOMAND32:
13899 case X86::ATOMAND64:
13901 case X86::ATOMOR16:
13902 case X86::ATOMOR32:
13903 case X86::ATOMOR64:
13904 case X86::ATOMXOR8:
13905 case X86::ATOMXOR16:
13906 case X86::ATOMXOR32:
13907 case X86::ATOMXOR64: {
13908 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13909 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13913 case X86::ATOMNAND8:
13914 case X86::ATOMNAND16:
13915 case X86::ATOMNAND32:
13916 case X86::ATOMNAND64: {
13917 unsigned Tmp = MRI.createVirtualRegister(RC);
13919 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13920 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13922 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13925 case X86::ATOMMAX8:
13926 case X86::ATOMMAX16:
13927 case X86::ATOMMAX32:
13928 case X86::ATOMMAX64:
13929 case X86::ATOMMIN8:
13930 case X86::ATOMMIN16:
13931 case X86::ATOMMIN32:
13932 case X86::ATOMMIN64:
13933 case X86::ATOMUMAX8:
13934 case X86::ATOMUMAX16:
13935 case X86::ATOMUMAX32:
13936 case X86::ATOMUMAX64:
13937 case X86::ATOMUMIN8:
13938 case X86::ATOMUMIN16:
13939 case X86::ATOMUMIN32:
13940 case X86::ATOMUMIN64: {
13942 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13944 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13948 if (Subtarget->hasCMov()) {
13949 if (VT != MVT::i8) {
13951 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13955 // Promote i8 to i32 to use CMOV32
13956 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13957 const TargetRegisterClass *RC32 =
13958 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13959 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13960 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13961 unsigned Tmp = MRI.createVirtualRegister(RC32);
13963 unsigned Undef = MRI.createVirtualRegister(RC32);
13964 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13966 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13969 .addImm(X86::sub_8bit);
13970 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13973 .addImm(X86::sub_8bit);
13975 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13979 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13980 .addReg(Tmp, 0, X86::sub_8bit);
13983 // Use pseudo select and lower them.
13984 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13985 "Invalid atomic-load-op transformation!");
13986 unsigned SelOpc = getPseudoCMOVOpc(VT);
13987 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13988 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13989 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13990 .addReg(SrcReg).addReg(t4)
13992 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13993 // Replace the original PHI node as mainMBB is changed after CMOV
13995 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13996 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13997 Phi->eraseFromParent();
14003 // Copy PhyReg back from virtual register.
14004 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14007 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14008 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14009 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14011 NewMO.setIsKill(false);
14012 MIB.addOperand(NewMO);
14015 MIB.setMemRefs(MMOBegin, MMOEnd);
14017 // Copy PhyReg back to virtual register.
14018 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14021 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14023 mainMBB->addSuccessor(origMainMBB);
14024 mainMBB->addSuccessor(sinkMBB);
14027 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14028 TII->get(TargetOpcode::COPY), DstReg)
14031 MI->eraseFromParent();
14035 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14036 // instructions. They will be translated into a spin-loop or compare-exchange
14040 // dst = atomic-fetch-op MI.addr, MI.val
14046 // t1L = LOAD [MI.addr + 0]
14047 // t1H = LOAD [MI.addr + 4]
14049 // t4L = phi(t1L, t3L / loop)
14050 // t4H = phi(t1H, t3H / loop)
14051 // t2L = OP MI.val.lo, t4L
14052 // t2H = OP MI.val.hi, t4H
14057 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14065 MachineBasicBlock *
14066 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14067 MachineBasicBlock *MBB) const {
14068 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14069 DebugLoc DL = MI->getDebugLoc();
14071 MachineFunction *MF = MBB->getParent();
14072 MachineRegisterInfo &MRI = MF->getRegInfo();
14074 const BasicBlock *BB = MBB->getBasicBlock();
14075 MachineFunction::iterator I = MBB;
14078 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14079 "Unexpected number of operands");
14081 assert(MI->hasOneMemOperand() &&
14082 "Expected atomic-load-op32 to have one memoperand");
14084 // Memory Reference
14085 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14086 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14088 unsigned DstLoReg, DstHiReg;
14089 unsigned SrcLoReg, SrcHiReg;
14090 unsigned MemOpndSlot;
14092 unsigned CurOp = 0;
14094 DstLoReg = MI->getOperand(CurOp++).getReg();
14095 DstHiReg = MI->getOperand(CurOp++).getReg();
14096 MemOpndSlot = CurOp;
14097 CurOp += X86::AddrNumOperands;
14098 SrcLoReg = MI->getOperand(CurOp++).getReg();
14099 SrcHiReg = MI->getOperand(CurOp++).getReg();
14101 const TargetRegisterClass *RC = &X86::GR32RegClass;
14102 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14104 unsigned t1L = MRI.createVirtualRegister(RC);
14105 unsigned t1H = MRI.createVirtualRegister(RC);
14106 unsigned t2L = MRI.createVirtualRegister(RC);
14107 unsigned t2H = MRI.createVirtualRegister(RC);
14108 unsigned t3L = MRI.createVirtualRegister(RC);
14109 unsigned t3H = MRI.createVirtualRegister(RC);
14110 unsigned t4L = MRI.createVirtualRegister(RC);
14111 unsigned t4H = MRI.createVirtualRegister(RC);
14113 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14114 unsigned LOADOpc = X86::MOV32rm;
14116 // For the atomic load-arith operator, we generate
14119 // t1L = LOAD [MI.addr + 0]
14120 // t1H = LOAD [MI.addr + 4]
14122 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14123 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14124 // t2L = OP MI.val.lo, t4L
14125 // t2H = OP MI.val.hi, t4H
14128 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14136 MachineBasicBlock *thisMBB = MBB;
14137 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14138 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14139 MF->insert(I, mainMBB);
14140 MF->insert(I, sinkMBB);
14142 MachineInstrBuilder MIB;
14144 // Transfer the remainder of BB and its successor edges to sinkMBB.
14145 sinkMBB->splice(sinkMBB->begin(), MBB,
14146 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14147 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14151 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14152 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14153 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14155 NewMO.setIsKill(false);
14156 MIB.addOperand(NewMO);
14158 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14159 unsigned flags = (*MMOI)->getFlags();
14160 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14161 MachineMemOperand *MMO =
14162 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14163 (*MMOI)->getSize(),
14164 (*MMOI)->getBaseAlignment(),
14165 (*MMOI)->getTBAAInfo(),
14166 (*MMOI)->getRanges());
14167 MIB.addMemOperand(MMO);
14169 MachineInstr *LowMI = MIB;
14172 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14173 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14174 if (i == X86::AddrDisp) {
14175 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14177 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14179 NewMO.setIsKill(false);
14180 MIB.addOperand(NewMO);
14183 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14185 thisMBB->addSuccessor(mainMBB);
14188 MachineBasicBlock *origMainMBB = mainMBB;
14191 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14192 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14193 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14194 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14196 unsigned Opc = MI->getOpcode();
14199 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14200 case X86::ATOMAND6432:
14201 case X86::ATOMOR6432:
14202 case X86::ATOMXOR6432:
14203 case X86::ATOMADD6432:
14204 case X86::ATOMSUB6432: {
14206 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14207 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14209 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14213 case X86::ATOMNAND6432: {
14214 unsigned HiOpc, NOTOpc;
14215 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14216 unsigned TmpL = MRI.createVirtualRegister(RC);
14217 unsigned TmpH = MRI.createVirtualRegister(RC);
14218 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14220 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14222 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14223 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14226 case X86::ATOMMAX6432:
14227 case X86::ATOMMIN6432:
14228 case X86::ATOMUMAX6432:
14229 case X86::ATOMUMIN6432: {
14231 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14232 unsigned cL = MRI.createVirtualRegister(RC8);
14233 unsigned cH = MRI.createVirtualRegister(RC8);
14234 unsigned cL32 = MRI.createVirtualRegister(RC);
14235 unsigned cH32 = MRI.createVirtualRegister(RC);
14236 unsigned cc = MRI.createVirtualRegister(RC);
14237 // cl := cmp src_lo, lo
14238 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14239 .addReg(SrcLoReg).addReg(t4L);
14240 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14241 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14242 // ch := cmp src_hi, hi
14243 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14244 .addReg(SrcHiReg).addReg(t4H);
14245 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14246 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14247 // cc := if (src_hi == hi) ? cl : ch;
14248 if (Subtarget->hasCMov()) {
14249 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14250 .addReg(cH32).addReg(cL32);
14252 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14253 .addReg(cH32).addReg(cL32)
14254 .addImm(X86::COND_E);
14255 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14257 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14258 if (Subtarget->hasCMov()) {
14259 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14260 .addReg(SrcLoReg).addReg(t4L);
14261 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14262 .addReg(SrcHiReg).addReg(t4H);
14264 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14265 .addReg(SrcLoReg).addReg(t4L)
14266 .addImm(X86::COND_NE);
14267 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14268 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14269 // 2nd CMOV lowering.
14270 mainMBB->addLiveIn(X86::EFLAGS);
14271 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14272 .addReg(SrcHiReg).addReg(t4H)
14273 .addImm(X86::COND_NE);
14274 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14275 // Replace the original PHI node as mainMBB is changed after CMOV
14277 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14278 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14279 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14280 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14281 PhiL->eraseFromParent();
14282 PhiH->eraseFromParent();
14286 case X86::ATOMSWAP6432: {
14288 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14289 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14290 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14295 // Copy EDX:EAX back from HiReg:LoReg
14296 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14297 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14298 // Copy ECX:EBX from t1H:t1L
14299 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14300 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14302 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14303 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14304 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14306 NewMO.setIsKill(false);
14307 MIB.addOperand(NewMO);
14309 MIB.setMemRefs(MMOBegin, MMOEnd);
14311 // Copy EDX:EAX back to t3H:t3L
14312 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14313 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14315 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14317 mainMBB->addSuccessor(origMainMBB);
14318 mainMBB->addSuccessor(sinkMBB);
14321 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14322 TII->get(TargetOpcode::COPY), DstLoReg)
14324 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14325 TII->get(TargetOpcode::COPY), DstHiReg)
14328 MI->eraseFromParent();
14332 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14333 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14334 // in the .td file.
14335 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14336 const TargetInstrInfo *TII) {
14338 switch (MI->getOpcode()) {
14339 default: llvm_unreachable("illegal opcode!");
14340 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
14341 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14342 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
14343 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14344 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
14345 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14346 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
14347 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14350 DebugLoc dl = MI->getDebugLoc();
14351 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14353 unsigned NumArgs = MI->getNumOperands();
14354 for (unsigned i = 1; i < NumArgs; ++i) {
14355 MachineOperand &Op = MI->getOperand(i);
14356 if (!(Op.isReg() && Op.isImplicit()))
14357 MIB.addOperand(Op);
14359 if (MI->hasOneMemOperand())
14360 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14362 BuildMI(*BB, MI, dl,
14363 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14364 .addReg(X86::XMM0);
14366 MI->eraseFromParent();
14370 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14371 // defs in an instruction pattern
14372 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14373 const TargetInstrInfo *TII) {
14375 switch (MI->getOpcode()) {
14376 default: llvm_unreachable("illegal opcode!");
14377 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
14378 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14379 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
14380 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14381 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
14382 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14383 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
14384 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14387 DebugLoc dl = MI->getDebugLoc();
14388 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14390 unsigned NumArgs = MI->getNumOperands(); // remove the results
14391 for (unsigned i = 1; i < NumArgs; ++i) {
14392 MachineOperand &Op = MI->getOperand(i);
14393 if (!(Op.isReg() && Op.isImplicit()))
14394 MIB.addOperand(Op);
14396 if (MI->hasOneMemOperand())
14397 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14399 BuildMI(*BB, MI, dl,
14400 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14403 MI->eraseFromParent();
14407 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14408 const TargetInstrInfo *TII,
14409 const X86Subtarget* Subtarget) {
14410 DebugLoc dl = MI->getDebugLoc();
14412 // Address into RAX/EAX, other two args into ECX, EDX.
14413 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14414 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14415 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14416 for (int i = 0; i < X86::AddrNumOperands; ++i)
14417 MIB.addOperand(MI->getOperand(i));
14419 unsigned ValOps = X86::AddrNumOperands;
14420 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14421 .addReg(MI->getOperand(ValOps).getReg());
14422 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14423 .addReg(MI->getOperand(ValOps+1).getReg());
14425 // The instruction doesn't actually take any operands though.
14426 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14428 MI->eraseFromParent(); // The pseudo is gone now.
14432 MachineBasicBlock *
14433 X86TargetLowering::EmitVAARG64WithCustomInserter(
14435 MachineBasicBlock *MBB) const {
14436 // Emit va_arg instruction on X86-64.
14438 // Operands to this pseudo-instruction:
14439 // 0 ) Output : destination address (reg)
14440 // 1-5) Input : va_list address (addr, i64mem)
14441 // 6 ) ArgSize : Size (in bytes) of vararg type
14442 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14443 // 8 ) Align : Alignment of type
14444 // 9 ) EFLAGS (implicit-def)
14446 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14447 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14449 unsigned DestReg = MI->getOperand(0).getReg();
14450 MachineOperand &Base = MI->getOperand(1);
14451 MachineOperand &Scale = MI->getOperand(2);
14452 MachineOperand &Index = MI->getOperand(3);
14453 MachineOperand &Disp = MI->getOperand(4);
14454 MachineOperand &Segment = MI->getOperand(5);
14455 unsigned ArgSize = MI->getOperand(6).getImm();
14456 unsigned ArgMode = MI->getOperand(7).getImm();
14457 unsigned Align = MI->getOperand(8).getImm();
14459 // Memory Reference
14460 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14461 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14462 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14464 // Machine Information
14465 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14466 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14467 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14468 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14469 DebugLoc DL = MI->getDebugLoc();
14471 // struct va_list {
14474 // i64 overflow_area (address)
14475 // i64 reg_save_area (address)
14477 // sizeof(va_list) = 24
14478 // alignment(va_list) = 8
14480 unsigned TotalNumIntRegs = 6;
14481 unsigned TotalNumXMMRegs = 8;
14482 bool UseGPOffset = (ArgMode == 1);
14483 bool UseFPOffset = (ArgMode == 2);
14484 unsigned MaxOffset = TotalNumIntRegs * 8 +
14485 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14487 /* Align ArgSize to a multiple of 8 */
14488 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14489 bool NeedsAlign = (Align > 8);
14491 MachineBasicBlock *thisMBB = MBB;
14492 MachineBasicBlock *overflowMBB;
14493 MachineBasicBlock *offsetMBB;
14494 MachineBasicBlock *endMBB;
14496 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
14497 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
14498 unsigned OffsetReg = 0;
14500 if (!UseGPOffset && !UseFPOffset) {
14501 // If we only pull from the overflow region, we don't create a branch.
14502 // We don't need to alter control flow.
14503 OffsetDestReg = 0; // unused
14504 OverflowDestReg = DestReg;
14507 overflowMBB = thisMBB;
14510 // First emit code to check if gp_offset (or fp_offset) is below the bound.
14511 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14512 // If not, pull from overflow_area. (branch to overflowMBB)
14517 // offsetMBB overflowMBB
14522 // Registers for the PHI in endMBB
14523 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14524 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14526 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14527 MachineFunction *MF = MBB->getParent();
14528 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14529 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14530 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14532 MachineFunction::iterator MBBIter = MBB;
14535 // Insert the new basic blocks
14536 MF->insert(MBBIter, offsetMBB);
14537 MF->insert(MBBIter, overflowMBB);
14538 MF->insert(MBBIter, endMBB);
14540 // Transfer the remainder of MBB and its successor edges to endMBB.
14541 endMBB->splice(endMBB->begin(), thisMBB,
14542 llvm::next(MachineBasicBlock::iterator(MI)),
14544 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14546 // Make offsetMBB and overflowMBB successors of thisMBB
14547 thisMBB->addSuccessor(offsetMBB);
14548 thisMBB->addSuccessor(overflowMBB);
14550 // endMBB is a successor of both offsetMBB and overflowMBB
14551 offsetMBB->addSuccessor(endMBB);
14552 overflowMBB->addSuccessor(endMBB);
14554 // Load the offset value into a register
14555 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14556 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14560 .addDisp(Disp, UseFPOffset ? 4 : 0)
14561 .addOperand(Segment)
14562 .setMemRefs(MMOBegin, MMOEnd);
14564 // Check if there is enough room left to pull this argument.
14565 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14567 .addImm(MaxOffset + 8 - ArgSizeA8);
14569 // Branch to "overflowMBB" if offset >= max
14570 // Fall through to "offsetMBB" otherwise
14571 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14572 .addMBB(overflowMBB);
14575 // In offsetMBB, emit code to use the reg_save_area.
14577 assert(OffsetReg != 0);
14579 // Read the reg_save_area address.
14580 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14581 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14586 .addOperand(Segment)
14587 .setMemRefs(MMOBegin, MMOEnd);
14589 // Zero-extend the offset
14590 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14591 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14594 .addImm(X86::sub_32bit);
14596 // Add the offset to the reg_save_area to get the final address.
14597 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14598 .addReg(OffsetReg64)
14599 .addReg(RegSaveReg);
14601 // Compute the offset for the next argument
14602 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14603 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14605 .addImm(UseFPOffset ? 16 : 8);
14607 // Store it back into the va_list.
14608 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14612 .addDisp(Disp, UseFPOffset ? 4 : 0)
14613 .addOperand(Segment)
14614 .addReg(NextOffsetReg)
14615 .setMemRefs(MMOBegin, MMOEnd);
14618 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14623 // Emit code to use overflow area
14626 // Load the overflow_area address into a register.
14627 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14628 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14633 .addOperand(Segment)
14634 .setMemRefs(MMOBegin, MMOEnd);
14636 // If we need to align it, do so. Otherwise, just copy the address
14637 // to OverflowDestReg.
14639 // Align the overflow address
14640 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14641 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14643 // aligned_addr = (addr + (align-1)) & ~(align-1)
14644 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14645 .addReg(OverflowAddrReg)
14648 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14650 .addImm(~(uint64_t)(Align-1));
14652 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14653 .addReg(OverflowAddrReg);
14656 // Compute the next overflow address after this argument.
14657 // (the overflow address should be kept 8-byte aligned)
14658 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14659 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14660 .addReg(OverflowDestReg)
14661 .addImm(ArgSizeA8);
14663 // Store the new overflow address.
14664 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14669 .addOperand(Segment)
14670 .addReg(NextAddrReg)
14671 .setMemRefs(MMOBegin, MMOEnd);
14673 // If we branched, emit the PHI to the front of endMBB.
14675 BuildMI(*endMBB, endMBB->begin(), DL,
14676 TII->get(X86::PHI), DestReg)
14677 .addReg(OffsetDestReg).addMBB(offsetMBB)
14678 .addReg(OverflowDestReg).addMBB(overflowMBB);
14681 // Erase the pseudo instruction
14682 MI->eraseFromParent();
14687 MachineBasicBlock *
14688 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14690 MachineBasicBlock *MBB) const {
14691 // Emit code to save XMM registers to the stack. The ABI says that the
14692 // number of registers to save is given in %al, so it's theoretically
14693 // possible to do an indirect jump trick to avoid saving all of them,
14694 // however this code takes a simpler approach and just executes all
14695 // of the stores if %al is non-zero. It's less code, and it's probably
14696 // easier on the hardware branch predictor, and stores aren't all that
14697 // expensive anyway.
14699 // Create the new basic blocks. One block contains all the XMM stores,
14700 // and one block is the final destination regardless of whether any
14701 // stores were performed.
14702 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14703 MachineFunction *F = MBB->getParent();
14704 MachineFunction::iterator MBBIter = MBB;
14706 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14707 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14708 F->insert(MBBIter, XMMSaveMBB);
14709 F->insert(MBBIter, EndMBB);
14711 // Transfer the remainder of MBB and its successor edges to EndMBB.
14712 EndMBB->splice(EndMBB->begin(), MBB,
14713 llvm::next(MachineBasicBlock::iterator(MI)),
14715 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14717 // The original block will now fall through to the XMM save block.
14718 MBB->addSuccessor(XMMSaveMBB);
14719 // The XMMSaveMBB will fall through to the end block.
14720 XMMSaveMBB->addSuccessor(EndMBB);
14722 // Now add the instructions.
14723 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14724 DebugLoc DL = MI->getDebugLoc();
14726 unsigned CountReg = MI->getOperand(0).getReg();
14727 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14728 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14730 if (!Subtarget->isTargetWin64()) {
14731 // If %al is 0, branch around the XMM save block.
14732 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14733 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14734 MBB->addSuccessor(EndMBB);
14737 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14738 // In the XMM save block, save all the XMM argument registers.
14739 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14740 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14741 MachineMemOperand *MMO =
14742 F->getMachineMemOperand(
14743 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14744 MachineMemOperand::MOStore,
14745 /*Size=*/16, /*Align=*/16);
14746 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14747 .addFrameIndex(RegSaveFrameIndex)
14748 .addImm(/*Scale=*/1)
14749 .addReg(/*IndexReg=*/0)
14750 .addImm(/*Disp=*/Offset)
14751 .addReg(/*Segment=*/0)
14752 .addReg(MI->getOperand(i).getReg())
14753 .addMemOperand(MMO);
14756 MI->eraseFromParent(); // The pseudo instruction is gone now.
14761 // The EFLAGS operand of SelectItr might be missing a kill marker
14762 // because there were multiple uses of EFLAGS, and ISel didn't know
14763 // which to mark. Figure out whether SelectItr should have had a
14764 // kill marker, and set it if it should. Returns the correct kill
14766 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14767 MachineBasicBlock* BB,
14768 const TargetRegisterInfo* TRI) {
14769 // Scan forward through BB for a use/def of EFLAGS.
14770 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14771 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14772 const MachineInstr& mi = *miI;
14773 if (mi.readsRegister(X86::EFLAGS))
14775 if (mi.definesRegister(X86::EFLAGS))
14776 break; // Should have kill-flag - update below.
14779 // If we hit the end of the block, check whether EFLAGS is live into a
14781 if (miI == BB->end()) {
14782 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14783 sEnd = BB->succ_end();
14784 sItr != sEnd; ++sItr) {
14785 MachineBasicBlock* succ = *sItr;
14786 if (succ->isLiveIn(X86::EFLAGS))
14791 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14792 // out. SelectMI should have a kill flag on EFLAGS.
14793 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14797 MachineBasicBlock *
14798 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14799 MachineBasicBlock *BB) const {
14800 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14801 DebugLoc DL = MI->getDebugLoc();
14803 // To "insert" a SELECT_CC instruction, we actually have to insert the
14804 // diamond control-flow pattern. The incoming instruction knows the
14805 // destination vreg to set, the condition code register to branch on, the
14806 // true/false values to select between, and a branch opcode to use.
14807 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14808 MachineFunction::iterator It = BB;
14814 // cmpTY ccX, r1, r2
14816 // fallthrough --> copy0MBB
14817 MachineBasicBlock *thisMBB = BB;
14818 MachineFunction *F = BB->getParent();
14819 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14820 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14821 F->insert(It, copy0MBB);
14822 F->insert(It, sinkMBB);
14824 // If the EFLAGS register isn't dead in the terminator, then claim that it's
14825 // live into the sink and copy blocks.
14826 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14827 if (!MI->killsRegister(X86::EFLAGS) &&
14828 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14829 copy0MBB->addLiveIn(X86::EFLAGS);
14830 sinkMBB->addLiveIn(X86::EFLAGS);
14833 // Transfer the remainder of BB and its successor edges to sinkMBB.
14834 sinkMBB->splice(sinkMBB->begin(), BB,
14835 llvm::next(MachineBasicBlock::iterator(MI)),
14837 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14839 // Add the true and fallthrough blocks as its successors.
14840 BB->addSuccessor(copy0MBB);
14841 BB->addSuccessor(sinkMBB);
14843 // Create the conditional branch instruction.
14845 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14846 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14849 // %FalseValue = ...
14850 // # fallthrough to sinkMBB
14851 copy0MBB->addSuccessor(sinkMBB);
14854 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14856 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14857 TII->get(X86::PHI), MI->getOperand(0).getReg())
14858 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14859 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14861 MI->eraseFromParent(); // The pseudo instruction is gone now.
14865 MachineBasicBlock *
14866 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14867 bool Is64Bit) const {
14868 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14869 DebugLoc DL = MI->getDebugLoc();
14870 MachineFunction *MF = BB->getParent();
14871 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14873 assert(getTargetMachine().Options.EnableSegmentedStacks);
14875 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14876 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14879 // ... [Till the alloca]
14880 // If stacklet is not large enough, jump to mallocMBB
14883 // Allocate by subtracting from RSP
14884 // Jump to continueMBB
14887 // Allocate by call to runtime
14891 // [rest of original BB]
14894 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14895 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14896 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14898 MachineRegisterInfo &MRI = MF->getRegInfo();
14899 const TargetRegisterClass *AddrRegClass =
14900 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14902 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14903 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14904 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14905 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14906 sizeVReg = MI->getOperand(1).getReg(),
14907 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14909 MachineFunction::iterator MBBIter = BB;
14912 MF->insert(MBBIter, bumpMBB);
14913 MF->insert(MBBIter, mallocMBB);
14914 MF->insert(MBBIter, continueMBB);
14916 continueMBB->splice(continueMBB->begin(), BB, llvm::next
14917 (MachineBasicBlock::iterator(MI)), BB->end());
14918 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14920 // Add code to the main basic block to check if the stack limit has been hit,
14921 // and if so, jump to mallocMBB otherwise to bumpMBB.
14922 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14923 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14924 .addReg(tmpSPVReg).addReg(sizeVReg);
14925 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14926 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14927 .addReg(SPLimitVReg);
14928 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14930 // bumpMBB simply decreases the stack pointer, since we know the current
14931 // stacklet has enough space.
14932 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14933 .addReg(SPLimitVReg);
14934 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14935 .addReg(SPLimitVReg);
14936 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14938 // Calls into a routine in libgcc to allocate more space from the heap.
14939 const uint32_t *RegMask =
14940 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14942 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14944 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14945 .addExternalSymbol("__morestack_allocate_stack_space")
14946 .addRegMask(RegMask)
14947 .addReg(X86::RDI, RegState::Implicit)
14948 .addReg(X86::RAX, RegState::ImplicitDefine);
14950 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14952 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14953 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14954 .addExternalSymbol("__morestack_allocate_stack_space")
14955 .addRegMask(RegMask)
14956 .addReg(X86::EAX, RegState::ImplicitDefine);
14960 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14963 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14964 .addReg(Is64Bit ? X86::RAX : X86::EAX);
14965 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14967 // Set up the CFG correctly.
14968 BB->addSuccessor(bumpMBB);
14969 BB->addSuccessor(mallocMBB);
14970 mallocMBB->addSuccessor(continueMBB);
14971 bumpMBB->addSuccessor(continueMBB);
14973 // Take care of the PHI nodes.
14974 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14975 MI->getOperand(0).getReg())
14976 .addReg(mallocPtrVReg).addMBB(mallocMBB)
14977 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14979 // Delete the original pseudo instruction.
14980 MI->eraseFromParent();
14983 return continueMBB;
14986 MachineBasicBlock *
14987 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14988 MachineBasicBlock *BB) const {
14989 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14990 DebugLoc DL = MI->getDebugLoc();
14992 assert(!Subtarget->isTargetEnvMacho());
14994 // The lowering is pretty easy: we're just emitting the call to _alloca. The
14995 // non-trivial part is impdef of ESP.
14997 if (Subtarget->isTargetWin64()) {
14998 if (Subtarget->isTargetCygMing()) {
14999 // ___chkstk(Mingw64):
15000 // Clobbers R10, R11, RAX and EFLAGS.
15002 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15003 .addExternalSymbol("___chkstk")
15004 .addReg(X86::RAX, RegState::Implicit)
15005 .addReg(X86::RSP, RegState::Implicit)
15006 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15007 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15008 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15010 // __chkstk(MSVCRT): does not update stack pointer.
15011 // Clobbers R10, R11 and EFLAGS.
15012 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15013 .addExternalSymbol("__chkstk")
15014 .addReg(X86::RAX, RegState::Implicit)
15015 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15016 // RAX has the offset to be subtracted from RSP.
15017 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15022 const char *StackProbeSymbol =
15023 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15025 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15026 .addExternalSymbol(StackProbeSymbol)
15027 .addReg(X86::EAX, RegState::Implicit)
15028 .addReg(X86::ESP, RegState::Implicit)
15029 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15030 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15031 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15034 MI->eraseFromParent(); // The pseudo instruction is gone now.
15038 MachineBasicBlock *
15039 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15040 MachineBasicBlock *BB) const {
15041 // This is pretty easy. We're taking the value that we received from
15042 // our load from the relocation, sticking it in either RDI (x86-64)
15043 // or EAX and doing an indirect call. The return value will then
15044 // be in the normal return register.
15045 const X86InstrInfo *TII
15046 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15047 DebugLoc DL = MI->getDebugLoc();
15048 MachineFunction *F = BB->getParent();
15050 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15051 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15053 // Get a register mask for the lowered call.
15054 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15055 // proper register mask.
15056 const uint32_t *RegMask =
15057 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15058 if (Subtarget->is64Bit()) {
15059 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15060 TII->get(X86::MOV64rm), X86::RDI)
15062 .addImm(0).addReg(0)
15063 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15064 MI->getOperand(3).getTargetFlags())
15066 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15067 addDirectMem(MIB, X86::RDI);
15068 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15069 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15070 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15071 TII->get(X86::MOV32rm), X86::EAX)
15073 .addImm(0).addReg(0)
15074 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15075 MI->getOperand(3).getTargetFlags())
15077 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15078 addDirectMem(MIB, X86::EAX);
15079 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15081 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15082 TII->get(X86::MOV32rm), X86::EAX)
15083 .addReg(TII->getGlobalBaseReg(F))
15084 .addImm(0).addReg(0)
15085 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15086 MI->getOperand(3).getTargetFlags())
15088 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15089 addDirectMem(MIB, X86::EAX);
15090 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15093 MI->eraseFromParent(); // The pseudo instruction is gone now.
15097 MachineBasicBlock *
15098 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15099 MachineBasicBlock *MBB) const {
15100 DebugLoc DL = MI->getDebugLoc();
15101 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15103 MachineFunction *MF = MBB->getParent();
15104 MachineRegisterInfo &MRI = MF->getRegInfo();
15106 const BasicBlock *BB = MBB->getBasicBlock();
15107 MachineFunction::iterator I = MBB;
15110 // Memory Reference
15111 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15112 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15115 unsigned MemOpndSlot = 0;
15117 unsigned CurOp = 0;
15119 DstReg = MI->getOperand(CurOp++).getReg();
15120 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15121 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15122 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15123 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15125 MemOpndSlot = CurOp;
15127 MVT PVT = getPointerTy();
15128 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15129 "Invalid Pointer Size!");
15131 // For v = setjmp(buf), we generate
15134 // buf[LabelOffset] = restoreMBB
15135 // SjLjSetup restoreMBB
15141 // v = phi(main, restore)
15146 MachineBasicBlock *thisMBB = MBB;
15147 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15148 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15149 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15150 MF->insert(I, mainMBB);
15151 MF->insert(I, sinkMBB);
15152 MF->push_back(restoreMBB);
15154 MachineInstrBuilder MIB;
15156 // Transfer the remainder of BB and its successor edges to sinkMBB.
15157 sinkMBB->splice(sinkMBB->begin(), MBB,
15158 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15159 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15162 unsigned PtrStoreOpc = 0;
15163 unsigned LabelReg = 0;
15164 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15165 Reloc::Model RM = getTargetMachine().getRelocationModel();
15166 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15167 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15169 // Prepare IP either in reg or imm.
15170 if (!UseImmLabel) {
15171 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15172 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15173 LabelReg = MRI.createVirtualRegister(PtrRC);
15174 if (Subtarget->is64Bit()) {
15175 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15179 .addMBB(restoreMBB)
15182 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15183 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15184 .addReg(XII->getGlobalBaseReg(MF))
15187 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15191 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15193 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15194 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15195 if (i == X86::AddrDisp)
15196 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15198 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15201 MIB.addReg(LabelReg);
15203 MIB.addMBB(restoreMBB);
15204 MIB.setMemRefs(MMOBegin, MMOEnd);
15206 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15207 .addMBB(restoreMBB);
15209 const X86RegisterInfo *RegInfo =
15210 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15211 MIB.addRegMask(RegInfo->getNoPreservedMask());
15212 thisMBB->addSuccessor(mainMBB);
15213 thisMBB->addSuccessor(restoreMBB);
15217 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15218 mainMBB->addSuccessor(sinkMBB);
15221 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15222 TII->get(X86::PHI), DstReg)
15223 .addReg(mainDstReg).addMBB(mainMBB)
15224 .addReg(restoreDstReg).addMBB(restoreMBB);
15227 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15228 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15229 restoreMBB->addSuccessor(sinkMBB);
15231 MI->eraseFromParent();
15235 MachineBasicBlock *
15236 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15237 MachineBasicBlock *MBB) const {
15238 DebugLoc DL = MI->getDebugLoc();
15239 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15241 MachineFunction *MF = MBB->getParent();
15242 MachineRegisterInfo &MRI = MF->getRegInfo();
15244 // Memory Reference
15245 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15246 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15248 MVT PVT = getPointerTy();
15249 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15250 "Invalid Pointer Size!");
15252 const TargetRegisterClass *RC =
15253 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15254 unsigned Tmp = MRI.createVirtualRegister(RC);
15255 // Since FP is only updated here but NOT referenced, it's treated as GPR.
15256 const X86RegisterInfo *RegInfo =
15257 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15258 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15259 unsigned SP = RegInfo->getStackRegister();
15261 MachineInstrBuilder MIB;
15263 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15264 const int64_t SPOffset = 2 * PVT.getStoreSize();
15266 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15267 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15270 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15271 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15272 MIB.addOperand(MI->getOperand(i));
15273 MIB.setMemRefs(MMOBegin, MMOEnd);
15275 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15276 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15277 if (i == X86::AddrDisp)
15278 MIB.addDisp(MI->getOperand(i), LabelOffset);
15280 MIB.addOperand(MI->getOperand(i));
15282 MIB.setMemRefs(MMOBegin, MMOEnd);
15284 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15285 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15286 if (i == X86::AddrDisp)
15287 MIB.addDisp(MI->getOperand(i), SPOffset);
15289 MIB.addOperand(MI->getOperand(i));
15291 MIB.setMemRefs(MMOBegin, MMOEnd);
15293 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15295 MI->eraseFromParent();
15299 MachineBasicBlock *
15300 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15301 MachineBasicBlock *BB) const {
15302 switch (MI->getOpcode()) {
15303 default: llvm_unreachable("Unexpected instr type to insert");
15304 case X86::TAILJMPd64:
15305 case X86::TAILJMPr64:
15306 case X86::TAILJMPm64:
15307 llvm_unreachable("TAILJMP64 would not be touched here.");
15308 case X86::TCRETURNdi64:
15309 case X86::TCRETURNri64:
15310 case X86::TCRETURNmi64:
15312 case X86::WIN_ALLOCA:
15313 return EmitLoweredWinAlloca(MI, BB);
15314 case X86::SEG_ALLOCA_32:
15315 return EmitLoweredSegAlloca(MI, BB, false);
15316 case X86::SEG_ALLOCA_64:
15317 return EmitLoweredSegAlloca(MI, BB, true);
15318 case X86::TLSCall_32:
15319 case X86::TLSCall_64:
15320 return EmitLoweredTLSCall(MI, BB);
15321 case X86::CMOV_GR8:
15322 case X86::CMOV_FR32:
15323 case X86::CMOV_FR64:
15324 case X86::CMOV_V4F32:
15325 case X86::CMOV_V2F64:
15326 case X86::CMOV_V2I64:
15327 case X86::CMOV_V8F32:
15328 case X86::CMOV_V4F64:
15329 case X86::CMOV_V4I64:
15330 case X86::CMOV_GR16:
15331 case X86::CMOV_GR32:
15332 case X86::CMOV_RFP32:
15333 case X86::CMOV_RFP64:
15334 case X86::CMOV_RFP80:
15335 return EmitLoweredSelect(MI, BB);
15337 case X86::FP32_TO_INT16_IN_MEM:
15338 case X86::FP32_TO_INT32_IN_MEM:
15339 case X86::FP32_TO_INT64_IN_MEM:
15340 case X86::FP64_TO_INT16_IN_MEM:
15341 case X86::FP64_TO_INT32_IN_MEM:
15342 case X86::FP64_TO_INT64_IN_MEM:
15343 case X86::FP80_TO_INT16_IN_MEM:
15344 case X86::FP80_TO_INT32_IN_MEM:
15345 case X86::FP80_TO_INT64_IN_MEM: {
15346 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15347 DebugLoc DL = MI->getDebugLoc();
15349 // Change the floating point control register to use "round towards zero"
15350 // mode when truncating to an integer value.
15351 MachineFunction *F = BB->getParent();
15352 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15353 addFrameReference(BuildMI(*BB, MI, DL,
15354 TII->get(X86::FNSTCW16m)), CWFrameIdx);
15356 // Load the old value of the high byte of the control word...
15358 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15359 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15362 // Set the high part to be round to zero...
15363 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15366 // Reload the modified control word now...
15367 addFrameReference(BuildMI(*BB, MI, DL,
15368 TII->get(X86::FLDCW16m)), CWFrameIdx);
15370 // Restore the memory image of control word to original value
15371 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15374 // Get the X86 opcode to use.
15376 switch (MI->getOpcode()) {
15377 default: llvm_unreachable("illegal opcode!");
15378 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15379 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15380 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15381 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15382 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15383 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15384 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15385 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15386 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15390 MachineOperand &Op = MI->getOperand(0);
15392 AM.BaseType = X86AddressMode::RegBase;
15393 AM.Base.Reg = Op.getReg();
15395 AM.BaseType = X86AddressMode::FrameIndexBase;
15396 AM.Base.FrameIndex = Op.getIndex();
15398 Op = MI->getOperand(1);
15400 AM.Scale = Op.getImm();
15401 Op = MI->getOperand(2);
15403 AM.IndexReg = Op.getImm();
15404 Op = MI->getOperand(3);
15405 if (Op.isGlobal()) {
15406 AM.GV = Op.getGlobal();
15408 AM.Disp = Op.getImm();
15410 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15411 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15413 // Reload the original control word now.
15414 addFrameReference(BuildMI(*BB, MI, DL,
15415 TII->get(X86::FLDCW16m)), CWFrameIdx);
15417 MI->eraseFromParent(); // The pseudo instruction is gone now.
15420 // String/text processing lowering.
15421 case X86::PCMPISTRM128REG:
15422 case X86::VPCMPISTRM128REG:
15423 case X86::PCMPISTRM128MEM:
15424 case X86::VPCMPISTRM128MEM:
15425 case X86::PCMPESTRM128REG:
15426 case X86::VPCMPESTRM128REG:
15427 case X86::PCMPESTRM128MEM:
15428 case X86::VPCMPESTRM128MEM:
15429 assert(Subtarget->hasSSE42() &&
15430 "Target must have SSE4.2 or AVX features enabled");
15431 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15433 // String/text processing lowering.
15434 case X86::PCMPISTRIREG:
15435 case X86::VPCMPISTRIREG:
15436 case X86::PCMPISTRIMEM:
15437 case X86::VPCMPISTRIMEM:
15438 case X86::PCMPESTRIREG:
15439 case X86::VPCMPESTRIREG:
15440 case X86::PCMPESTRIMEM:
15441 case X86::VPCMPESTRIMEM:
15442 assert(Subtarget->hasSSE42() &&
15443 "Target must have SSE4.2 or AVX features enabled");
15444 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15446 // Thread synchronization.
15448 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15452 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15454 // Atomic Lowering.
15455 case X86::ATOMAND8:
15456 case X86::ATOMAND16:
15457 case X86::ATOMAND32:
15458 case X86::ATOMAND64:
15461 case X86::ATOMOR16:
15462 case X86::ATOMOR32:
15463 case X86::ATOMOR64:
15465 case X86::ATOMXOR16:
15466 case X86::ATOMXOR8:
15467 case X86::ATOMXOR32:
15468 case X86::ATOMXOR64:
15470 case X86::ATOMNAND8:
15471 case X86::ATOMNAND16:
15472 case X86::ATOMNAND32:
15473 case X86::ATOMNAND64:
15475 case X86::ATOMMAX8:
15476 case X86::ATOMMAX16:
15477 case X86::ATOMMAX32:
15478 case X86::ATOMMAX64:
15480 case X86::ATOMMIN8:
15481 case X86::ATOMMIN16:
15482 case X86::ATOMMIN32:
15483 case X86::ATOMMIN64:
15485 case X86::ATOMUMAX8:
15486 case X86::ATOMUMAX16:
15487 case X86::ATOMUMAX32:
15488 case X86::ATOMUMAX64:
15490 case X86::ATOMUMIN8:
15491 case X86::ATOMUMIN16:
15492 case X86::ATOMUMIN32:
15493 case X86::ATOMUMIN64:
15494 return EmitAtomicLoadArith(MI, BB);
15496 // This group does 64-bit operations on a 32-bit host.
15497 case X86::ATOMAND6432:
15498 case X86::ATOMOR6432:
15499 case X86::ATOMXOR6432:
15500 case X86::ATOMNAND6432:
15501 case X86::ATOMADD6432:
15502 case X86::ATOMSUB6432:
15503 case X86::ATOMMAX6432:
15504 case X86::ATOMMIN6432:
15505 case X86::ATOMUMAX6432:
15506 case X86::ATOMUMIN6432:
15507 case X86::ATOMSWAP6432:
15508 return EmitAtomicLoadArith6432(MI, BB);
15510 case X86::VASTART_SAVE_XMM_REGS:
15511 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15513 case X86::VAARG_64:
15514 return EmitVAARG64WithCustomInserter(MI, BB);
15516 case X86::EH_SjLj_SetJmp32:
15517 case X86::EH_SjLj_SetJmp64:
15518 return emitEHSjLjSetJmp(MI, BB);
15520 case X86::EH_SjLj_LongJmp32:
15521 case X86::EH_SjLj_LongJmp64:
15522 return emitEHSjLjLongJmp(MI, BB);
15526 //===----------------------------------------------------------------------===//
15527 // X86 Optimization Hooks
15528 //===----------------------------------------------------------------------===//
15530 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15533 const SelectionDAG &DAG,
15534 unsigned Depth) const {
15535 unsigned BitWidth = KnownZero.getBitWidth();
15536 unsigned Opc = Op.getOpcode();
15537 assert((Opc >= ISD::BUILTIN_OP_END ||
15538 Opc == ISD::INTRINSIC_WO_CHAIN ||
15539 Opc == ISD::INTRINSIC_W_CHAIN ||
15540 Opc == ISD::INTRINSIC_VOID) &&
15541 "Should use MaskedValueIsZero if you don't know whether Op"
15542 " is a target node!");
15544 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
15558 // These nodes' second result is a boolean.
15559 if (Op.getResNo() == 0)
15562 case X86ISD::SETCC:
15563 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15565 case ISD::INTRINSIC_WO_CHAIN: {
15566 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15567 unsigned NumLoBits = 0;
15570 case Intrinsic::x86_sse_movmsk_ps:
15571 case Intrinsic::x86_avx_movmsk_ps_256:
15572 case Intrinsic::x86_sse2_movmsk_pd:
15573 case Intrinsic::x86_avx_movmsk_pd_256:
15574 case Intrinsic::x86_mmx_pmovmskb:
15575 case Intrinsic::x86_sse2_pmovmskb_128:
15576 case Intrinsic::x86_avx2_pmovmskb: {
15577 // High bits of movmskp{s|d}, pmovmskb are known zero.
15579 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15580 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
15581 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
15582 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
15583 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
15584 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
15585 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
15586 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
15588 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15597 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15598 unsigned Depth) const {
15599 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15600 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15601 return Op.getValueType().getScalarType().getSizeInBits();
15607 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15608 /// node is a GlobalAddress + offset.
15609 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15610 const GlobalValue* &GA,
15611 int64_t &Offset) const {
15612 if (N->getOpcode() == X86ISD::Wrapper) {
15613 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15614 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15615 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15619 return TargetLowering::isGAPlusOffset(N, GA, Offset);
15622 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15623 /// same as extracting the high 128-bit part of 256-bit vector and then
15624 /// inserting the result into the low part of a new 256-bit vector
15625 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15626 EVT VT = SVOp->getValueType(0);
15627 unsigned NumElems = VT.getVectorNumElements();
15629 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15630 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15631 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15632 SVOp->getMaskElt(j) >= 0)
15638 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15639 /// same as extracting the low 128-bit part of 256-bit vector and then
15640 /// inserting the result into the high part of a new 256-bit vector
15641 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15642 EVT VT = SVOp->getValueType(0);
15643 unsigned NumElems = VT.getVectorNumElements();
15645 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15646 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15647 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15648 SVOp->getMaskElt(j) >= 0)
15654 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15655 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15656 TargetLowering::DAGCombinerInfo &DCI,
15657 const X86Subtarget* Subtarget) {
15659 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15660 SDValue V1 = SVOp->getOperand(0);
15661 SDValue V2 = SVOp->getOperand(1);
15662 EVT VT = SVOp->getValueType(0);
15663 unsigned NumElems = VT.getVectorNumElements();
15665 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15666 V2.getOpcode() == ISD::CONCAT_VECTORS) {
15670 // V UNDEF BUILD_VECTOR UNDEF
15672 // CONCAT_VECTOR CONCAT_VECTOR
15675 // RESULT: V + zero extended
15677 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15678 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15679 V1.getOperand(1).getOpcode() != ISD::UNDEF)
15682 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15685 // To match the shuffle mask, the first half of the mask should
15686 // be exactly the first vector, and all the rest a splat with the
15687 // first element of the second one.
15688 for (unsigned i = 0; i != NumElems/2; ++i)
15689 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15690 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15693 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15694 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15695 if (Ld->hasNUsesOfValue(1, 0)) {
15696 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15697 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15699 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15700 array_lengthof(Ops),
15702 Ld->getPointerInfo(),
15703 Ld->getAlignment(),
15704 false/*isVolatile*/, true/*ReadMem*/,
15705 false/*WriteMem*/);
15707 // Make sure the newly-created LOAD is in the same position as Ld in
15708 // terms of dependency. We create a TokenFactor for Ld and ResNode,
15709 // and update uses of Ld's output chain to use the TokenFactor.
15710 if (Ld->hasAnyUseOfValue(1)) {
15711 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15712 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15713 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15714 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15715 SDValue(ResNode.getNode(), 1));
15718 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15722 // Emit a zeroed vector and insert the desired subvector on its
15724 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15725 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15726 return DCI.CombineTo(N, InsV);
15729 //===--------------------------------------------------------------------===//
15730 // Combine some shuffles into subvector extracts and inserts:
15733 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15734 if (isShuffleHigh128VectorInsertLow(SVOp)) {
15735 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15736 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15737 return DCI.CombineTo(N, InsV);
15740 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15741 if (isShuffleLow128VectorInsertHigh(SVOp)) {
15742 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15743 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15744 return DCI.CombineTo(N, InsV);
15750 /// PerformShuffleCombine - Performs several different shuffle combines.
15751 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15752 TargetLowering::DAGCombinerInfo &DCI,
15753 const X86Subtarget *Subtarget) {
15755 EVT VT = N->getValueType(0);
15757 // Don't create instructions with illegal types after legalize types has run.
15758 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15759 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15762 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15763 if (Subtarget->hasFp256() && VT.is256BitVector() &&
15764 N->getOpcode() == ISD::VECTOR_SHUFFLE)
15765 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15767 // Only handle 128 wide vector from here on.
15768 if (!VT.is128BitVector())
15771 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15772 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15773 // consecutive, non-overlapping, and in the right order.
15774 SmallVector<SDValue, 16> Elts;
15775 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15776 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15778 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15781 /// PerformTruncateCombine - Converts truncate operation to
15782 /// a sequence of vector shuffle operations.
15783 /// It is possible when we truncate 256-bit vector to 128-bit vector
15784 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15785 TargetLowering::DAGCombinerInfo &DCI,
15786 const X86Subtarget *Subtarget) {
15790 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15791 /// specific shuffle of a load can be folded into a single element load.
15792 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15793 /// shuffles have been customed lowered so we need to handle those here.
15794 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15795 TargetLowering::DAGCombinerInfo &DCI) {
15796 if (DCI.isBeforeLegalizeOps())
15799 SDValue InVec = N->getOperand(0);
15800 SDValue EltNo = N->getOperand(1);
15802 if (!isa<ConstantSDNode>(EltNo))
15805 EVT VT = InVec.getValueType();
15807 bool HasShuffleIntoBitcast = false;
15808 if (InVec.getOpcode() == ISD::BITCAST) {
15809 // Don't duplicate a load with other uses.
15810 if (!InVec.hasOneUse())
15812 EVT BCVT = InVec.getOperand(0).getValueType();
15813 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15815 InVec = InVec.getOperand(0);
15816 HasShuffleIntoBitcast = true;
15819 if (!isTargetShuffle(InVec.getOpcode()))
15822 // Don't duplicate a load with other uses.
15823 if (!InVec.hasOneUse())
15826 SmallVector<int, 16> ShuffleMask;
15828 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15832 // Select the input vector, guarding against out of range extract vector.
15833 unsigned NumElems = VT.getVectorNumElements();
15834 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15835 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15836 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15837 : InVec.getOperand(1);
15839 // If inputs to shuffle are the same for both ops, then allow 2 uses
15840 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15842 if (LdNode.getOpcode() == ISD::BITCAST) {
15843 // Don't duplicate a load with other uses.
15844 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15847 AllowedUses = 1; // only allow 1 load use if we have a bitcast
15848 LdNode = LdNode.getOperand(0);
15851 if (!ISD::isNormalLoad(LdNode.getNode()))
15854 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15856 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15859 if (HasShuffleIntoBitcast) {
15860 // If there's a bitcast before the shuffle, check if the load type and
15861 // alignment is valid.
15862 unsigned Align = LN0->getAlignment();
15863 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15864 unsigned NewAlign = TLI.getDataLayout()->
15865 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15867 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15871 // All checks match so transform back to vector_shuffle so that DAG combiner
15872 // can finish the job
15875 // Create shuffle node taking into account the case that its a unary shuffle
15876 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15877 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15878 InVec.getOperand(0), Shuffle,
15880 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15881 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15885 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15886 /// generation and convert it from being a bunch of shuffles and extracts
15887 /// to a simple store and scalar loads to extract the elements.
15888 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15889 TargetLowering::DAGCombinerInfo &DCI) {
15890 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15891 if (NewOp.getNode())
15894 SDValue InputVector = N->getOperand(0);
15895 // Detect whether we are trying to convert from mmx to i32 and the bitcast
15896 // from mmx to v2i32 has a single usage.
15897 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15898 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15899 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15900 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15901 N->getValueType(0),
15902 InputVector.getNode()->getOperand(0));
15904 // Only operate on vectors of 4 elements, where the alternative shuffling
15905 // gets to be more expensive.
15906 if (InputVector.getValueType() != MVT::v4i32)
15909 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15910 // single use which is a sign-extend or zero-extend, and all elements are
15912 SmallVector<SDNode *, 4> Uses;
15913 unsigned ExtractedElements = 0;
15914 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15915 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15916 if (UI.getUse().getResNo() != InputVector.getResNo())
15919 SDNode *Extract = *UI;
15920 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15923 if (Extract->getValueType(0) != MVT::i32)
15925 if (!Extract->hasOneUse())
15927 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15928 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15930 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15933 // Record which element was extracted.
15934 ExtractedElements |=
15935 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15937 Uses.push_back(Extract);
15940 // If not all the elements were used, this may not be worthwhile.
15941 if (ExtractedElements != 15)
15944 // Ok, we've now decided to do the transformation.
15945 SDLoc dl(InputVector);
15947 // Store the value to a temporary stack slot.
15948 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15949 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15950 MachinePointerInfo(), false, false, 0);
15952 // Replace each use (extract) with a load of the appropriate element.
15953 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15954 UE = Uses.end(); UI != UE; ++UI) {
15955 SDNode *Extract = *UI;
15957 // cOMpute the element's address.
15958 SDValue Idx = Extract->getOperand(1);
15960 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15961 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15962 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15963 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15965 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15966 StackPtr, OffsetVal);
15968 // Load the scalar.
15969 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15970 ScalarAddr, MachinePointerInfo(),
15971 false, false, false, 0);
15973 // Replace the exact with the load.
15974 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15977 // The replacement was made in place; don't return anything.
15981 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15982 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15983 SDValue RHS, SelectionDAG &DAG,
15984 const X86Subtarget *Subtarget) {
15985 if (!VT.isVector())
15988 switch (VT.getSimpleVT().SimpleTy) {
15993 if (!Subtarget->hasAVX2())
15998 if (!Subtarget->hasSSE2())
16002 // SSE2 has only a small subset of the operations.
16003 bool hasUnsigned = Subtarget->hasSSE41() ||
16004 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16005 bool hasSigned = Subtarget->hasSSE41() ||
16006 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16008 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16010 // Check for x CC y ? x : y.
16011 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16012 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16017 return hasUnsigned ? X86ISD::UMIN : 0;
16020 return hasUnsigned ? X86ISD::UMAX : 0;
16023 return hasSigned ? X86ISD::SMIN : 0;
16026 return hasSigned ? X86ISD::SMAX : 0;
16028 // Check for x CC y ? y : x -- a min/max with reversed arms.
16029 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16030 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16035 return hasUnsigned ? X86ISD::UMAX : 0;
16038 return hasUnsigned ? X86ISD::UMIN : 0;
16041 return hasSigned ? X86ISD::SMAX : 0;
16044 return hasSigned ? X86ISD::SMIN : 0;
16051 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16053 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16054 TargetLowering::DAGCombinerInfo &DCI,
16055 const X86Subtarget *Subtarget) {
16057 SDValue Cond = N->getOperand(0);
16058 // Get the LHS/RHS of the select.
16059 SDValue LHS = N->getOperand(1);
16060 SDValue RHS = N->getOperand(2);
16061 EVT VT = LHS.getValueType();
16063 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16064 // instructions match the semantics of the common C idiom x<y?x:y but not
16065 // x<=y?x:y, because of how they handle negative zero (which can be
16066 // ignored in unsafe-math mode).
16067 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16068 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16069 (Subtarget->hasSSE2() ||
16070 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16071 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16073 unsigned Opcode = 0;
16074 // Check for x CC y ? x : y.
16075 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16076 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16080 // Converting this to a min would handle NaNs incorrectly, and swapping
16081 // the operands would cause it to handle comparisons between positive
16082 // and negative zero incorrectly.
16083 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16084 if (!DAG.getTarget().Options.UnsafeFPMath &&
16085 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16087 std::swap(LHS, RHS);
16089 Opcode = X86ISD::FMIN;
16092 // Converting this to a min would handle comparisons between positive
16093 // and negative zero incorrectly.
16094 if (!DAG.getTarget().Options.UnsafeFPMath &&
16095 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16097 Opcode = X86ISD::FMIN;
16100 // Converting this to a min would handle both negative zeros and NaNs
16101 // incorrectly, but we can swap the operands to fix both.
16102 std::swap(LHS, RHS);
16106 Opcode = X86ISD::FMIN;
16110 // Converting this to a max would handle comparisons between positive
16111 // and negative zero incorrectly.
16112 if (!DAG.getTarget().Options.UnsafeFPMath &&
16113 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16115 Opcode = X86ISD::FMAX;
16118 // Converting this to a max would handle NaNs incorrectly, and swapping
16119 // the operands would cause it to handle comparisons between positive
16120 // and negative zero incorrectly.
16121 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16122 if (!DAG.getTarget().Options.UnsafeFPMath &&
16123 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16125 std::swap(LHS, RHS);
16127 Opcode = X86ISD::FMAX;
16130 // Converting this to a max would handle both negative zeros and NaNs
16131 // incorrectly, but we can swap the operands to fix both.
16132 std::swap(LHS, RHS);
16136 Opcode = X86ISD::FMAX;
16139 // Check for x CC y ? y : x -- a min/max with reversed arms.
16140 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16141 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16145 // Converting this to a min would handle comparisons between positive
16146 // and negative zero incorrectly, and swapping the operands would
16147 // cause it to handle NaNs incorrectly.
16148 if (!DAG.getTarget().Options.UnsafeFPMath &&
16149 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16150 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16152 std::swap(LHS, RHS);
16154 Opcode = X86ISD::FMIN;
16157 // Converting this to a min would handle NaNs incorrectly.
16158 if (!DAG.getTarget().Options.UnsafeFPMath &&
16159 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16161 Opcode = X86ISD::FMIN;
16164 // Converting this to a min would handle both negative zeros and NaNs
16165 // incorrectly, but we can swap the operands to fix both.
16166 std::swap(LHS, RHS);
16170 Opcode = X86ISD::FMIN;
16174 // Converting this to a max would handle NaNs incorrectly.
16175 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16177 Opcode = X86ISD::FMAX;
16180 // Converting this to a max would handle comparisons between positive
16181 // and negative zero incorrectly, and swapping the operands would
16182 // cause it to handle NaNs incorrectly.
16183 if (!DAG.getTarget().Options.UnsafeFPMath &&
16184 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16185 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16187 std::swap(LHS, RHS);
16189 Opcode = X86ISD::FMAX;
16192 // Converting this to a max would handle both negative zeros and NaNs
16193 // incorrectly, but we can swap the operands to fix both.
16194 std::swap(LHS, RHS);
16198 Opcode = X86ISD::FMAX;
16204 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16207 // If this is a select between two integer constants, try to do some
16209 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16210 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16211 // Don't do this for crazy integer types.
16212 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16213 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16214 // so that TrueC (the true value) is larger than FalseC.
16215 bool NeedsCondInvert = false;
16217 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16218 // Efficiently invertible.
16219 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
16220 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
16221 isa<ConstantSDNode>(Cond.getOperand(1))))) {
16222 NeedsCondInvert = true;
16223 std::swap(TrueC, FalseC);
16226 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
16227 if (FalseC->getAPIntValue() == 0 &&
16228 TrueC->getAPIntValue().isPowerOf2()) {
16229 if (NeedsCondInvert) // Invert the condition if needed.
16230 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16231 DAG.getConstant(1, Cond.getValueType()));
16233 // Zero extend the condition if needed.
16234 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16236 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16237 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16238 DAG.getConstant(ShAmt, MVT::i8));
16241 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16242 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16243 if (NeedsCondInvert) // Invert the condition if needed.
16244 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16245 DAG.getConstant(1, Cond.getValueType()));
16247 // Zero extend the condition if needed.
16248 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16249 FalseC->getValueType(0), Cond);
16250 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16251 SDValue(FalseC, 0));
16254 // Optimize cases that will turn into an LEA instruction. This requires
16255 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16256 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16257 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16258 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16260 bool isFastMultiplier = false;
16262 switch ((unsigned char)Diff) {
16264 case 1: // result = add base, cond
16265 case 2: // result = lea base( , cond*2)
16266 case 3: // result = lea base(cond, cond*2)
16267 case 4: // result = lea base( , cond*4)
16268 case 5: // result = lea base(cond, cond*4)
16269 case 8: // result = lea base( , cond*8)
16270 case 9: // result = lea base(cond, cond*8)
16271 isFastMultiplier = true;
16276 if (isFastMultiplier) {
16277 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16278 if (NeedsCondInvert) // Invert the condition if needed.
16279 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16280 DAG.getConstant(1, Cond.getValueType()));
16282 // Zero extend the condition if needed.
16283 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16285 // Scale the condition by the difference.
16287 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16288 DAG.getConstant(Diff, Cond.getValueType()));
16290 // Add the base if non-zero.
16291 if (FalseC->getAPIntValue() != 0)
16292 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16293 SDValue(FalseC, 0));
16300 // Canonicalize max and min:
16301 // (x > y) ? x : y -> (x >= y) ? x : y
16302 // (x < y) ? x : y -> (x <= y) ? x : y
16303 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16304 // the need for an extra compare
16305 // against zero. e.g.
16306 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16308 // testl %edi, %edi
16310 // cmovgl %edi, %eax
16314 // cmovsl %eax, %edi
16315 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16316 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16317 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16318 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16323 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16324 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16325 Cond.getOperand(0), Cond.getOperand(1), NewCC);
16326 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16331 // Match VSELECTs into subs with unsigned saturation.
16332 if (!DCI.isBeforeLegalize() &&
16333 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16334 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16335 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16336 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16337 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16339 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16340 // left side invert the predicate to simplify logic below.
16342 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16344 CC = ISD::getSetCCInverse(CC, true);
16345 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16349 if (Other.getNode() && Other->getNumOperands() == 2 &&
16350 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16351 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16352 SDValue CondRHS = Cond->getOperand(1);
16354 // Look for a general sub with unsigned saturation first.
16355 // x >= y ? x-y : 0 --> subus x, y
16356 // x > y ? x-y : 0 --> subus x, y
16357 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16358 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16359 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16361 // If the RHS is a constant we have to reverse the const canonicalization.
16362 // x > C-1 ? x+-C : 0 --> subus x, C
16363 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16364 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16365 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16366 if (CondRHS.getConstantOperandVal(0) == -A-1)
16367 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16368 DAG.getConstant(-A, VT));
16371 // Another special case: If C was a sign bit, the sub has been
16372 // canonicalized into a xor.
16373 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16374 // it's safe to decanonicalize the xor?
16375 // x s< 0 ? x^C : 0 --> subus x, C
16376 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16377 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16378 isSplatVector(OpRHS.getNode())) {
16379 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16381 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16386 // Try to match a min/max vector operation.
16387 if (!DCI.isBeforeLegalize() &&
16388 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16389 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16390 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16392 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16393 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16394 Cond.getOpcode() == ISD::SETCC) {
16396 assert(Cond.getValueType().isVector() &&
16397 "vector select expects a vector selector!");
16399 EVT IntVT = Cond.getValueType();
16400 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16401 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16403 if (!TValIsAllOnes && !FValIsAllZeros) {
16404 // Try invert the condition if true value is not all 1s and false value
16406 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16407 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16409 if (TValIsAllZeros || FValIsAllOnes) {
16410 SDValue CC = Cond.getOperand(2);
16411 ISD::CondCode NewCC =
16412 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16413 Cond.getOperand(0).getValueType().isInteger());
16414 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16415 std::swap(LHS, RHS);
16416 TValIsAllOnes = FValIsAllOnes;
16417 FValIsAllZeros = TValIsAllZeros;
16421 if (TValIsAllOnes || FValIsAllZeros) {
16424 if (TValIsAllOnes && FValIsAllZeros)
16426 else if (TValIsAllOnes)
16427 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16428 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16429 else if (FValIsAllZeros)
16430 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16431 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16433 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16437 // If we know that this node is legal then we know that it is going to be
16438 // matched by one of the SSE/AVX BLEND instructions. These instructions only
16439 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16440 // to simplify previous instructions.
16441 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16442 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16443 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16444 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16446 // Don't optimize vector selects that map to mask-registers.
16450 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16451 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16453 APInt KnownZero, KnownOne;
16454 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16455 DCI.isBeforeLegalizeOps());
16456 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16457 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16458 DCI.CommitTargetLoweringOpt(TLO);
16464 // Check whether a boolean test is testing a boolean value generated by
16465 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16468 // Simplify the following patterns:
16469 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16470 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16471 // to (Op EFLAGS Cond)
16473 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16474 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16475 // to (Op EFLAGS !Cond)
16477 // where Op could be BRCOND or CMOV.
16479 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16480 // Quit if not CMP and SUB with its value result used.
16481 if (Cmp.getOpcode() != X86ISD::CMP &&
16482 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16485 // Quit if not used as a boolean value.
16486 if (CC != X86::COND_E && CC != X86::COND_NE)
16489 // Check CMP operands. One of them should be 0 or 1 and the other should be
16490 // an SetCC or extended from it.
16491 SDValue Op1 = Cmp.getOperand(0);
16492 SDValue Op2 = Cmp.getOperand(1);
16495 const ConstantSDNode* C = 0;
16496 bool needOppositeCond = (CC == X86::COND_E);
16497 bool checkAgainstTrue = false; // Is it a comparison against 1?
16499 if ((C = dyn_cast<ConstantSDNode>(Op1)))
16501 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16503 else // Quit if all operands are not constants.
16506 if (C->getZExtValue() == 1) {
16507 needOppositeCond = !needOppositeCond;
16508 checkAgainstTrue = true;
16509 } else if (C->getZExtValue() != 0)
16510 // Quit if the constant is neither 0 or 1.
16513 bool truncatedToBoolWithAnd = false;
16514 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16515 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16516 SetCC.getOpcode() == ISD::TRUNCATE ||
16517 SetCC.getOpcode() == ISD::AND) {
16518 if (SetCC.getOpcode() == ISD::AND) {
16520 ConstantSDNode *CS;
16521 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16522 CS->getZExtValue() == 1)
16524 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16525 CS->getZExtValue() == 1)
16529 SetCC = SetCC.getOperand(OpIdx);
16530 truncatedToBoolWithAnd = true;
16532 SetCC = SetCC.getOperand(0);
16535 switch (SetCC.getOpcode()) {
16536 case X86ISD::SETCC_CARRY:
16537 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16538 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16539 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16540 // truncated to i1 using 'and'.
16541 if (checkAgainstTrue && !truncatedToBoolWithAnd)
16543 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16544 "Invalid use of SETCC_CARRY!");
16546 case X86ISD::SETCC:
16547 // Set the condition code or opposite one if necessary.
16548 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16549 if (needOppositeCond)
16550 CC = X86::GetOppositeBranchCondition(CC);
16551 return SetCC.getOperand(1);
16552 case X86ISD::CMOV: {
16553 // Check whether false/true value has canonical one, i.e. 0 or 1.
16554 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16555 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16556 // Quit if true value is not a constant.
16559 // Quit if false value is not a constant.
16561 SDValue Op = SetCC.getOperand(0);
16562 // Skip 'zext' or 'trunc' node.
16563 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16564 Op.getOpcode() == ISD::TRUNCATE)
16565 Op = Op.getOperand(0);
16566 // A special case for rdrand/rdseed, where 0 is set if false cond is
16568 if ((Op.getOpcode() != X86ISD::RDRAND &&
16569 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16572 // Quit if false value is not the constant 0 or 1.
16573 bool FValIsFalse = true;
16574 if (FVal && FVal->getZExtValue() != 0) {
16575 if (FVal->getZExtValue() != 1)
16577 // If FVal is 1, opposite cond is needed.
16578 needOppositeCond = !needOppositeCond;
16579 FValIsFalse = false;
16581 // Quit if TVal is not the constant opposite of FVal.
16582 if (FValIsFalse && TVal->getZExtValue() != 1)
16584 if (!FValIsFalse && TVal->getZExtValue() != 0)
16586 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16587 if (needOppositeCond)
16588 CC = X86::GetOppositeBranchCondition(CC);
16589 return SetCC.getOperand(3);
16596 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16597 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16598 TargetLowering::DAGCombinerInfo &DCI,
16599 const X86Subtarget *Subtarget) {
16602 // If the flag operand isn't dead, don't touch this CMOV.
16603 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16606 SDValue FalseOp = N->getOperand(0);
16607 SDValue TrueOp = N->getOperand(1);
16608 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16609 SDValue Cond = N->getOperand(3);
16611 if (CC == X86::COND_E || CC == X86::COND_NE) {
16612 switch (Cond.getOpcode()) {
16616 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16617 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16618 return (CC == X86::COND_E) ? FalseOp : TrueOp;
16624 Flags = checkBoolTestSetCCCombine(Cond, CC);
16625 if (Flags.getNode() &&
16626 // Extra check as FCMOV only supports a subset of X86 cond.
16627 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16628 SDValue Ops[] = { FalseOp, TrueOp,
16629 DAG.getConstant(CC, MVT::i8), Flags };
16630 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16631 Ops, array_lengthof(Ops));
16634 // If this is a select between two integer constants, try to do some
16635 // optimizations. Note that the operands are ordered the opposite of SELECT
16637 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16638 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16639 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16640 // larger than FalseC (the false value).
16641 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16642 CC = X86::GetOppositeBranchCondition(CC);
16643 std::swap(TrueC, FalseC);
16644 std::swap(TrueOp, FalseOp);
16647 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
16648 // This is efficient for any integer data type (including i8/i16) and
16650 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16651 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16652 DAG.getConstant(CC, MVT::i8), Cond);
16654 // Zero extend the condition if needed.
16655 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16657 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16658 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16659 DAG.getConstant(ShAmt, MVT::i8));
16660 if (N->getNumValues() == 2) // Dead flag value?
16661 return DCI.CombineTo(N, Cond, SDValue());
16665 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
16666 // for any integer data type, including i8/i16.
16667 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16668 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16669 DAG.getConstant(CC, MVT::i8), Cond);
16671 // Zero extend the condition if needed.
16672 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16673 FalseC->getValueType(0), Cond);
16674 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16675 SDValue(FalseC, 0));
16677 if (N->getNumValues() == 2) // Dead flag value?
16678 return DCI.CombineTo(N, Cond, SDValue());
16682 // Optimize cases that will turn into an LEA instruction. This requires
16683 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16684 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16685 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16686 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16688 bool isFastMultiplier = false;
16690 switch ((unsigned char)Diff) {
16692 case 1: // result = add base, cond
16693 case 2: // result = lea base( , cond*2)
16694 case 3: // result = lea base(cond, cond*2)
16695 case 4: // result = lea base( , cond*4)
16696 case 5: // result = lea base(cond, cond*4)
16697 case 8: // result = lea base( , cond*8)
16698 case 9: // result = lea base(cond, cond*8)
16699 isFastMultiplier = true;
16704 if (isFastMultiplier) {
16705 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16706 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16707 DAG.getConstant(CC, MVT::i8), Cond);
16708 // Zero extend the condition if needed.
16709 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16711 // Scale the condition by the difference.
16713 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16714 DAG.getConstant(Diff, Cond.getValueType()));
16716 // Add the base if non-zero.
16717 if (FalseC->getAPIntValue() != 0)
16718 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16719 SDValue(FalseC, 0));
16720 if (N->getNumValues() == 2) // Dead flag value?
16721 return DCI.CombineTo(N, Cond, SDValue());
16728 // Handle these cases:
16729 // (select (x != c), e, c) -> select (x != c), e, x),
16730 // (select (x == c), c, e) -> select (x == c), x, e)
16731 // where the c is an integer constant, and the "select" is the combination
16732 // of CMOV and CMP.
16734 // The rationale for this change is that the conditional-move from a constant
16735 // needs two instructions, however, conditional-move from a register needs
16736 // only one instruction.
16738 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16739 // some instruction-combining opportunities. This opt needs to be
16740 // postponed as late as possible.
16742 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16743 // the DCI.xxxx conditions are provided to postpone the optimization as
16744 // late as possible.
16746 ConstantSDNode *CmpAgainst = 0;
16747 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16748 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16749 !isa<ConstantSDNode>(Cond.getOperand(0))) {
16751 if (CC == X86::COND_NE &&
16752 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16753 CC = X86::GetOppositeBranchCondition(CC);
16754 std::swap(TrueOp, FalseOp);
16757 if (CC == X86::COND_E &&
16758 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16759 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16760 DAG.getConstant(CC, MVT::i8), Cond };
16761 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16762 array_lengthof(Ops));
16770 /// PerformMulCombine - Optimize a single multiply with constant into two
16771 /// in order to implement it with two cheaper instructions, e.g.
16772 /// LEA + SHL, LEA + LEA.
16773 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16774 TargetLowering::DAGCombinerInfo &DCI) {
16775 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16778 EVT VT = N->getValueType(0);
16779 if (VT != MVT::i64)
16782 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16785 uint64_t MulAmt = C->getZExtValue();
16786 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16789 uint64_t MulAmt1 = 0;
16790 uint64_t MulAmt2 = 0;
16791 if ((MulAmt % 9) == 0) {
16793 MulAmt2 = MulAmt / 9;
16794 } else if ((MulAmt % 5) == 0) {
16796 MulAmt2 = MulAmt / 5;
16797 } else if ((MulAmt % 3) == 0) {
16799 MulAmt2 = MulAmt / 3;
16802 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16805 if (isPowerOf2_64(MulAmt2) &&
16806 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16807 // If second multiplifer is pow2, issue it first. We want the multiply by
16808 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16810 std::swap(MulAmt1, MulAmt2);
16813 if (isPowerOf2_64(MulAmt1))
16814 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16815 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16817 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16818 DAG.getConstant(MulAmt1, VT));
16820 if (isPowerOf2_64(MulAmt2))
16821 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16822 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16824 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16825 DAG.getConstant(MulAmt2, VT));
16827 // Do not add new nodes to DAG combiner worklist.
16828 DCI.CombineTo(N, NewMul, false);
16833 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16834 SDValue N0 = N->getOperand(0);
16835 SDValue N1 = N->getOperand(1);
16836 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16837 EVT VT = N0.getValueType();
16839 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16840 // since the result of setcc_c is all zero's or all ones.
16841 if (VT.isInteger() && !VT.isVector() &&
16842 N1C && N0.getOpcode() == ISD::AND &&
16843 N0.getOperand(1).getOpcode() == ISD::Constant) {
16844 SDValue N00 = N0.getOperand(0);
16845 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16846 ((N00.getOpcode() == ISD::ANY_EXTEND ||
16847 N00.getOpcode() == ISD::ZERO_EXTEND) &&
16848 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16849 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16850 APInt ShAmt = N1C->getAPIntValue();
16851 Mask = Mask.shl(ShAmt);
16853 return DAG.getNode(ISD::AND, SDLoc(N), VT,
16854 N00, DAG.getConstant(Mask, VT));
16858 // Hardware support for vector shifts is sparse which makes us scalarize the
16859 // vector operations in many cases. Also, on sandybridge ADD is faster than
16861 // (shl V, 1) -> add V,V
16862 if (isSplatVector(N1.getNode())) {
16863 assert(N0.getValueType().isVector() && "Invalid vector shift type");
16864 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16865 // We shift all of the values by one. In many cases we do not have
16866 // hardware support for this operation. This is better expressed as an ADD
16868 if (N1C && (1 == N1C->getZExtValue())) {
16869 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16876 /// \brief Returns a vector of 0s if the node in input is a vector logical
16877 /// shift by a constant amount which is known to be bigger than or equal
16878 /// to the vector element size in bits.
16879 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16880 const X86Subtarget *Subtarget) {
16881 EVT VT = N->getValueType(0);
16883 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16884 (!Subtarget->hasInt256() ||
16885 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16888 SDValue Amt = N->getOperand(1);
16890 if (isSplatVector(Amt.getNode())) {
16891 SDValue SclrAmt = Amt->getOperand(0);
16892 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16893 APInt ShiftAmt = C->getAPIntValue();
16894 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16896 // SSE2/AVX2 logical shifts always return a vector of 0s
16897 // if the shift amount is bigger than or equal to
16898 // the element size. The constant shift amount will be
16899 // encoded as a 8-bit immediate.
16900 if (ShiftAmt.trunc(8).uge(MaxAmount))
16901 return getZeroVector(VT, Subtarget, DAG, DL);
16908 /// PerformShiftCombine - Combine shifts.
16909 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16910 TargetLowering::DAGCombinerInfo &DCI,
16911 const X86Subtarget *Subtarget) {
16912 if (N->getOpcode() == ISD::SHL) {
16913 SDValue V = PerformSHLCombine(N, DAG);
16914 if (V.getNode()) return V;
16917 if (N->getOpcode() != ISD::SRA) {
16918 // Try to fold this logical shift into a zero vector.
16919 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16920 if (V.getNode()) return V;
16926 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
16927 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16928 // and friends. Likewise for OR -> CMPNEQSS.
16929 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16930 TargetLowering::DAGCombinerInfo &DCI,
16931 const X86Subtarget *Subtarget) {
16934 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16935 // we're requiring SSE2 for both.
16936 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16937 SDValue N0 = N->getOperand(0);
16938 SDValue N1 = N->getOperand(1);
16939 SDValue CMP0 = N0->getOperand(1);
16940 SDValue CMP1 = N1->getOperand(1);
16943 // The SETCCs should both refer to the same CMP.
16944 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16947 SDValue CMP00 = CMP0->getOperand(0);
16948 SDValue CMP01 = CMP0->getOperand(1);
16949 EVT VT = CMP00.getValueType();
16951 if (VT == MVT::f32 || VT == MVT::f64) {
16952 bool ExpectingFlags = false;
16953 // Check for any users that want flags:
16954 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16955 !ExpectingFlags && UI != UE; ++UI)
16956 switch (UI->getOpcode()) {
16961 ExpectingFlags = true;
16963 case ISD::CopyToReg:
16964 case ISD::SIGN_EXTEND:
16965 case ISD::ZERO_EXTEND:
16966 case ISD::ANY_EXTEND:
16970 if (!ExpectingFlags) {
16971 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16972 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16974 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16975 X86::CondCode tmp = cc0;
16980 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
16981 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16982 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16983 X86ISD::NodeType NTOperator = is64BitFP ?
16984 X86ISD::FSETCCsd : X86ISD::FSETCCss;
16985 // FIXME: need symbolic constants for these magic numbers.
16986 // See X86ATTInstPrinter.cpp:printSSECC().
16987 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16988 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16989 DAG.getConstant(x86cc, MVT::i8));
16990 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16992 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16993 DAG.getConstant(1, MVT::i32));
16994 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16995 return OneBitOfTruth;
17003 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17004 /// so it can be folded inside ANDNP.
17005 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17006 EVT VT = N->getValueType(0);
17008 // Match direct AllOnes for 128 and 256-bit vectors
17009 if (ISD::isBuildVectorAllOnes(N))
17012 // Look through a bit convert.
17013 if (N->getOpcode() == ISD::BITCAST)
17014 N = N->getOperand(0).getNode();
17016 // Sometimes the operand may come from a insert_subvector building a 256-bit
17018 if (VT.is256BitVector() &&
17019 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17020 SDValue V1 = N->getOperand(0);
17021 SDValue V2 = N->getOperand(1);
17023 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17024 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17025 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17026 ISD::isBuildVectorAllOnes(V2.getNode()))
17033 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17034 // register. In most cases we actually compare or select YMM-sized registers
17035 // and mixing the two types creates horrible code. This method optimizes
17036 // some of the transition sequences.
17037 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17038 TargetLowering::DAGCombinerInfo &DCI,
17039 const X86Subtarget *Subtarget) {
17040 EVT VT = N->getValueType(0);
17041 if (!VT.is256BitVector())
17044 assert((N->getOpcode() == ISD::ANY_EXTEND ||
17045 N->getOpcode() == ISD::ZERO_EXTEND ||
17046 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17048 SDValue Narrow = N->getOperand(0);
17049 EVT NarrowVT = Narrow->getValueType(0);
17050 if (!NarrowVT.is128BitVector())
17053 if (Narrow->getOpcode() != ISD::XOR &&
17054 Narrow->getOpcode() != ISD::AND &&
17055 Narrow->getOpcode() != ISD::OR)
17058 SDValue N0 = Narrow->getOperand(0);
17059 SDValue N1 = Narrow->getOperand(1);
17062 // The Left side has to be a trunc.
17063 if (N0.getOpcode() != ISD::TRUNCATE)
17066 // The type of the truncated inputs.
17067 EVT WideVT = N0->getOperand(0)->getValueType(0);
17071 // The right side has to be a 'trunc' or a constant vector.
17072 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17073 bool RHSConst = (isSplatVector(N1.getNode()) &&
17074 isa<ConstantSDNode>(N1->getOperand(0)));
17075 if (!RHSTrunc && !RHSConst)
17078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17080 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17083 // Set N0 and N1 to hold the inputs to the new wide operation.
17084 N0 = N0->getOperand(0);
17086 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17087 N1->getOperand(0));
17088 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17089 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17090 } else if (RHSTrunc) {
17091 N1 = N1->getOperand(0);
17094 // Generate the wide operation.
17095 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17096 unsigned Opcode = N->getOpcode();
17098 case ISD::ANY_EXTEND:
17100 case ISD::ZERO_EXTEND: {
17101 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17102 APInt Mask = APInt::getAllOnesValue(InBits);
17103 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17104 return DAG.getNode(ISD::AND, DL, VT,
17105 Op, DAG.getConstant(Mask, VT));
17107 case ISD::SIGN_EXTEND:
17108 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17109 Op, DAG.getValueType(NarrowVT));
17111 llvm_unreachable("Unexpected opcode");
17115 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17116 TargetLowering::DAGCombinerInfo &DCI,
17117 const X86Subtarget *Subtarget) {
17118 EVT VT = N->getValueType(0);
17119 if (DCI.isBeforeLegalizeOps())
17122 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17126 // Create BLSI, and BLSR instructions
17127 // BLSI is X & (-X)
17128 // BLSR is X & (X-1)
17129 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
17130 SDValue N0 = N->getOperand(0);
17131 SDValue N1 = N->getOperand(1);
17134 // Check LHS for neg
17135 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17136 isZero(N0.getOperand(0)))
17137 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17139 // Check RHS for neg
17140 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17141 isZero(N1.getOperand(0)))
17142 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17144 // Check LHS for X-1
17145 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17146 isAllOnes(N0.getOperand(1)))
17147 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17149 // Check RHS for X-1
17150 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17151 isAllOnes(N1.getOperand(1)))
17152 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17157 // Want to form ANDNP nodes:
17158 // 1) In the hopes of then easily combining them with OR and AND nodes
17159 // to form PBLEND/PSIGN.
17160 // 2) To match ANDN packed intrinsics
17161 if (VT != MVT::v2i64 && VT != MVT::v4i64)
17164 SDValue N0 = N->getOperand(0);
17165 SDValue N1 = N->getOperand(1);
17168 // Check LHS for vnot
17169 if (N0.getOpcode() == ISD::XOR &&
17170 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17171 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17172 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17174 // Check RHS for vnot
17175 if (N1.getOpcode() == ISD::XOR &&
17176 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17177 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17178 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17183 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17184 TargetLowering::DAGCombinerInfo &DCI,
17185 const X86Subtarget *Subtarget) {
17186 EVT VT = N->getValueType(0);
17187 if (DCI.isBeforeLegalizeOps())
17190 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17194 SDValue N0 = N->getOperand(0);
17195 SDValue N1 = N->getOperand(1);
17197 // look for psign/blend
17198 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17199 if (!Subtarget->hasSSSE3() ||
17200 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17203 // Canonicalize pandn to RHS
17204 if (N0.getOpcode() == X86ISD::ANDNP)
17206 // or (and (m, y), (pandn m, x))
17207 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17208 SDValue Mask = N1.getOperand(0);
17209 SDValue X = N1.getOperand(1);
17211 if (N0.getOperand(0) == Mask)
17212 Y = N0.getOperand(1);
17213 if (N0.getOperand(1) == Mask)
17214 Y = N0.getOperand(0);
17216 // Check to see if the mask appeared in both the AND and ANDNP and
17220 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17221 // Look through mask bitcast.
17222 if (Mask.getOpcode() == ISD::BITCAST)
17223 Mask = Mask.getOperand(0);
17224 if (X.getOpcode() == ISD::BITCAST)
17225 X = X.getOperand(0);
17226 if (Y.getOpcode() == ISD::BITCAST)
17227 Y = Y.getOperand(0);
17229 EVT MaskVT = Mask.getValueType();
17231 // Validate that the Mask operand is a vector sra node.
17232 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17233 // there is no psrai.b
17234 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17235 unsigned SraAmt = ~0;
17236 if (Mask.getOpcode() == ISD::SRA) {
17237 SDValue Amt = Mask.getOperand(1);
17238 if (isSplatVector(Amt.getNode())) {
17239 SDValue SclrAmt = Amt->getOperand(0);
17240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17241 SraAmt = C->getZExtValue();
17243 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17244 SDValue SraC = Mask.getOperand(1);
17245 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
17247 if ((SraAmt + 1) != EltBits)
17252 // Now we know we at least have a plendvb with the mask val. See if
17253 // we can form a psignb/w/d.
17254 // psign = x.type == y.type == mask.type && y = sub(0, x);
17255 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17256 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17257 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17258 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17259 "Unsupported VT for PSIGN");
17260 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17261 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17263 // PBLENDVB only available on SSE 4.1
17264 if (!Subtarget->hasSSE41())
17267 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17269 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17270 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17271 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17272 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17273 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17277 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17280 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17281 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17283 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17285 if (!N0.hasOneUse() || !N1.hasOneUse())
17288 SDValue ShAmt0 = N0.getOperand(1);
17289 if (ShAmt0.getValueType() != MVT::i8)
17291 SDValue ShAmt1 = N1.getOperand(1);
17292 if (ShAmt1.getValueType() != MVT::i8)
17294 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17295 ShAmt0 = ShAmt0.getOperand(0);
17296 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17297 ShAmt1 = ShAmt1.getOperand(0);
17300 unsigned Opc = X86ISD::SHLD;
17301 SDValue Op0 = N0.getOperand(0);
17302 SDValue Op1 = N1.getOperand(0);
17303 if (ShAmt0.getOpcode() == ISD::SUB) {
17304 Opc = X86ISD::SHRD;
17305 std::swap(Op0, Op1);
17306 std::swap(ShAmt0, ShAmt1);
17309 unsigned Bits = VT.getSizeInBits();
17310 if (ShAmt1.getOpcode() == ISD::SUB) {
17311 SDValue Sum = ShAmt1.getOperand(0);
17312 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17313 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17314 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17315 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17316 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17317 return DAG.getNode(Opc, DL, VT,
17319 DAG.getNode(ISD::TRUNCATE, DL,
17322 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17323 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17325 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17326 return DAG.getNode(Opc, DL, VT,
17327 N0.getOperand(0), N1.getOperand(0),
17328 DAG.getNode(ISD::TRUNCATE, DL,
17335 // Generate NEG and CMOV for integer abs.
17336 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17337 EVT VT = N->getValueType(0);
17339 // Since X86 does not have CMOV for 8-bit integer, we don't convert
17340 // 8-bit integer abs to NEG and CMOV.
17341 if (VT.isInteger() && VT.getSizeInBits() == 8)
17344 SDValue N0 = N->getOperand(0);
17345 SDValue N1 = N->getOperand(1);
17348 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17349 // and change it to SUB and CMOV.
17350 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17351 N0.getOpcode() == ISD::ADD &&
17352 N0.getOperand(1) == N1 &&
17353 N1.getOpcode() == ISD::SRA &&
17354 N1.getOperand(0) == N0.getOperand(0))
17355 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17356 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17357 // Generate SUB & CMOV.
17358 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17359 DAG.getConstant(0, VT), N0.getOperand(0));
17361 SDValue Ops[] = { N0.getOperand(0), Neg,
17362 DAG.getConstant(X86::COND_GE, MVT::i8),
17363 SDValue(Neg.getNode(), 1) };
17364 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17365 Ops, array_lengthof(Ops));
17370 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17371 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17372 TargetLowering::DAGCombinerInfo &DCI,
17373 const X86Subtarget *Subtarget) {
17374 EVT VT = N->getValueType(0);
17375 if (DCI.isBeforeLegalizeOps())
17378 if (Subtarget->hasCMov()) {
17379 SDValue RV = performIntegerAbsCombine(N, DAG);
17384 // Try forming BMI if it is available.
17385 if (!Subtarget->hasBMI())
17388 if (VT != MVT::i32 && VT != MVT::i64)
17391 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17393 // Create BLSMSK instructions by finding X ^ (X-1)
17394 SDValue N0 = N->getOperand(0);
17395 SDValue N1 = N->getOperand(1);
17398 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17399 isAllOnes(N0.getOperand(1)))
17400 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17402 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17403 isAllOnes(N1.getOperand(1)))
17404 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17409 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17410 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17411 TargetLowering::DAGCombinerInfo &DCI,
17412 const X86Subtarget *Subtarget) {
17413 LoadSDNode *Ld = cast<LoadSDNode>(N);
17414 EVT RegVT = Ld->getValueType(0);
17415 EVT MemVT = Ld->getMemoryVT();
17417 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17418 unsigned RegSz = RegVT.getSizeInBits();
17420 // On Sandybridge unaligned 256bit loads are inefficient.
17421 ISD::LoadExtType Ext = Ld->getExtensionType();
17422 unsigned Alignment = Ld->getAlignment();
17423 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17424 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17425 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17426 unsigned NumElems = RegVT.getVectorNumElements();
17430 SDValue Ptr = Ld->getBasePtr();
17431 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17433 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17435 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17436 Ld->getPointerInfo(), Ld->isVolatile(),
17437 Ld->isNonTemporal(), Ld->isInvariant(),
17439 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17440 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17441 Ld->getPointerInfo(), Ld->isVolatile(),
17442 Ld->isNonTemporal(), Ld->isInvariant(),
17443 std::min(16U, Alignment));
17444 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17446 Load2.getValue(1));
17448 SDValue NewVec = DAG.getUNDEF(RegVT);
17449 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17450 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17451 return DCI.CombineTo(N, NewVec, TF, true);
17454 // If this is a vector EXT Load then attempt to optimize it using a
17455 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17456 // expansion is still better than scalar code.
17457 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17458 // emit a shuffle and a arithmetic shift.
17459 // TODO: It is possible to support ZExt by zeroing the undef values
17460 // during the shuffle phase or after the shuffle.
17461 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17462 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17463 assert(MemVT != RegVT && "Cannot extend to the same type");
17464 assert(MemVT.isVector() && "Must load a vector from memory");
17466 unsigned NumElems = RegVT.getVectorNumElements();
17467 unsigned MemSz = MemVT.getSizeInBits();
17468 assert(RegSz > MemSz && "Register size must be greater than the mem size");
17470 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17473 // All sizes must be a power of two.
17474 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17477 // Attempt to load the original value using scalar loads.
17478 // Find the largest scalar type that divides the total loaded size.
17479 MVT SclrLoadTy = MVT::i8;
17480 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17481 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17482 MVT Tp = (MVT::SimpleValueType)tp;
17483 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17488 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17489 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17491 SclrLoadTy = MVT::f64;
17493 // Calculate the number of scalar loads that we need to perform
17494 // in order to load our vector from memory.
17495 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17496 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17499 unsigned loadRegZize = RegSz;
17500 if (Ext == ISD::SEXTLOAD && RegSz == 256)
17503 // Represent our vector as a sequence of elements which are the
17504 // largest scalar that we can load.
17505 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17506 loadRegZize/SclrLoadTy.getSizeInBits());
17508 // Represent the data using the same element type that is stored in
17509 // memory. In practice, we ''widen'' MemVT.
17511 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17512 loadRegZize/MemVT.getScalarType().getSizeInBits());
17514 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17515 "Invalid vector type");
17517 // We can't shuffle using an illegal type.
17518 if (!TLI.isTypeLegal(WideVecVT))
17521 SmallVector<SDValue, 8> Chains;
17522 SDValue Ptr = Ld->getBasePtr();
17523 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17524 TLI.getPointerTy());
17525 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17527 for (unsigned i = 0; i < NumLoads; ++i) {
17528 // Perform a single load.
17529 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17530 Ptr, Ld->getPointerInfo(),
17531 Ld->isVolatile(), Ld->isNonTemporal(),
17532 Ld->isInvariant(), Ld->getAlignment());
17533 Chains.push_back(ScalarLoad.getValue(1));
17534 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17535 // another round of DAGCombining.
17537 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17539 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17540 ScalarLoad, DAG.getIntPtrConstant(i));
17542 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17545 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17548 // Bitcast the loaded value to a vector of the original element type, in
17549 // the size of the target vector type.
17550 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17551 unsigned SizeRatio = RegSz/MemSz;
17553 if (Ext == ISD::SEXTLOAD) {
17554 // If we have SSE4.1 we can directly emit a VSEXT node.
17555 if (Subtarget->hasSSE41()) {
17556 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17557 return DCI.CombineTo(N, Sext, TF, true);
17560 // Otherwise we'll shuffle the small elements in the high bits of the
17561 // larger type and perform an arithmetic shift. If the shift is not legal
17562 // it's better to scalarize.
17563 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17566 // Redistribute the loaded elements into the different locations.
17567 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17568 for (unsigned i = 0; i != NumElems; ++i)
17569 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17571 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17572 DAG.getUNDEF(WideVecVT),
17575 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17577 // Build the arithmetic shift.
17578 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17579 MemVT.getVectorElementType().getSizeInBits();
17580 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17581 DAG.getConstant(Amt, RegVT));
17583 return DCI.CombineTo(N, Shuff, TF, true);
17586 // Redistribute the loaded elements into the different locations.
17587 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17588 for (unsigned i = 0; i != NumElems; ++i)
17589 ShuffleVec[i*SizeRatio] = i;
17591 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17592 DAG.getUNDEF(WideVecVT),
17595 // Bitcast to the requested type.
17596 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17597 // Replace the original load with the new sequence
17598 // and return the new chain.
17599 return DCI.CombineTo(N, Shuff, TF, true);
17605 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17606 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17607 const X86Subtarget *Subtarget) {
17608 StoreSDNode *St = cast<StoreSDNode>(N);
17609 EVT VT = St->getValue().getValueType();
17610 EVT StVT = St->getMemoryVT();
17612 SDValue StoredVal = St->getOperand(1);
17613 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17615 // If we are saving a concatenation of two XMM registers, perform two stores.
17616 // On Sandy Bridge, 256-bit memory operations are executed by two
17617 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17618 // memory operation.
17619 unsigned Alignment = St->getAlignment();
17620 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17621 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17622 StVT == VT && !IsAligned) {
17623 unsigned NumElems = VT.getVectorNumElements();
17627 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17628 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17630 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17631 SDValue Ptr0 = St->getBasePtr();
17632 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17634 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17635 St->getPointerInfo(), St->isVolatile(),
17636 St->isNonTemporal(), Alignment);
17637 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17638 St->getPointerInfo(), St->isVolatile(),
17639 St->isNonTemporal(),
17640 std::min(16U, Alignment));
17641 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17644 // Optimize trunc store (of multiple scalars) to shuffle and store.
17645 // First, pack all of the elements in one place. Next, store to memory
17646 // in fewer chunks.
17647 if (St->isTruncatingStore() && VT.isVector()) {
17648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17649 unsigned NumElems = VT.getVectorNumElements();
17650 assert(StVT != VT && "Cannot truncate to the same type");
17651 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17652 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17654 // From, To sizes and ElemCount must be pow of two
17655 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17656 // We are going to use the original vector elt for storing.
17657 // Accumulated smaller vector elements must be a multiple of the store size.
17658 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17660 unsigned SizeRatio = FromSz / ToSz;
17662 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17664 // Create a type on which we perform the shuffle
17665 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17666 StVT.getScalarType(), NumElems*SizeRatio);
17668 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17670 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17671 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17672 for (unsigned i = 0; i != NumElems; ++i)
17673 ShuffleVec[i] = i * SizeRatio;
17675 // Can't shuffle using an illegal type.
17676 if (!TLI.isTypeLegal(WideVecVT))
17679 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17680 DAG.getUNDEF(WideVecVT),
17682 // At this point all of the data is stored at the bottom of the
17683 // register. We now need to save it to mem.
17685 // Find the largest store unit
17686 MVT StoreType = MVT::i8;
17687 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17688 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17689 MVT Tp = (MVT::SimpleValueType)tp;
17690 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17694 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17695 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17696 (64 <= NumElems * ToSz))
17697 StoreType = MVT::f64;
17699 // Bitcast the original vector into a vector of store-size units
17700 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17701 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17702 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17703 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17704 SmallVector<SDValue, 8> Chains;
17705 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17706 TLI.getPointerTy());
17707 SDValue Ptr = St->getBasePtr();
17709 // Perform one or more big stores into memory.
17710 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17711 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17712 StoreType, ShuffWide,
17713 DAG.getIntPtrConstant(i));
17714 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17715 St->getPointerInfo(), St->isVolatile(),
17716 St->isNonTemporal(), St->getAlignment());
17717 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17718 Chains.push_back(Ch);
17721 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17725 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
17726 // the FP state in cases where an emms may be missing.
17727 // A preferable solution to the general problem is to figure out the right
17728 // places to insert EMMS. This qualifies as a quick hack.
17730 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17731 if (VT.getSizeInBits() != 64)
17734 const Function *F = DAG.getMachineFunction().getFunction();
17735 bool NoImplicitFloatOps = F->getAttributes().
17736 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17737 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17738 && Subtarget->hasSSE2();
17739 if ((VT.isVector() ||
17740 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17741 isa<LoadSDNode>(St->getValue()) &&
17742 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17743 St->getChain().hasOneUse() && !St->isVolatile()) {
17744 SDNode* LdVal = St->getValue().getNode();
17745 LoadSDNode *Ld = 0;
17746 int TokenFactorIndex = -1;
17747 SmallVector<SDValue, 8> Ops;
17748 SDNode* ChainVal = St->getChain().getNode();
17749 // Must be a store of a load. We currently handle two cases: the load
17750 // is a direct child, and it's under an intervening TokenFactor. It is
17751 // possible to dig deeper under nested TokenFactors.
17752 if (ChainVal == LdVal)
17753 Ld = cast<LoadSDNode>(St->getChain());
17754 else if (St->getValue().hasOneUse() &&
17755 ChainVal->getOpcode() == ISD::TokenFactor) {
17756 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17757 if (ChainVal->getOperand(i).getNode() == LdVal) {
17758 TokenFactorIndex = i;
17759 Ld = cast<LoadSDNode>(St->getValue());
17761 Ops.push_back(ChainVal->getOperand(i));
17765 if (!Ld || !ISD::isNormalLoad(Ld))
17768 // If this is not the MMX case, i.e. we are just turning i64 load/store
17769 // into f64 load/store, avoid the transformation if there are multiple
17770 // uses of the loaded value.
17771 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17776 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17777 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17779 if (Subtarget->is64Bit() || F64IsLegal) {
17780 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17781 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17782 Ld->getPointerInfo(), Ld->isVolatile(),
17783 Ld->isNonTemporal(), Ld->isInvariant(),
17784 Ld->getAlignment());
17785 SDValue NewChain = NewLd.getValue(1);
17786 if (TokenFactorIndex != -1) {
17787 Ops.push_back(NewChain);
17788 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17791 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17792 St->getPointerInfo(),
17793 St->isVolatile(), St->isNonTemporal(),
17794 St->getAlignment());
17797 // Otherwise, lower to two pairs of 32-bit loads / stores.
17798 SDValue LoAddr = Ld->getBasePtr();
17799 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17800 DAG.getConstant(4, MVT::i32));
17802 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17803 Ld->getPointerInfo(),
17804 Ld->isVolatile(), Ld->isNonTemporal(),
17805 Ld->isInvariant(), Ld->getAlignment());
17806 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17807 Ld->getPointerInfo().getWithOffset(4),
17808 Ld->isVolatile(), Ld->isNonTemporal(),
17810 MinAlign(Ld->getAlignment(), 4));
17812 SDValue NewChain = LoLd.getValue(1);
17813 if (TokenFactorIndex != -1) {
17814 Ops.push_back(LoLd);
17815 Ops.push_back(HiLd);
17816 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17820 LoAddr = St->getBasePtr();
17821 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17822 DAG.getConstant(4, MVT::i32));
17824 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17825 St->getPointerInfo(),
17826 St->isVolatile(), St->isNonTemporal(),
17827 St->getAlignment());
17828 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17829 St->getPointerInfo().getWithOffset(4),
17831 St->isNonTemporal(),
17832 MinAlign(St->getAlignment(), 4));
17833 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17838 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17839 /// and return the operands for the horizontal operation in LHS and RHS. A
17840 /// horizontal operation performs the binary operation on successive elements
17841 /// of its first operand, then on successive elements of its second operand,
17842 /// returning the resulting values in a vector. For example, if
17843 /// A = < float a0, float a1, float a2, float a3 >
17845 /// B = < float b0, float b1, float b2, float b3 >
17846 /// then the result of doing a horizontal operation on A and B is
17847 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17848 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17849 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17850 /// set to A, RHS to B, and the routine returns 'true'.
17851 /// Note that the binary operation should have the property that if one of the
17852 /// operands is UNDEF then the result is UNDEF.
17853 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17854 // Look for the following pattern: if
17855 // A = < float a0, float a1, float a2, float a3 >
17856 // B = < float b0, float b1, float b2, float b3 >
17858 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17859 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17860 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17861 // which is A horizontal-op B.
17863 // At least one of the operands should be a vector shuffle.
17864 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17865 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17868 MVT VT = LHS.getSimpleValueType();
17870 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17871 "Unsupported vector type for horizontal add/sub");
17873 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17874 // operate independently on 128-bit lanes.
17875 unsigned NumElts = VT.getVectorNumElements();
17876 unsigned NumLanes = VT.getSizeInBits()/128;
17877 unsigned NumLaneElts = NumElts / NumLanes;
17878 assert((NumLaneElts % 2 == 0) &&
17879 "Vector type should have an even number of elements in each lane");
17880 unsigned HalfLaneElts = NumLaneElts/2;
17882 // View LHS in the form
17883 // LHS = VECTOR_SHUFFLE A, B, LMask
17884 // If LHS is not a shuffle then pretend it is the shuffle
17885 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17886 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17889 SmallVector<int, 16> LMask(NumElts);
17890 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17891 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17892 A = LHS.getOperand(0);
17893 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17894 B = LHS.getOperand(1);
17895 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17896 std::copy(Mask.begin(), Mask.end(), LMask.begin());
17898 if (LHS.getOpcode() != ISD::UNDEF)
17900 for (unsigned i = 0; i != NumElts; ++i)
17904 // Likewise, view RHS in the form
17905 // RHS = VECTOR_SHUFFLE C, D, RMask
17907 SmallVector<int, 16> RMask(NumElts);
17908 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17909 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17910 C = RHS.getOperand(0);
17911 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17912 D = RHS.getOperand(1);
17913 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17914 std::copy(Mask.begin(), Mask.end(), RMask.begin());
17916 if (RHS.getOpcode() != ISD::UNDEF)
17918 for (unsigned i = 0; i != NumElts; ++i)
17922 // Check that the shuffles are both shuffling the same vectors.
17923 if (!(A == C && B == D) && !(A == D && B == C))
17926 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17927 if (!A.getNode() && !B.getNode())
17930 // If A and B occur in reverse order in RHS, then "swap" them (which means
17931 // rewriting the mask).
17933 CommuteVectorShuffleMask(RMask, NumElts);
17935 // At this point LHS and RHS are equivalent to
17936 // LHS = VECTOR_SHUFFLE A, B, LMask
17937 // RHS = VECTOR_SHUFFLE A, B, RMask
17938 // Check that the masks correspond to performing a horizontal operation.
17939 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
17940 for (unsigned i = 0; i != NumLaneElts; ++i) {
17941 int LIdx = LMask[i+l], RIdx = RMask[i+l];
17943 // Ignore any UNDEF components.
17944 if (LIdx < 0 || RIdx < 0 ||
17945 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17946 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17949 // Check that successive elements are being operated on. If not, this is
17950 // not a horizontal operation.
17951 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
17952 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
17953 if (!(LIdx == Index && RIdx == Index + 1) &&
17954 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17959 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17960 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17964 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17965 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17966 const X86Subtarget *Subtarget) {
17967 EVT VT = N->getValueType(0);
17968 SDValue LHS = N->getOperand(0);
17969 SDValue RHS = N->getOperand(1);
17971 // Try to synthesize horizontal adds from adds of shuffles.
17972 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17973 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17974 isHorizontalBinOp(LHS, RHS, true))
17975 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17979 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17980 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17981 const X86Subtarget *Subtarget) {
17982 EVT VT = N->getValueType(0);
17983 SDValue LHS = N->getOperand(0);
17984 SDValue RHS = N->getOperand(1);
17986 // Try to synthesize horizontal subs from subs of shuffles.
17987 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17988 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17989 isHorizontalBinOp(LHS, RHS, false))
17990 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17994 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17995 /// X86ISD::FXOR nodes.
17996 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17997 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17998 // F[X]OR(0.0, x) -> x
17999 // F[X]OR(x, 0.0) -> x
18000 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18001 if (C->getValueAPF().isPosZero())
18002 return N->getOperand(1);
18003 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18004 if (C->getValueAPF().isPosZero())
18005 return N->getOperand(0);
18009 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18010 /// X86ISD::FMAX nodes.
18011 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18012 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18014 // Only perform optimizations if UnsafeMath is used.
18015 if (!DAG.getTarget().Options.UnsafeFPMath)
18018 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18019 // into FMINC and FMAXC, which are Commutative operations.
18020 unsigned NewOp = 0;
18021 switch (N->getOpcode()) {
18022 default: llvm_unreachable("unknown opcode");
18023 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
18024 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
18027 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18028 N->getOperand(0), N->getOperand(1));
18031 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18032 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18033 // FAND(0.0, x) -> 0.0
18034 // FAND(x, 0.0) -> 0.0
18035 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18036 if (C->getValueAPF().isPosZero())
18037 return N->getOperand(0);
18038 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18039 if (C->getValueAPF().isPosZero())
18040 return N->getOperand(1);
18044 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18045 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18046 // FANDN(x, 0.0) -> 0.0
18047 // FANDN(0.0, x) -> x
18048 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18049 if (C->getValueAPF().isPosZero())
18050 return N->getOperand(1);
18051 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18052 if (C->getValueAPF().isPosZero())
18053 return N->getOperand(1);
18057 static SDValue PerformBTCombine(SDNode *N,
18059 TargetLowering::DAGCombinerInfo &DCI) {
18060 // BT ignores high bits in the bit index operand.
18061 SDValue Op1 = N->getOperand(1);
18062 if (Op1.hasOneUse()) {
18063 unsigned BitWidth = Op1.getValueSizeInBits();
18064 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18065 APInt KnownZero, KnownOne;
18066 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18067 !DCI.isBeforeLegalizeOps());
18068 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18069 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18070 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18071 DCI.CommitTargetLoweringOpt(TLO);
18076 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18077 SDValue Op = N->getOperand(0);
18078 if (Op.getOpcode() == ISD::BITCAST)
18079 Op = Op.getOperand(0);
18080 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18081 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18082 VT.getVectorElementType().getSizeInBits() ==
18083 OpVT.getVectorElementType().getSizeInBits()) {
18084 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18089 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18090 const X86Subtarget *Subtarget) {
18091 EVT VT = N->getValueType(0);
18092 if (!VT.isVector())
18095 SDValue N0 = N->getOperand(0);
18096 SDValue N1 = N->getOperand(1);
18097 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18100 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18101 // both SSE and AVX2 since there is no sign-extended shift right
18102 // operation on a vector with 64-bit elements.
18103 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18104 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18105 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18106 N0.getOpcode() == ISD::SIGN_EXTEND)) {
18107 SDValue N00 = N0.getOperand(0);
18109 // EXTLOAD has a better solution on AVX2,
18110 // it may be replaced with X86ISD::VSEXT node.
18111 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18112 if (!ISD::isNormalLoad(N00.getNode()))
18115 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18116 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18118 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18124 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18125 TargetLowering::DAGCombinerInfo &DCI,
18126 const X86Subtarget *Subtarget) {
18127 if (!DCI.isBeforeLegalizeOps())
18130 if (!Subtarget->hasFp256())
18133 EVT VT = N->getValueType(0);
18134 if (VT.isVector() && VT.getSizeInBits() == 256) {
18135 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18143 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18144 const X86Subtarget* Subtarget) {
18146 EVT VT = N->getValueType(0);
18148 // Let legalize expand this if it isn't a legal type yet.
18149 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18152 EVT ScalarVT = VT.getScalarType();
18153 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18154 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18157 SDValue A = N->getOperand(0);
18158 SDValue B = N->getOperand(1);
18159 SDValue C = N->getOperand(2);
18161 bool NegA = (A.getOpcode() == ISD::FNEG);
18162 bool NegB = (B.getOpcode() == ISD::FNEG);
18163 bool NegC = (C.getOpcode() == ISD::FNEG);
18165 // Negative multiplication when NegA xor NegB
18166 bool NegMul = (NegA != NegB);
18168 A = A.getOperand(0);
18170 B = B.getOperand(0);
18172 C = C.getOperand(0);
18176 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18178 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18180 return DAG.getNode(Opcode, dl, VT, A, B, C);
18183 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18184 TargetLowering::DAGCombinerInfo &DCI,
18185 const X86Subtarget *Subtarget) {
18186 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
18187 // (and (i32 x86isd::setcc_carry), 1)
18188 // This eliminates the zext. This transformation is necessary because
18189 // ISD::SETCC is always legalized to i8.
18191 SDValue N0 = N->getOperand(0);
18192 EVT VT = N->getValueType(0);
18194 if (N0.getOpcode() == ISD::AND &&
18196 N0.getOperand(0).hasOneUse()) {
18197 SDValue N00 = N0.getOperand(0);
18198 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18199 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18200 if (!C || C->getZExtValue() != 1)
18202 return DAG.getNode(ISD::AND, dl, VT,
18203 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18204 N00.getOperand(0), N00.getOperand(1)),
18205 DAG.getConstant(1, VT));
18209 if (VT.is256BitVector()) {
18210 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18218 // Optimize x == -y --> x+y == 0
18219 // x != -y --> x+y != 0
18220 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18221 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18222 SDValue LHS = N->getOperand(0);
18223 SDValue RHS = N->getOperand(1);
18225 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18226 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18227 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18228 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18229 LHS.getValueType(), RHS, LHS.getOperand(1));
18230 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18231 addV, DAG.getConstant(0, addV.getValueType()), CC);
18233 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18235 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18236 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18237 RHS.getValueType(), LHS, RHS.getOperand(1));
18238 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18239 addV, DAG.getConstant(0, addV.getValueType()), CC);
18244 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18245 // as "sbb reg,reg", since it can be extended without zext and produces
18246 // an all-ones bit which is more useful than 0/1 in some cases.
18247 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18248 return DAG.getNode(ISD::AND, DL, MVT::i8,
18249 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18250 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18251 DAG.getConstant(1, MVT::i8));
18254 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18255 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18256 TargetLowering::DAGCombinerInfo &DCI,
18257 const X86Subtarget *Subtarget) {
18259 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18260 SDValue EFLAGS = N->getOperand(1);
18262 if (CC == X86::COND_A) {
18263 // Try to convert COND_A into COND_B in an attempt to facilitate
18264 // materializing "setb reg".
18266 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18267 // cannot take an immediate as its first operand.
18269 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18270 EFLAGS.getValueType().isInteger() &&
18271 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18272 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18273 EFLAGS.getNode()->getVTList(),
18274 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18275 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18276 return MaterializeSETB(DL, NewEFLAGS, DAG);
18280 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18281 // a zext and produces an all-ones bit which is more useful than 0/1 in some
18283 if (CC == X86::COND_B)
18284 return MaterializeSETB(DL, EFLAGS, DAG);
18288 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18289 if (Flags.getNode()) {
18290 SDValue Cond = DAG.getConstant(CC, MVT::i8);
18291 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18297 // Optimize branch condition evaluation.
18299 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18300 TargetLowering::DAGCombinerInfo &DCI,
18301 const X86Subtarget *Subtarget) {
18303 SDValue Chain = N->getOperand(0);
18304 SDValue Dest = N->getOperand(1);
18305 SDValue EFLAGS = N->getOperand(3);
18306 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18310 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18311 if (Flags.getNode()) {
18312 SDValue Cond = DAG.getConstant(CC, MVT::i8);
18313 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18320 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18321 const X86TargetLowering *XTLI) {
18322 SDValue Op0 = N->getOperand(0);
18323 EVT InVT = Op0->getValueType(0);
18325 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18326 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18328 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18329 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18330 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18333 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18334 // a 32-bit target where SSE doesn't support i64->FP operations.
18335 if (Op0.getOpcode() == ISD::LOAD) {
18336 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18337 EVT VT = Ld->getValueType(0);
18338 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18339 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18340 !XTLI->getSubtarget()->is64Bit() &&
18341 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18342 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18343 Ld->getChain(), Op0, DAG);
18344 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18351 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18352 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18353 X86TargetLowering::DAGCombinerInfo &DCI) {
18354 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18355 // the result is either zero or one (depending on the input carry bit).
18356 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18357 if (X86::isZeroNode(N->getOperand(0)) &&
18358 X86::isZeroNode(N->getOperand(1)) &&
18359 // We don't have a good way to replace an EFLAGS use, so only do this when
18361 SDValue(N, 1).use_empty()) {
18363 EVT VT = N->getValueType(0);
18364 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18365 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18366 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18367 DAG.getConstant(X86::COND_B,MVT::i8),
18369 DAG.getConstant(1, VT));
18370 return DCI.CombineTo(N, Res1, CarryOut);
18376 // fold (add Y, (sete X, 0)) -> adc 0, Y
18377 // (add Y, (setne X, 0)) -> sbb -1, Y
18378 // (sub (sete X, 0), Y) -> sbb 0, Y
18379 // (sub (setne X, 0), Y) -> adc -1, Y
18380 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18383 // Look through ZExts.
18384 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18385 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18388 SDValue SetCC = Ext.getOperand(0);
18389 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18392 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18393 if (CC != X86::COND_E && CC != X86::COND_NE)
18396 SDValue Cmp = SetCC.getOperand(1);
18397 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18398 !X86::isZeroNode(Cmp.getOperand(1)) ||
18399 !Cmp.getOperand(0).getValueType().isInteger())
18402 SDValue CmpOp0 = Cmp.getOperand(0);
18403 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18404 DAG.getConstant(1, CmpOp0.getValueType()));
18406 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18407 if (CC == X86::COND_NE)
18408 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18409 DL, OtherVal.getValueType(), OtherVal,
18410 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18411 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18412 DL, OtherVal.getValueType(), OtherVal,
18413 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18416 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18417 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18418 const X86Subtarget *Subtarget) {
18419 EVT VT = N->getValueType(0);
18420 SDValue Op0 = N->getOperand(0);
18421 SDValue Op1 = N->getOperand(1);
18423 // Try to synthesize horizontal adds from adds of shuffles.
18424 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18425 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18426 isHorizontalBinOp(Op0, Op1, true))
18427 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18429 return OptimizeConditionalInDecrement(N, DAG);
18432 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18433 const X86Subtarget *Subtarget) {
18434 SDValue Op0 = N->getOperand(0);
18435 SDValue Op1 = N->getOperand(1);
18437 // X86 can't encode an immediate LHS of a sub. See if we can push the
18438 // negation into a preceding instruction.
18439 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18440 // If the RHS of the sub is a XOR with one use and a constant, invert the
18441 // immediate. Then add one to the LHS of the sub so we can turn
18442 // X-Y -> X+~Y+1, saving one register.
18443 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18444 isa<ConstantSDNode>(Op1.getOperand(1))) {
18445 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18446 EVT VT = Op0.getValueType();
18447 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18449 DAG.getConstant(~XorC, VT));
18450 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18451 DAG.getConstant(C->getAPIntValue()+1, VT));
18455 // Try to synthesize horizontal adds from adds of shuffles.
18456 EVT VT = N->getValueType(0);
18457 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18458 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18459 isHorizontalBinOp(Op0, Op1, true))
18460 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18462 return OptimizeConditionalInDecrement(N, DAG);
18465 /// performVZEXTCombine - Performs build vector combines
18466 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18467 TargetLowering::DAGCombinerInfo &DCI,
18468 const X86Subtarget *Subtarget) {
18469 // (vzext (bitcast (vzext (x)) -> (vzext x)
18470 SDValue In = N->getOperand(0);
18471 while (In.getOpcode() == ISD::BITCAST)
18472 In = In.getOperand(0);
18474 if (In.getOpcode() != X86ISD::VZEXT)
18477 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18481 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18482 DAGCombinerInfo &DCI) const {
18483 SelectionDAG &DAG = DCI.DAG;
18484 switch (N->getOpcode()) {
18486 case ISD::EXTRACT_VECTOR_ELT:
18487 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18489 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18490 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18491 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
18492 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
18493 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
18494 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
18497 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
18498 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
18499 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
18500 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
18501 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
18502 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
18503 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
18504 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
18505 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
18507 case X86ISD::FOR: return PerformFORCombine(N, DAG);
18509 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
18510 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
18511 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
18512 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
18513 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
18514 case ISD::ANY_EXTEND:
18515 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
18516 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
18517 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18518 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18519 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
18520 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18521 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18522 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
18523 case X86ISD::SHUFP: // Handle all target specific shuffles
18524 case X86ISD::PALIGNR:
18525 case X86ISD::UNPCKH:
18526 case X86ISD::UNPCKL:
18527 case X86ISD::MOVHLPS:
18528 case X86ISD::MOVLHPS:
18529 case X86ISD::PSHUFD:
18530 case X86ISD::PSHUFHW:
18531 case X86ISD::PSHUFLW:
18532 case X86ISD::MOVSS:
18533 case X86ISD::MOVSD:
18534 case X86ISD::VPERMILP:
18535 case X86ISD::VPERM2X128:
18536 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18537 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
18543 /// isTypeDesirableForOp - Return true if the target has native support for
18544 /// the specified value type and it is 'desirable' to use the type for the
18545 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18546 /// instruction encodings are longer and some i16 instructions are slow.
18547 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18548 if (!isTypeLegal(VT))
18550 if (VT != MVT::i16)
18557 case ISD::SIGN_EXTEND:
18558 case ISD::ZERO_EXTEND:
18559 case ISD::ANY_EXTEND:
18572 /// IsDesirableToPromoteOp - This method query the target whether it is
18573 /// beneficial for dag combiner to promote the specified node. If true, it
18574 /// should return the desired promotion type by reference.
18575 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18576 EVT VT = Op.getValueType();
18577 if (VT != MVT::i16)
18580 bool Promote = false;
18581 bool Commute = false;
18582 switch (Op.getOpcode()) {
18585 LoadSDNode *LD = cast<LoadSDNode>(Op);
18586 // If the non-extending load has a single use and it's not live out, then it
18587 // might be folded.
18588 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18589 Op.hasOneUse()*/) {
18590 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18591 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18592 // The only case where we'd want to promote LOAD (rather then it being
18593 // promoted as an operand is when it's only use is liveout.
18594 if (UI->getOpcode() != ISD::CopyToReg)
18601 case ISD::SIGN_EXTEND:
18602 case ISD::ZERO_EXTEND:
18603 case ISD::ANY_EXTEND:
18608 SDValue N0 = Op.getOperand(0);
18609 // Look out for (store (shl (load), x)).
18610 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18623 SDValue N0 = Op.getOperand(0);
18624 SDValue N1 = Op.getOperand(1);
18625 if (!Commute && MayFoldLoad(N1))
18627 // Avoid disabling potential load folding opportunities.
18628 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18630 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18640 //===----------------------------------------------------------------------===//
18641 // X86 Inline Assembly Support
18642 //===----------------------------------------------------------------------===//
18645 // Helper to match a string separated by whitespace.
18646 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18647 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18649 for (unsigned i = 0, e = args.size(); i != e; ++i) {
18650 StringRef piece(*args[i]);
18651 if (!s.startswith(piece)) // Check if the piece matches.
18654 s = s.substr(piece.size());
18655 StringRef::size_type pos = s.find_first_not_of(" \t");
18656 if (pos == 0) // We matched a prefix.
18664 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18667 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18668 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18670 std::string AsmStr = IA->getAsmString();
18672 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18673 if (!Ty || Ty->getBitWidth() % 16 != 0)
18676 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18677 SmallVector<StringRef, 4> AsmPieces;
18678 SplitString(AsmStr, AsmPieces, ";\n");
18680 switch (AsmPieces.size()) {
18681 default: return false;
18683 // FIXME: this should verify that we are targeting a 486 or better. If not,
18684 // we will turn this bswap into something that will be lowered to logical
18685 // ops instead of emitting the bswap asm. For now, we don't support 486 or
18686 // lower so don't worry about this.
18688 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18689 matchAsm(AsmPieces[0], "bswapl", "$0") ||
18690 matchAsm(AsmPieces[0], "bswapq", "$0") ||
18691 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18692 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18693 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18694 // No need to check constraints, nothing other than the equivalent of
18695 // "=r,0" would be valid here.
18696 return IntrinsicLowering::LowerToByteSwap(CI);
18699 // rorw $$8, ${0:w} --> llvm.bswap.i16
18700 if (CI->getType()->isIntegerTy(16) &&
18701 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18702 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18703 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18705 const std::string &ConstraintsStr = IA->getConstraintString();
18706 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18707 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18708 if (AsmPieces.size() == 4 &&
18709 AsmPieces[0] == "~{cc}" &&
18710 AsmPieces[1] == "~{dirflag}" &&
18711 AsmPieces[2] == "~{flags}" &&
18712 AsmPieces[3] == "~{fpsr}")
18713 return IntrinsicLowering::LowerToByteSwap(CI);
18717 if (CI->getType()->isIntegerTy(32) &&
18718 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18719 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18720 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18721 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18723 const std::string &ConstraintsStr = IA->getConstraintString();
18724 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18725 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18726 if (AsmPieces.size() == 4 &&
18727 AsmPieces[0] == "~{cc}" &&
18728 AsmPieces[1] == "~{dirflag}" &&
18729 AsmPieces[2] == "~{flags}" &&
18730 AsmPieces[3] == "~{fpsr}")
18731 return IntrinsicLowering::LowerToByteSwap(CI);
18734 if (CI->getType()->isIntegerTy(64)) {
18735 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18736 if (Constraints.size() >= 2 &&
18737 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18738 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18739 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
18740 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18741 matchAsm(AsmPieces[1], "bswap", "%edx") &&
18742 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18743 return IntrinsicLowering::LowerToByteSwap(CI);
18751 /// getConstraintType - Given a constraint letter, return the type of
18752 /// constraint it is for this target.
18753 X86TargetLowering::ConstraintType
18754 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18755 if (Constraint.size() == 1) {
18756 switch (Constraint[0]) {
18767 return C_RegisterClass;
18791 return TargetLowering::getConstraintType(Constraint);
18794 /// Examine constraint type and operand type and determine a weight value.
18795 /// This object must already have been set up with the operand type
18796 /// and the current alternative constraint selected.
18797 TargetLowering::ConstraintWeight
18798 X86TargetLowering::getSingleConstraintMatchWeight(
18799 AsmOperandInfo &info, const char *constraint) const {
18800 ConstraintWeight weight = CW_Invalid;
18801 Value *CallOperandVal = info.CallOperandVal;
18802 // If we don't have a value, we can't do a match,
18803 // but allow it at the lowest weight.
18804 if (CallOperandVal == NULL)
18806 Type *type = CallOperandVal->getType();
18807 // Look at the constraint type.
18808 switch (*constraint) {
18810 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18821 if (CallOperandVal->getType()->isIntegerTy())
18822 weight = CW_SpecificReg;
18827 if (type->isFloatingPointTy())
18828 weight = CW_SpecificReg;
18831 if (type->isX86_MMXTy() && Subtarget->hasMMX())
18832 weight = CW_SpecificReg;
18836 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18837 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18838 weight = CW_Register;
18841 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18842 if (C->getZExtValue() <= 31)
18843 weight = CW_Constant;
18847 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18848 if (C->getZExtValue() <= 63)
18849 weight = CW_Constant;
18853 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18854 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18855 weight = CW_Constant;
18859 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18860 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18861 weight = CW_Constant;
18865 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18866 if (C->getZExtValue() <= 3)
18867 weight = CW_Constant;
18871 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18872 if (C->getZExtValue() <= 0xff)
18873 weight = CW_Constant;
18878 if (dyn_cast<ConstantFP>(CallOperandVal)) {
18879 weight = CW_Constant;
18883 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18884 if ((C->getSExtValue() >= -0x80000000LL) &&
18885 (C->getSExtValue() <= 0x7fffffffLL))
18886 weight = CW_Constant;
18890 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18891 if (C->getZExtValue() <= 0xffffffff)
18892 weight = CW_Constant;
18899 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18900 /// with another that has more specific requirements based on the type of the
18901 /// corresponding operand.
18902 const char *X86TargetLowering::
18903 LowerXConstraint(EVT ConstraintVT) const {
18904 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18905 // 'f' like normal targets.
18906 if (ConstraintVT.isFloatingPoint()) {
18907 if (Subtarget->hasSSE2())
18909 if (Subtarget->hasSSE1())
18913 return TargetLowering::LowerXConstraint(ConstraintVT);
18916 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18917 /// vector. If it is invalid, don't add anything to Ops.
18918 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18919 std::string &Constraint,
18920 std::vector<SDValue>&Ops,
18921 SelectionDAG &DAG) const {
18922 SDValue Result(0, 0);
18924 // Only support length 1 constraints for now.
18925 if (Constraint.length() > 1) return;
18927 char ConstraintLetter = Constraint[0];
18928 switch (ConstraintLetter) {
18931 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18932 if (C->getZExtValue() <= 31) {
18933 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18939 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18940 if (C->getZExtValue() <= 63) {
18941 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18947 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18948 if (isInt<8>(C->getSExtValue())) {
18949 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18955 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18956 if (C->getZExtValue() <= 255) {
18957 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18963 // 32-bit signed value
18964 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18965 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18966 C->getSExtValue())) {
18967 // Widen to 64 bits here to get it sign extended.
18968 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18971 // FIXME gcc accepts some relocatable values here too, but only in certain
18972 // memory models; it's complicated.
18977 // 32-bit unsigned value
18978 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18979 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18980 C->getZExtValue())) {
18981 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18985 // FIXME gcc accepts some relocatable values here too, but only in certain
18986 // memory models; it's complicated.
18990 // Literal immediates are always ok.
18991 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18992 // Widen to 64 bits here to get it sign extended.
18993 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18997 // In any sort of PIC mode addresses need to be computed at runtime by
18998 // adding in a register or some sort of table lookup. These can't
18999 // be used as immediates.
19000 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19003 // If we are in non-pic codegen mode, we allow the address of a global (with
19004 // an optional displacement) to be used with 'i'.
19005 GlobalAddressSDNode *GA = 0;
19006 int64_t Offset = 0;
19008 // Match either (GA), (GA+C), (GA+C1+C2), etc.
19010 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19011 Offset += GA->getOffset();
19013 } else if (Op.getOpcode() == ISD::ADD) {
19014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19015 Offset += C->getZExtValue();
19016 Op = Op.getOperand(0);
19019 } else if (Op.getOpcode() == ISD::SUB) {
19020 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19021 Offset += -C->getZExtValue();
19022 Op = Op.getOperand(0);
19027 // Otherwise, this isn't something we can handle, reject it.
19031 const GlobalValue *GV = GA->getGlobal();
19032 // If we require an extra load to get this address, as in PIC mode, we
19033 // can't accept it.
19034 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19035 getTargetMachine())))
19038 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19039 GA->getValueType(0), Offset);
19044 if (Result.getNode()) {
19045 Ops.push_back(Result);
19048 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19051 std::pair<unsigned, const TargetRegisterClass*>
19052 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19054 // First, see if this is a constraint that directly corresponds to an LLVM
19056 if (Constraint.size() == 1) {
19057 // GCC Constraint Letters
19058 switch (Constraint[0]) {
19060 // TODO: Slight differences here in allocation order and leaving
19061 // RIP in the class. Do they matter any more here than they do
19062 // in the normal allocation?
19063 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19064 if (Subtarget->is64Bit()) {
19065 if (VT == MVT::i32 || VT == MVT::f32)
19066 return std::make_pair(0U, &X86::GR32RegClass);
19067 if (VT == MVT::i16)
19068 return std::make_pair(0U, &X86::GR16RegClass);
19069 if (VT == MVT::i8 || VT == MVT::i1)
19070 return std::make_pair(0U, &X86::GR8RegClass);
19071 if (VT == MVT::i64 || VT == MVT::f64)
19072 return std::make_pair(0U, &X86::GR64RegClass);
19075 // 32-bit fallthrough
19076 case 'Q': // Q_REGS
19077 if (VT == MVT::i32 || VT == MVT::f32)
19078 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19079 if (VT == MVT::i16)
19080 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19081 if (VT == MVT::i8 || VT == MVT::i1)
19082 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19083 if (VT == MVT::i64)
19084 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19086 case 'r': // GENERAL_REGS
19087 case 'l': // INDEX_REGS
19088 if (VT == MVT::i8 || VT == MVT::i1)
19089 return std::make_pair(0U, &X86::GR8RegClass);
19090 if (VT == MVT::i16)
19091 return std::make_pair(0U, &X86::GR16RegClass);
19092 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19093 return std::make_pair(0U, &X86::GR32RegClass);
19094 return std::make_pair(0U, &X86::GR64RegClass);
19095 case 'R': // LEGACY_REGS
19096 if (VT == MVT::i8 || VT == MVT::i1)
19097 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19098 if (VT == MVT::i16)
19099 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19100 if (VT == MVT::i32 || !Subtarget->is64Bit())
19101 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19102 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19103 case 'f': // FP Stack registers.
19104 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19105 // value to the correct fpstack register class.
19106 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19107 return std::make_pair(0U, &X86::RFP32RegClass);
19108 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19109 return std::make_pair(0U, &X86::RFP64RegClass);
19110 return std::make_pair(0U, &X86::RFP80RegClass);
19111 case 'y': // MMX_REGS if MMX allowed.
19112 if (!Subtarget->hasMMX()) break;
19113 return std::make_pair(0U, &X86::VR64RegClass);
19114 case 'Y': // SSE_REGS if SSE2 allowed
19115 if (!Subtarget->hasSSE2()) break;
19117 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19118 if (!Subtarget->hasSSE1()) break;
19120 switch (VT.SimpleTy) {
19122 // Scalar SSE types.
19125 return std::make_pair(0U, &X86::FR32RegClass);
19128 return std::make_pair(0U, &X86::FR64RegClass);
19136 return std::make_pair(0U, &X86::VR128RegClass);
19144 return std::make_pair(0U, &X86::VR256RegClass);
19149 return std::make_pair(0U, &X86::VR512RegClass);
19155 // Use the default implementation in TargetLowering to convert the register
19156 // constraint into a member of a register class.
19157 std::pair<unsigned, const TargetRegisterClass*> Res;
19158 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19160 // Not found as a standard register?
19161 if (Res.second == 0) {
19162 // Map st(0) -> st(7) -> ST0
19163 if (Constraint.size() == 7 && Constraint[0] == '{' &&
19164 tolower(Constraint[1]) == 's' &&
19165 tolower(Constraint[2]) == 't' &&
19166 Constraint[3] == '(' &&
19167 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19168 Constraint[5] == ')' &&
19169 Constraint[6] == '}') {
19171 Res.first = X86::ST0+Constraint[4]-'0';
19172 Res.second = &X86::RFP80RegClass;
19176 // GCC allows "st(0)" to be called just plain "st".
19177 if (StringRef("{st}").equals_lower(Constraint)) {
19178 Res.first = X86::ST0;
19179 Res.second = &X86::RFP80RegClass;
19184 if (StringRef("{flags}").equals_lower(Constraint)) {
19185 Res.first = X86::EFLAGS;
19186 Res.second = &X86::CCRRegClass;
19190 // 'A' means EAX + EDX.
19191 if (Constraint == "A") {
19192 Res.first = X86::EAX;
19193 Res.second = &X86::GR32_ADRegClass;
19199 // Otherwise, check to see if this is a register class of the wrong value
19200 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19201 // turn into {ax},{dx}.
19202 if (Res.second->hasType(VT))
19203 return Res; // Correct type already, nothing to do.
19205 // All of the single-register GCC register classes map their values onto
19206 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
19207 // really want an 8-bit or 32-bit register, map to the appropriate register
19208 // class and return the appropriate register.
19209 if (Res.second == &X86::GR16RegClass) {
19210 if (VT == MVT::i8 || VT == MVT::i1) {
19211 unsigned DestReg = 0;
19212 switch (Res.first) {
19214 case X86::AX: DestReg = X86::AL; break;
19215 case X86::DX: DestReg = X86::DL; break;
19216 case X86::CX: DestReg = X86::CL; break;
19217 case X86::BX: DestReg = X86::BL; break;
19220 Res.first = DestReg;
19221 Res.second = &X86::GR8RegClass;
19223 } else if (VT == MVT::i32 || VT == MVT::f32) {
19224 unsigned DestReg = 0;
19225 switch (Res.first) {
19227 case X86::AX: DestReg = X86::EAX; break;
19228 case X86::DX: DestReg = X86::EDX; break;
19229 case X86::CX: DestReg = X86::ECX; break;
19230 case X86::BX: DestReg = X86::EBX; break;
19231 case X86::SI: DestReg = X86::ESI; break;
19232 case X86::DI: DestReg = X86::EDI; break;
19233 case X86::BP: DestReg = X86::EBP; break;
19234 case X86::SP: DestReg = X86::ESP; break;
19237 Res.first = DestReg;
19238 Res.second = &X86::GR32RegClass;
19240 } else if (VT == MVT::i64 || VT == MVT::f64) {
19241 unsigned DestReg = 0;
19242 switch (Res.first) {
19244 case X86::AX: DestReg = X86::RAX; break;
19245 case X86::DX: DestReg = X86::RDX; break;
19246 case X86::CX: DestReg = X86::RCX; break;
19247 case X86::BX: DestReg = X86::RBX; break;
19248 case X86::SI: DestReg = X86::RSI; break;
19249 case X86::DI: DestReg = X86::RDI; break;
19250 case X86::BP: DestReg = X86::RBP; break;
19251 case X86::SP: DestReg = X86::RSP; break;
19254 Res.first = DestReg;
19255 Res.second = &X86::GR64RegClass;
19258 } else if (Res.second == &X86::FR32RegClass ||
19259 Res.second == &X86::FR64RegClass ||
19260 Res.second == &X86::VR128RegClass ||
19261 Res.second == &X86::VR256RegClass ||
19262 Res.second == &X86::FR32XRegClass ||
19263 Res.second == &X86::FR64XRegClass ||
19264 Res.second == &X86::VR128XRegClass ||
19265 Res.second == &X86::VR256XRegClass ||
19266 Res.second == &X86::VR512RegClass) {
19267 // Handle references to XMM physical registers that got mapped into the
19268 // wrong class. This can happen with constraints like {xmm0} where the
19269 // target independent register mapper will just pick the first match it can
19270 // find, ignoring the required type.
19272 if (VT == MVT::f32 || VT == MVT::i32)
19273 Res.second = &X86::FR32RegClass;
19274 else if (VT == MVT::f64 || VT == MVT::i64)
19275 Res.second = &X86::FR64RegClass;
19276 else if (X86::VR128RegClass.hasType(VT))
19277 Res.second = &X86::VR128RegClass;
19278 else if (X86::VR256RegClass.hasType(VT))
19279 Res.second = &X86::VR256RegClass;
19280 else if (X86::VR512RegClass.hasType(VT))
19281 Res.second = &X86::VR512RegClass;