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 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, SDLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 // If the input is a buildvector just emit a smaller one.
89 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
90 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
91 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
93 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
94 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
100 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
101 /// sets things up to match to an AVX VINSERTF128 instruction or a
102 /// simple superregister reference. Idx is an index in the 128 bits
103 /// we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering INSERT_VECTOR_ELT operations easier.
105 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
106 unsigned IdxVal, SelectionDAG &DAG,
108 // Inserting UNDEF is Result
109 if (Vec.getOpcode() == ISD::UNDEF)
112 EVT VT = Vec.getValueType();
113 assert(VT.is128BitVector() && "Unexpected vector size!");
115 EVT ElVT = VT.getVectorElementType();
116 EVT ResultVT = Result.getValueType();
118 // Insert the relevant 128 bits.
119 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
121 // This is the index of the first element of the 128-bit chunk
123 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
126 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
127 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
131 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
132 /// instructions. This is used because creating CONCAT_VECTOR nodes of
133 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
134 /// large BUILD_VECTORS.
135 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
136 unsigned NumElems, SelectionDAG &DAG,
138 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
139 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
142 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
143 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
144 bool is64Bit = Subtarget->is64Bit();
146 if (Subtarget->isTargetEnvMacho()) {
148 return new X86_64MachoTargetObjectFile();
149 return new TargetLoweringObjectFileMachO();
152 if (Subtarget->isTargetLinux())
153 return new X86LinuxTargetObjectFile();
154 if (Subtarget->isTargetELF())
155 return new TargetLoweringObjectFileELF();
156 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157 return new TargetLoweringObjectFileCOFF();
158 llvm_unreachable("unknown subtarget type");
161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162 : TargetLowering(TM, createTLOF(TM)) {
163 Subtarget = &TM.getSubtarget<X86Subtarget>();
164 X86ScalarSSEf64 = Subtarget->hasSSE2();
165 X86ScalarSSEf32 = Subtarget->hasSSE1();
166 TD = getDataLayout();
168 resetOperationActions();
171 void X86TargetLowering::resetOperationActions() {
172 const TargetMachine &TM = getTargetMachine();
173 static bool FirstTimeThrough = true;
175 // If none of the target options have changed, then we don't need to reset the
176 // operation actions.
177 if (!FirstTimeThrough && TO == TM.Options) return;
179 if (!FirstTimeThrough) {
180 // Reinitialize the actions.
182 FirstTimeThrough = false;
187 // Set up the TargetLowering object.
188 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
190 // X86 is weird, it always uses i8 for shift amounts and setcc results.
191 setBooleanContents(ZeroOrOneBooleanContent);
192 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
193 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
195 // For 64-bit since we have so many registers use the ILP scheduler, for
196 // 32-bit code use the register pressure specific scheduling.
197 // For Atom, always use ILP scheduling.
198 if (Subtarget->isAtom())
199 setSchedulingPreference(Sched::ILP);
200 else if (Subtarget->is64Bit())
201 setSchedulingPreference(Sched::ILP);
203 setSchedulingPreference(Sched::RegPressure);
204 const X86RegisterInfo *RegInfo =
205 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
206 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
208 // Bypass expensive divides on Atom when compiling with O2
209 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
210 addBypassSlowDiv(32, 8);
211 if (Subtarget->is64Bit())
212 addBypassSlowDiv(64, 16);
215 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
216 // Setup Windows compiler runtime calls.
217 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
218 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
219 setLibcallName(RTLIB::SREM_I64, "_allrem");
220 setLibcallName(RTLIB::UREM_I64, "_aullrem");
221 setLibcallName(RTLIB::MUL_I64, "_allmul");
222 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
223 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
224 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
225 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
226 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
228 // The _ftol2 runtime function has an unusual calling conv, which
229 // is modeled by a special pseudo-instruction.
230 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
231 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
232 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
233 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
236 if (Subtarget->isTargetDarwin()) {
237 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
238 setUseUnderscoreSetJmp(false);
239 setUseUnderscoreLongJmp(false);
240 } else if (Subtarget->isTargetMingw()) {
241 // MS runtime is weird: it exports _setjmp, but longjmp!
242 setUseUnderscoreSetJmp(true);
243 setUseUnderscoreLongJmp(false);
245 setUseUnderscoreSetJmp(true);
246 setUseUnderscoreLongJmp(true);
249 // Set up the register classes.
250 addRegisterClass(MVT::i8, &X86::GR8RegClass);
251 addRegisterClass(MVT::i16, &X86::GR16RegClass);
252 addRegisterClass(MVT::i32, &X86::GR32RegClass);
253 if (Subtarget->is64Bit())
254 addRegisterClass(MVT::i64, &X86::GR64RegClass);
256 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
258 // We don't accept any truncstore of integer registers.
259 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
260 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
261 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
262 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
263 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
264 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
266 // SETOEQ and SETUNE require checking two conditions.
267 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
268 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
269 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
270 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
271 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
272 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
274 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
276 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
277 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
278 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
280 if (Subtarget->is64Bit()) {
281 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
282 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
283 } else if (!TM.Options.UseSoftFloat) {
284 // We have an algorithm for SSE2->double, and we turn this into a
285 // 64-bit FILD followed by conditional FADD for other targets.
286 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
287 // We have an algorithm for SSE2, and we turn this into a 64-bit
288 // FILD for other targets.
289 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
292 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
294 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
295 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
297 if (!TM.Options.UseSoftFloat) {
298 // SSE has no i16 to fp conversion, only i32
299 if (X86ScalarSSEf32) {
300 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
301 // f32 and f64 cases are Legal, f80 case is not
302 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
304 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
305 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
308 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
309 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
312 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
313 // are Legal, f80 is custom lowered.
314 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
315 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
317 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
319 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
320 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
322 if (X86ScalarSSEf32) {
323 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
324 // f32 and f64 cases are Legal, f80 case is not
325 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
327 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
328 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
331 // Handle FP_TO_UINT by promoting the destination to a larger signed
333 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
334 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
335 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
339 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
340 } else if (!TM.Options.UseSoftFloat) {
341 // Since AVX is a superset of SSE3, only check for SSE here.
342 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
343 // Expand FP_TO_UINT into a select.
344 // FIXME: We would like to use a Custom expander here eventually to do
345 // the optimal thing for SSE vs. the default expansion in the legalizer.
346 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
348 // With SSE3 we can use fisttpll to convert to a signed i64; without
349 // SSE, we're stuck with a fistpll.
350 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
353 if (isTargetFTOL()) {
354 // Use the _ftol2 runtime function, which has a pseudo-instruction
355 // to handle its weird calling convention.
356 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
359 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
360 if (!X86ScalarSSEf64) {
361 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
362 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
363 if (Subtarget->is64Bit()) {
364 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
365 // Without SSE, i64->f64 goes through memory.
366 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
370 // Scalar integer divide and remainder are lowered to use operations that
371 // produce two results, to match the available instructions. This exposes
372 // the two-result form to trivial CSE, which is able to combine x/y and x%y
373 // into a single instruction.
375 // Scalar integer multiply-high is also lowered to use two-result
376 // operations, to match the available instructions. However, plain multiply
377 // (low) operations are left as Legal, as there are single-result
378 // instructions for this in x86. Using the two-result multiply instructions
379 // when both high and low results are needed must be arranged by dagcombine.
380 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
382 setOperationAction(ISD::MULHS, VT, Expand);
383 setOperationAction(ISD::MULHU, VT, Expand);
384 setOperationAction(ISD::SDIV, VT, Expand);
385 setOperationAction(ISD::UDIV, VT, Expand);
386 setOperationAction(ISD::SREM, VT, Expand);
387 setOperationAction(ISD::UREM, VT, Expand);
389 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
390 setOperationAction(ISD::ADDC, VT, Custom);
391 setOperationAction(ISD::ADDE, VT, Custom);
392 setOperationAction(ISD::SUBC, VT, Custom);
393 setOperationAction(ISD::SUBE, VT, Custom);
396 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
397 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
398 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
399 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
400 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
401 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
402 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
403 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
404 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
405 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
406 if (Subtarget->is64Bit())
407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
408 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
409 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
410 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
411 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
412 setOperationAction(ISD::FREM , MVT::f32 , Expand);
413 setOperationAction(ISD::FREM , MVT::f64 , Expand);
414 setOperationAction(ISD::FREM , MVT::f80 , Expand);
415 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
417 // Promote the i8 variants and force them on up to i32 which has a shorter
419 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
420 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
421 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
422 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
423 if (Subtarget->hasBMI()) {
424 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
425 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
426 if (Subtarget->is64Bit())
427 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
429 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
430 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
431 if (Subtarget->is64Bit())
432 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
435 if (Subtarget->hasLZCNT()) {
436 // When promoting the i8 variants, force them to i32 for a shorter
438 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
439 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
440 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
441 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
442 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
443 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
444 if (Subtarget->is64Bit())
445 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
447 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
448 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
449 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
450 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
451 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
452 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
455 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
459 if (Subtarget->hasPOPCNT()) {
460 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
462 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
463 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
464 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
469 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
470 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
472 // These should be promoted to a larger select which is supported.
473 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
474 // X86 wants to expand cmov itself.
475 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
476 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
477 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
478 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
479 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
480 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
481 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
482 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
483 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
484 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
485 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
486 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
487 if (Subtarget->is64Bit()) {
488 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
489 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
491 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
492 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
493 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
494 // support continuation, user-level threading, and etc.. As a result, no
495 // other SjLj exception interfaces are implemented and please don't build
496 // your own exception handling based on them.
497 // LLVM/Clang supports zero-cost DWARF exception handling.
498 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
499 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
502 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
503 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
504 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
505 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
506 if (Subtarget->is64Bit())
507 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
508 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
509 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
510 if (Subtarget->is64Bit()) {
511 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
512 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
513 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
514 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
515 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
517 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
518 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
519 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
520 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
521 if (Subtarget->is64Bit()) {
522 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
523 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
524 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
527 if (Subtarget->hasSSE1())
528 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
530 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
532 // Expand certain atomics
533 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
535 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
536 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
537 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
540 if (!Subtarget->is64Bit()) {
541 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
542 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
543 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
544 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
545 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
546 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
547 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
548 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
549 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
550 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
551 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
552 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
555 if (Subtarget->hasCmpxchg16b()) {
556 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
559 // FIXME - use subtarget debug flags
560 if (!Subtarget->isTargetDarwin() &&
561 !Subtarget->isTargetELF() &&
562 !Subtarget->isTargetCygMing()) {
563 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
566 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
567 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
568 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
569 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
570 if (Subtarget->is64Bit()) {
571 setExceptionPointerRegister(X86::RAX);
572 setExceptionSelectorRegister(X86::RDX);
574 setExceptionPointerRegister(X86::EAX);
575 setExceptionSelectorRegister(X86::EDX);
577 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
578 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
580 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
581 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
583 setOperationAction(ISD::TRAP, MVT::Other, Legal);
584 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
586 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
587 setOperationAction(ISD::VASTART , MVT::Other, Custom);
588 setOperationAction(ISD::VAEND , MVT::Other, Expand);
589 if (Subtarget->is64Bit()) {
590 setOperationAction(ISD::VAARG , MVT::Other, Custom);
591 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
593 setOperationAction(ISD::VAARG , MVT::Other, Expand);
594 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
597 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
598 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
600 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
601 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
602 MVT::i64 : MVT::i32, Custom);
603 else if (TM.Options.EnableSegmentedStacks)
604 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
605 MVT::i64 : MVT::i32, Custom);
607 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
608 MVT::i64 : MVT::i32, Expand);
610 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
611 // f32 and f64 use SSE.
612 // Set up the FP register classes.
613 addRegisterClass(MVT::f32, &X86::FR32RegClass);
614 addRegisterClass(MVT::f64, &X86::FR64RegClass);
616 // Use ANDPD to simulate FABS.
617 setOperationAction(ISD::FABS , MVT::f64, Custom);
618 setOperationAction(ISD::FABS , MVT::f32, Custom);
620 // Use XORP to simulate FNEG.
621 setOperationAction(ISD::FNEG , MVT::f64, Custom);
622 setOperationAction(ISD::FNEG , MVT::f32, Custom);
624 // Use ANDPD and ORPD to simulate FCOPYSIGN.
625 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
626 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
628 // Lower this to FGETSIGNx86 plus an AND.
629 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
630 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
632 // We don't support sin/cos/fmod
633 setOperationAction(ISD::FSIN , MVT::f64, Expand);
634 setOperationAction(ISD::FCOS , MVT::f64, Expand);
635 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
636 setOperationAction(ISD::FSIN , MVT::f32, Expand);
637 setOperationAction(ISD::FCOS , MVT::f32, Expand);
638 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
640 // Expand FP immediates into loads from the stack, except for the special
642 addLegalFPImmediate(APFloat(+0.0)); // xorpd
643 addLegalFPImmediate(APFloat(+0.0f)); // xorps
644 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
645 // Use SSE for f32, x87 for f64.
646 // Set up the FP register classes.
647 addRegisterClass(MVT::f32, &X86::FR32RegClass);
648 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
650 // Use ANDPS to simulate FABS.
651 setOperationAction(ISD::FABS , MVT::f32, Custom);
653 // Use XORP to simulate FNEG.
654 setOperationAction(ISD::FNEG , MVT::f32, Custom);
656 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
658 // Use ANDPS and ORPS to simulate FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
662 // We don't support sin/cos/fmod
663 setOperationAction(ISD::FSIN , MVT::f32, Expand);
664 setOperationAction(ISD::FCOS , MVT::f32, Expand);
665 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
667 // Special cases we handle for FP constants.
668 addLegalFPImmediate(APFloat(+0.0f)); // xorps
669 addLegalFPImmediate(APFloat(+0.0)); // FLD0
670 addLegalFPImmediate(APFloat(+1.0)); // FLD1
671 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
672 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
674 if (!TM.Options.UnsafeFPMath) {
675 setOperationAction(ISD::FSIN , MVT::f64, Expand);
676 setOperationAction(ISD::FCOS , MVT::f64, Expand);
677 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
679 } else if (!TM.Options.UseSoftFloat) {
680 // f32 and f64 in x87.
681 // Set up the FP register classes.
682 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
685 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
686 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
687 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
688 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
690 if (!TM.Options.UnsafeFPMath) {
691 setOperationAction(ISD::FSIN , MVT::f64, Expand);
692 setOperationAction(ISD::FSIN , MVT::f32, Expand);
693 setOperationAction(ISD::FCOS , MVT::f64, Expand);
694 setOperationAction(ISD::FCOS , MVT::f32, Expand);
695 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
696 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
698 addLegalFPImmediate(APFloat(+0.0)); // FLD0
699 addLegalFPImmediate(APFloat(+1.0)); // FLD1
700 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
701 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
702 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
703 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
704 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
705 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
708 // We don't support FMA.
709 setOperationAction(ISD::FMA, MVT::f64, Expand);
710 setOperationAction(ISD::FMA, MVT::f32, Expand);
712 // Long double always uses X87.
713 if (!TM.Options.UseSoftFloat) {
714 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
715 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
716 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
718 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
719 addLegalFPImmediate(TmpFlt); // FLD0
721 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
724 APFloat TmpFlt2(+1.0);
725 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
727 addLegalFPImmediate(TmpFlt2); // FLD1
728 TmpFlt2.changeSign();
729 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
732 if (!TM.Options.UnsafeFPMath) {
733 setOperationAction(ISD::FSIN , MVT::f80, Expand);
734 setOperationAction(ISD::FCOS , MVT::f80, Expand);
735 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
738 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
739 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
740 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
741 setOperationAction(ISD::FRINT, MVT::f80, Expand);
742 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
743 setOperationAction(ISD::FMA, MVT::f80, Expand);
746 // Always use a library call for pow.
747 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
748 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
749 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
751 setOperationAction(ISD::FLOG, MVT::f80, Expand);
752 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
753 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
754 setOperationAction(ISD::FEXP, MVT::f80, Expand);
755 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
757 // First set operation action for all vector types to either promote
758 // (for widening) or expand (for scalarization). Then we will selectively
759 // turn on ones that can be effectively codegen'd.
760 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
761 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
762 MVT VT = (MVT::SimpleValueType)i;
763 setOperationAction(ISD::ADD , VT, Expand);
764 setOperationAction(ISD::SUB , VT, Expand);
765 setOperationAction(ISD::FADD, VT, Expand);
766 setOperationAction(ISD::FNEG, VT, Expand);
767 setOperationAction(ISD::FSUB, VT, Expand);
768 setOperationAction(ISD::MUL , VT, Expand);
769 setOperationAction(ISD::FMUL, VT, Expand);
770 setOperationAction(ISD::SDIV, VT, Expand);
771 setOperationAction(ISD::UDIV, VT, Expand);
772 setOperationAction(ISD::FDIV, VT, Expand);
773 setOperationAction(ISD::SREM, VT, Expand);
774 setOperationAction(ISD::UREM, VT, Expand);
775 setOperationAction(ISD::LOAD, VT, Expand);
776 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
779 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
780 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
781 setOperationAction(ISD::FABS, VT, Expand);
782 setOperationAction(ISD::FSIN, VT, Expand);
783 setOperationAction(ISD::FSINCOS, VT, Expand);
784 setOperationAction(ISD::FCOS, VT, Expand);
785 setOperationAction(ISD::FSINCOS, VT, Expand);
786 setOperationAction(ISD::FREM, VT, Expand);
787 setOperationAction(ISD::FMA, VT, Expand);
788 setOperationAction(ISD::FPOWI, VT, Expand);
789 setOperationAction(ISD::FSQRT, VT, Expand);
790 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
791 setOperationAction(ISD::FFLOOR, VT, Expand);
792 setOperationAction(ISD::FCEIL, VT, Expand);
793 setOperationAction(ISD::FTRUNC, VT, Expand);
794 setOperationAction(ISD::FRINT, VT, Expand);
795 setOperationAction(ISD::FNEARBYINT, VT, Expand);
796 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
797 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
798 setOperationAction(ISD::SDIVREM, VT, Expand);
799 setOperationAction(ISD::UDIVREM, VT, Expand);
800 setOperationAction(ISD::FPOW, VT, Expand);
801 setOperationAction(ISD::CTPOP, VT, Expand);
802 setOperationAction(ISD::CTTZ, VT, Expand);
803 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
804 setOperationAction(ISD::CTLZ, VT, Expand);
805 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
806 setOperationAction(ISD::SHL, VT, Expand);
807 setOperationAction(ISD::SRA, VT, Expand);
808 setOperationAction(ISD::SRL, VT, Expand);
809 setOperationAction(ISD::ROTL, VT, Expand);
810 setOperationAction(ISD::ROTR, VT, Expand);
811 setOperationAction(ISD::BSWAP, VT, Expand);
812 setOperationAction(ISD::SETCC, VT, Expand);
813 setOperationAction(ISD::FLOG, VT, Expand);
814 setOperationAction(ISD::FLOG2, VT, Expand);
815 setOperationAction(ISD::FLOG10, VT, Expand);
816 setOperationAction(ISD::FEXP, VT, Expand);
817 setOperationAction(ISD::FEXP2, VT, Expand);
818 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
819 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
820 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
821 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
822 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
823 setOperationAction(ISD::TRUNCATE, VT, Expand);
824 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
825 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
826 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
827 setOperationAction(ISD::VSELECT, VT, Expand);
828 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
829 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
830 setTruncStoreAction(VT,
831 (MVT::SimpleValueType)InnerVT, Expand);
832 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
833 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
834 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
837 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
838 // with -msoft-float, disable use of MMX as well.
839 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
840 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
841 // No operations on x86mmx supported, everything uses intrinsics.
844 // MMX-sized vectors (other than x86mmx) are expected to be expanded
845 // into smaller operations.
846 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
847 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
848 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
849 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
850 setOperationAction(ISD::AND, MVT::v8i8, Expand);
851 setOperationAction(ISD::AND, MVT::v4i16, Expand);
852 setOperationAction(ISD::AND, MVT::v2i32, Expand);
853 setOperationAction(ISD::AND, MVT::v1i64, Expand);
854 setOperationAction(ISD::OR, MVT::v8i8, Expand);
855 setOperationAction(ISD::OR, MVT::v4i16, Expand);
856 setOperationAction(ISD::OR, MVT::v2i32, Expand);
857 setOperationAction(ISD::OR, MVT::v1i64, Expand);
858 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
859 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
860 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
861 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
862 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
863 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
864 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
865 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
866 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
867 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
868 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
869 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
870 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
871 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
872 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
873 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
874 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
876 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
877 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
879 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
880 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
881 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
882 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
883 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
884 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
885 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
886 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
887 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
888 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
889 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
890 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
893 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
894 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
896 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
897 // registers cannot be used even for integer operations.
898 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
899 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
900 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
901 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
903 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
904 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
905 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
906 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
907 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
908 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
909 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
910 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
911 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
912 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
913 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
914 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
915 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
916 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
917 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
918 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
919 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
920 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
922 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
923 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
924 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
925 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
930 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
933 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
934 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
935 MVT VT = (MVT::SimpleValueType)i;
936 // Do not attempt to custom lower non-power-of-2 vectors
937 if (!isPowerOf2_32(VT.getVectorNumElements()))
939 // Do not attempt to custom lower non-128-bit vectors
940 if (!VT.is128BitVector())
942 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
943 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
947 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
948 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
949 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
950 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
951 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
954 if (Subtarget->is64Bit()) {
955 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
956 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
959 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
960 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
961 MVT VT = (MVT::SimpleValueType)i;
963 // Do not attempt to promote non-128-bit vectors
964 if (!VT.is128BitVector())
967 setOperationAction(ISD::AND, VT, Promote);
968 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
969 setOperationAction(ISD::OR, VT, Promote);
970 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
971 setOperationAction(ISD::XOR, VT, Promote);
972 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
973 setOperationAction(ISD::LOAD, VT, Promote);
974 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
975 setOperationAction(ISD::SELECT, VT, Promote);
976 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
979 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
981 // Custom lower v2i64 and v2f64 selects.
982 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
983 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
984 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
985 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
987 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
988 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
990 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
991 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
992 // As there is no 64-bit GPR available, we need build a special custom
993 // sequence to convert from v2i32 to v2f32.
994 if (!Subtarget->is64Bit())
995 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
997 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
998 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1000 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1003 if (Subtarget->hasSSE41()) {
1004 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1005 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1006 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1007 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1008 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1009 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1010 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1011 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1012 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1013 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1015 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1016 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1017 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1018 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1019 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1020 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1021 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1022 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1023 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1024 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1026 // FIXME: Do we need to handle scalar-to-vector here?
1027 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1029 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1030 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1031 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1032 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1033 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1035 // i8 and i16 vectors are custom , because the source register and source
1036 // source memory operand types are not the same width. f32 vectors are
1037 // custom since the immediate controlling the insert encodes additional
1039 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1040 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1041 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1042 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1044 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1045 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1046 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1047 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1049 // FIXME: these should be Legal but thats only for the case where
1050 // the index is constant. For now custom expand to deal with that.
1051 if (Subtarget->is64Bit()) {
1052 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1053 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1057 if (Subtarget->hasSSE2()) {
1058 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1059 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1061 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1062 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1064 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1065 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1067 // In the customized shift lowering, the legal cases in AVX2 will be
1069 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1070 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1072 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1073 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1075 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1077 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1078 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1081 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1082 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1083 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1084 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1085 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1086 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1087 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1089 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1090 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1091 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1093 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1094 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1095 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1096 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1097 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1098 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1099 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1100 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1101 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1102 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1103 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1104 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1106 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1107 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1108 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1109 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1110 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1111 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1112 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1113 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1114 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1115 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1116 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1117 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1119 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1120 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1122 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1124 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1125 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1126 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1127 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1129 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1130 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1131 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1133 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1135 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1136 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1138 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1139 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1141 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1142 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1144 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1146 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1147 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1148 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1149 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1151 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1152 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1153 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1155 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1156 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1157 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1158 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1160 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1161 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1162 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1163 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1164 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1165 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1167 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1168 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1169 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1170 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1171 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1172 setOperationAction(ISD::FMA, MVT::f32, Legal);
1173 setOperationAction(ISD::FMA, MVT::f64, Legal);
1176 if (Subtarget->hasInt256()) {
1177 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1178 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1179 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1180 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1182 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1183 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1184 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1185 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1187 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1188 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1189 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1190 // Don't lower v32i8 because there is no 128-bit byte mul
1192 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1194 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1197 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1198 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1199 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1201 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1202 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1203 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1204 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1206 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1207 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1208 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1209 // Don't lower v32i8 because there is no 128-bit byte mul
1212 // In the customized shift lowering, the legal cases in AVX2 will be
1214 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1215 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1217 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1218 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1220 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1222 // Custom lower several nodes for 256-bit types.
1223 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1224 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1225 MVT VT = (MVT::SimpleValueType)i;
1227 // Extract subvector is special because the value type
1228 // (result) is 128-bit but the source is 256-bit wide.
1229 if (VT.is128BitVector())
1230 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1232 // Do not attempt to custom lower other non-256-bit vectors
1233 if (!VT.is256BitVector())
1236 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1237 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1238 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1239 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1240 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1241 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1242 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1245 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1246 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1247 MVT VT = (MVT::SimpleValueType)i;
1249 // Do not attempt to promote non-256-bit vectors
1250 if (!VT.is256BitVector())
1253 setOperationAction(ISD::AND, VT, Promote);
1254 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1255 setOperationAction(ISD::OR, VT, Promote);
1256 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1257 setOperationAction(ISD::XOR, VT, Promote);
1258 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1259 setOperationAction(ISD::LOAD, VT, Promote);
1260 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1261 setOperationAction(ISD::SELECT, VT, Promote);
1262 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1266 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1267 // of this type with custom code.
1268 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1269 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1270 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1274 // We want to custom lower some of our intrinsics.
1275 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1276 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1278 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1279 // handle type legalization for these operations here.
1281 // FIXME: We really should do custom legalization for addition and
1282 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1283 // than generic legalization for 64-bit multiplication-with-overflow, though.
1284 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1285 // Add/Sub/Mul with overflow operations are custom lowered.
1287 setOperationAction(ISD::SADDO, VT, Custom);
1288 setOperationAction(ISD::UADDO, VT, Custom);
1289 setOperationAction(ISD::SSUBO, VT, Custom);
1290 setOperationAction(ISD::USUBO, VT, Custom);
1291 setOperationAction(ISD::SMULO, VT, Custom);
1292 setOperationAction(ISD::UMULO, VT, Custom);
1295 // There are no 8-bit 3-address imul/mul instructions
1296 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1297 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1299 if (!Subtarget->is64Bit()) {
1300 // These libcalls are not available in 32-bit.
1301 setLibcallName(RTLIB::SHL_I128, 0);
1302 setLibcallName(RTLIB::SRL_I128, 0);
1303 setLibcallName(RTLIB::SRA_I128, 0);
1306 // Combine sin / cos into one node or libcall if possible.
1307 if (Subtarget->hasSinCos()) {
1308 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1309 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1310 if (Subtarget->isTargetDarwin()) {
1311 // For MacOSX, we don't want to the normal expansion of a libcall to
1312 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1314 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1315 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1319 // We have target-specific dag combine patterns for the following nodes:
1320 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1321 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1322 setTargetDAGCombine(ISD::VSELECT);
1323 setTargetDAGCombine(ISD::SELECT);
1324 setTargetDAGCombine(ISD::SHL);
1325 setTargetDAGCombine(ISD::SRA);
1326 setTargetDAGCombine(ISD::SRL);
1327 setTargetDAGCombine(ISD::OR);
1328 setTargetDAGCombine(ISD::AND);
1329 setTargetDAGCombine(ISD::ADD);
1330 setTargetDAGCombine(ISD::FADD);
1331 setTargetDAGCombine(ISD::FSUB);
1332 setTargetDAGCombine(ISD::FMA);
1333 setTargetDAGCombine(ISD::SUB);
1334 setTargetDAGCombine(ISD::LOAD);
1335 setTargetDAGCombine(ISD::STORE);
1336 setTargetDAGCombine(ISD::ZERO_EXTEND);
1337 setTargetDAGCombine(ISD::ANY_EXTEND);
1338 setTargetDAGCombine(ISD::SIGN_EXTEND);
1339 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1340 setTargetDAGCombine(ISD::TRUNCATE);
1341 setTargetDAGCombine(ISD::SINT_TO_FP);
1342 setTargetDAGCombine(ISD::SETCC);
1343 if (Subtarget->is64Bit())
1344 setTargetDAGCombine(ISD::MUL);
1345 setTargetDAGCombine(ISD::XOR);
1347 computeRegisterProperties();
1349 // On Darwin, -Os means optimize for size without hurting performance,
1350 // do not reduce the limit.
1351 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1352 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1353 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1354 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1355 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1356 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1357 setPrefLoopAlignment(4); // 2^4 bytes.
1359 // Predictable cmov don't hurt on atom because it's in-order.
1360 PredictableSelectIsExpensive = !Subtarget->isAtom();
1362 setPrefFunctionAlignment(4); // 2^4 bytes.
1365 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1366 if (!VT.isVector()) return MVT::i8;
1367 return VT.changeVectorElementTypeToInteger();
1370 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1371 /// the desired ByVal argument alignment.
1372 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1375 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1376 if (VTy->getBitWidth() == 128)
1378 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1379 unsigned EltAlign = 0;
1380 getMaxByValAlign(ATy->getElementType(), EltAlign);
1381 if (EltAlign > MaxAlign)
1382 MaxAlign = EltAlign;
1383 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1384 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1385 unsigned EltAlign = 0;
1386 getMaxByValAlign(STy->getElementType(i), EltAlign);
1387 if (EltAlign > MaxAlign)
1388 MaxAlign = EltAlign;
1395 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1396 /// function arguments in the caller parameter area. For X86, aggregates
1397 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1398 /// are at 4-byte boundaries.
1399 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1400 if (Subtarget->is64Bit()) {
1401 // Max of 8 and alignment of type.
1402 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1409 if (Subtarget->hasSSE1())
1410 getMaxByValAlign(Ty, Align);
1414 /// getOptimalMemOpType - Returns the target specific optimal type for load
1415 /// and store operations as a result of memset, memcpy, and memmove
1416 /// lowering. If DstAlign is zero that means it's safe to destination
1417 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1418 /// means there isn't a need to check it against alignment requirement,
1419 /// probably because the source does not need to be loaded. If 'IsMemset' is
1420 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1421 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1422 /// source is constant so it does not need to be loaded.
1423 /// It returns EVT::Other if the type should be determined using generic
1424 /// target-independent logic.
1426 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1427 unsigned DstAlign, unsigned SrcAlign,
1428 bool IsMemset, bool ZeroMemset,
1430 MachineFunction &MF) const {
1431 const Function *F = MF.getFunction();
1432 if ((!IsMemset || ZeroMemset) &&
1433 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1434 Attribute::NoImplicitFloat)) {
1436 (Subtarget->isUnalignedMemAccessFast() ||
1437 ((DstAlign == 0 || DstAlign >= 16) &&
1438 (SrcAlign == 0 || SrcAlign >= 16)))) {
1440 if (Subtarget->hasInt256())
1442 if (Subtarget->hasFp256())
1445 if (Subtarget->hasSSE2())
1447 if (Subtarget->hasSSE1())
1449 } else if (!MemcpyStrSrc && Size >= 8 &&
1450 !Subtarget->is64Bit() &&
1451 Subtarget->hasSSE2()) {
1452 // Do not use f64 to lower memcpy if source is string constant. It's
1453 // better to use i32 to avoid the loads.
1457 if (Subtarget->is64Bit() && Size >= 8)
1462 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1464 return X86ScalarSSEf32;
1465 else if (VT == MVT::f64)
1466 return X86ScalarSSEf64;
1471 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1473 *Fast = Subtarget->isUnalignedMemAccessFast();
1477 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1478 /// current function. The returned value is a member of the
1479 /// MachineJumpTableInfo::JTEntryKind enum.
1480 unsigned X86TargetLowering::getJumpTableEncoding() const {
1481 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1483 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1484 Subtarget->isPICStyleGOT())
1485 return MachineJumpTableInfo::EK_Custom32;
1487 // Otherwise, use the normal jump table encoding heuristics.
1488 return TargetLowering::getJumpTableEncoding();
1492 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1493 const MachineBasicBlock *MBB,
1494 unsigned uid,MCContext &Ctx) const{
1495 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1496 Subtarget->isPICStyleGOT());
1497 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1499 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1500 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1503 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1505 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1506 SelectionDAG &DAG) const {
1507 if (!Subtarget->is64Bit())
1508 // This doesn't have SDLoc associated with it, but is not really the
1509 // same as a Register.
1510 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1514 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1515 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1517 const MCExpr *X86TargetLowering::
1518 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1519 MCContext &Ctx) const {
1520 // X86-64 uses RIP relative addressing based on the jump table label.
1521 if (Subtarget->isPICStyleRIPRel())
1522 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1524 // Otherwise, the reference is relative to the PIC base.
1525 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1528 // FIXME: Why this routine is here? Move to RegInfo!
1529 std::pair<const TargetRegisterClass*, uint8_t>
1530 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1531 const TargetRegisterClass *RRC = 0;
1533 switch (VT.SimpleTy) {
1535 return TargetLowering::findRepresentativeClass(VT);
1536 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1537 RRC = Subtarget->is64Bit() ?
1538 (const TargetRegisterClass*)&X86::GR64RegClass :
1539 (const TargetRegisterClass*)&X86::GR32RegClass;
1542 RRC = &X86::VR64RegClass;
1544 case MVT::f32: case MVT::f64:
1545 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1546 case MVT::v4f32: case MVT::v2f64:
1547 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1549 RRC = &X86::VR128RegClass;
1552 return std::make_pair(RRC, Cost);
1555 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1556 unsigned &Offset) const {
1557 if (!Subtarget->isTargetLinux())
1560 if (Subtarget->is64Bit()) {
1561 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1563 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1575 //===----------------------------------------------------------------------===//
1576 // Return Value Calling Convention Implementation
1577 //===----------------------------------------------------------------------===//
1579 #include "X86GenCallingConv.inc"
1582 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1583 MachineFunction &MF, bool isVarArg,
1584 const SmallVectorImpl<ISD::OutputArg> &Outs,
1585 LLVMContext &Context) const {
1586 SmallVector<CCValAssign, 16> RVLocs;
1587 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1589 return CCInfo.CheckReturn(Outs, RetCC_X86);
1593 X86TargetLowering::LowerReturn(SDValue Chain,
1594 CallingConv::ID CallConv, bool isVarArg,
1595 const SmallVectorImpl<ISD::OutputArg> &Outs,
1596 const SmallVectorImpl<SDValue> &OutVals,
1597 SDLoc dl, SelectionDAG &DAG) const {
1598 MachineFunction &MF = DAG.getMachineFunction();
1599 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1601 SmallVector<CCValAssign, 16> RVLocs;
1602 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1603 RVLocs, *DAG.getContext());
1604 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1607 SmallVector<SDValue, 6> RetOps;
1608 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1609 // Operand #1 = Bytes To Pop
1610 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1613 // Copy the result values into the output registers.
1614 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1615 CCValAssign &VA = RVLocs[i];
1616 assert(VA.isRegLoc() && "Can only return in registers!");
1617 SDValue ValToCopy = OutVals[i];
1618 EVT ValVT = ValToCopy.getValueType();
1620 // Promote values to the appropriate types
1621 if (VA.getLocInfo() == CCValAssign::SExt)
1622 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1623 else if (VA.getLocInfo() == CCValAssign::ZExt)
1624 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1625 else if (VA.getLocInfo() == CCValAssign::AExt)
1626 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1627 else if (VA.getLocInfo() == CCValAssign::BCvt)
1628 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1630 // If this is x86-64, and we disabled SSE, we can't return FP values,
1631 // or SSE or MMX vectors.
1632 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1633 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1634 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1635 report_fatal_error("SSE register return with SSE disabled");
1637 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1638 // llvm-gcc has never done it right and no one has noticed, so this
1639 // should be OK for now.
1640 if (ValVT == MVT::f64 &&
1641 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1642 report_fatal_error("SSE2 register return with SSE2 disabled");
1644 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1645 // the RET instruction and handled by the FP Stackifier.
1646 if (VA.getLocReg() == X86::ST0 ||
1647 VA.getLocReg() == X86::ST1) {
1648 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1649 // change the value to the FP stack register class.
1650 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1651 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1652 RetOps.push_back(ValToCopy);
1653 // Don't emit a copytoreg.
1657 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1658 // which is returned in RAX / RDX.
1659 if (Subtarget->is64Bit()) {
1660 if (ValVT == MVT::x86mmx) {
1661 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1662 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1663 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1665 // If we don't have SSE2 available, convert to v4f32 so the generated
1666 // register is legal.
1667 if (!Subtarget->hasSSE2())
1668 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1673 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1674 Flag = Chain.getValue(1);
1675 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1678 // The x86-64 ABIs require that for returning structs by value we copy
1679 // the sret argument into %rax/%eax (depending on ABI) for the return.
1680 // Win32 requires us to put the sret argument to %eax as well.
1681 // We saved the argument into a virtual register in the entry block,
1682 // so now we copy the value out and into %rax/%eax.
1683 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1684 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1685 MachineFunction &MF = DAG.getMachineFunction();
1686 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1687 unsigned Reg = FuncInfo->getSRetReturnReg();
1689 "SRetReturnReg should have been set in LowerFormalArguments().");
1690 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1693 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1694 X86::RAX : X86::EAX;
1695 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1696 Flag = Chain.getValue(1);
1698 // RAX/EAX now acts like a return value.
1699 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1702 RetOps[0] = Chain; // Update chain.
1704 // Add the flag if we have it.
1706 RetOps.push_back(Flag);
1708 return DAG.getNode(X86ISD::RET_FLAG, dl,
1709 MVT::Other, &RetOps[0], RetOps.size());
1712 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1713 if (N->getNumValues() != 1)
1715 if (!N->hasNUsesOfValue(1, 0))
1718 SDValue TCChain = Chain;
1719 SDNode *Copy = *N->use_begin();
1720 if (Copy->getOpcode() == ISD::CopyToReg) {
1721 // If the copy has a glue operand, we conservatively assume it isn't safe to
1722 // perform a tail call.
1723 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1725 TCChain = Copy->getOperand(0);
1726 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1729 bool HasRet = false;
1730 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1732 if (UI->getOpcode() != X86ISD::RET_FLAG)
1745 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1746 ISD::NodeType ExtendKind) const {
1748 // TODO: Is this also valid on 32-bit?
1749 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1750 ReturnMVT = MVT::i8;
1752 ReturnMVT = MVT::i32;
1754 MVT MinVT = getRegisterType(ReturnMVT);
1755 return VT.bitsLT(MinVT) ? MinVT : VT;
1758 /// LowerCallResult - Lower the result values of a call into the
1759 /// appropriate copies out of appropriate physical registers.
1762 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1763 CallingConv::ID CallConv, bool isVarArg,
1764 const SmallVectorImpl<ISD::InputArg> &Ins,
1765 SDLoc dl, SelectionDAG &DAG,
1766 SmallVectorImpl<SDValue> &InVals) const {
1768 // Assign locations to each value returned by this call.
1769 SmallVector<CCValAssign, 16> RVLocs;
1770 bool Is64Bit = Subtarget->is64Bit();
1771 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1772 getTargetMachine(), RVLocs, *DAG.getContext());
1773 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1775 // Copy all of the result registers out of their specified physreg.
1776 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1777 CCValAssign &VA = RVLocs[i];
1778 EVT CopyVT = VA.getValVT();
1780 // If this is x86-64, and we disabled SSE, we can't return FP values
1781 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1782 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1783 report_fatal_error("SSE register return with SSE disabled");
1788 // If this is a call to a function that returns an fp value on the floating
1789 // point stack, we must guarantee the value is popped from the stack, so
1790 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1791 // if the return value is not used. We use the FpPOP_RETVAL instruction
1793 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1794 // If we prefer to use the value in xmm registers, copy it out as f80 and
1795 // use a truncate to move it from fp stack reg to xmm reg.
1796 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1797 SDValue Ops[] = { Chain, InFlag };
1798 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1799 MVT::Other, MVT::Glue, Ops), 1);
1800 Val = Chain.getValue(0);
1802 // Round the f80 to the right size, which also moves it to the appropriate
1804 if (CopyVT != VA.getValVT())
1805 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1806 // This truncation won't change the value.
1807 DAG.getIntPtrConstant(1));
1809 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1810 CopyVT, InFlag).getValue(1);
1811 Val = Chain.getValue(0);
1813 InFlag = Chain.getValue(2);
1814 InVals.push_back(Val);
1820 //===----------------------------------------------------------------------===//
1821 // C & StdCall & Fast Calling Convention implementation
1822 //===----------------------------------------------------------------------===//
1823 // StdCall calling convention seems to be standard for many Windows' API
1824 // routines and around. It differs from C calling convention just a little:
1825 // callee should clean up the stack, not caller. Symbols should be also
1826 // decorated in some fancy way :) It doesn't support any vector arguments.
1827 // For info on fast calling convention see Fast Calling Convention (tail call)
1828 // implementation LowerX86_32FastCCCallTo.
1830 /// CallIsStructReturn - Determines whether a call uses struct return
1832 enum StructReturnType {
1837 static StructReturnType
1838 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1840 return NotStructReturn;
1842 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1843 if (!Flags.isSRet())
1844 return NotStructReturn;
1845 if (Flags.isInReg())
1846 return RegStructReturn;
1847 return StackStructReturn;
1850 /// ArgsAreStructReturn - Determines whether a function uses struct
1851 /// return semantics.
1852 static StructReturnType
1853 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1855 return NotStructReturn;
1857 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1858 if (!Flags.isSRet())
1859 return NotStructReturn;
1860 if (Flags.isInReg())
1861 return RegStructReturn;
1862 return StackStructReturn;
1865 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1866 /// by "Src" to address "Dst" with size and alignment information specified by
1867 /// the specific parameter attribute. The copy will be passed as a byval
1868 /// function parameter.
1870 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1871 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1873 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1875 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1876 /*isVolatile*/false, /*AlwaysInline=*/true,
1877 MachinePointerInfo(), MachinePointerInfo());
1880 /// IsTailCallConvention - Return true if the calling convention is one that
1881 /// supports tail call optimization.
1882 static bool IsTailCallConvention(CallingConv::ID CC) {
1883 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1884 CC == CallingConv::HiPE);
1887 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1888 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1892 CallingConv::ID CalleeCC = CS.getCallingConv();
1893 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1899 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1900 /// a tailcall target by changing its ABI.
1901 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1902 bool GuaranteedTailCallOpt) {
1903 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1907 X86TargetLowering::LowerMemArgument(SDValue Chain,
1908 CallingConv::ID CallConv,
1909 const SmallVectorImpl<ISD::InputArg> &Ins,
1910 SDLoc dl, SelectionDAG &DAG,
1911 const CCValAssign &VA,
1912 MachineFrameInfo *MFI,
1914 // Create the nodes corresponding to a load from this parameter slot.
1915 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1916 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1917 getTargetMachine().Options.GuaranteedTailCallOpt);
1918 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1921 // If value is passed by pointer we have address passed instead of the value
1923 if (VA.getLocInfo() == CCValAssign::Indirect)
1924 ValVT = VA.getLocVT();
1926 ValVT = VA.getValVT();
1928 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1929 // changed with more analysis.
1930 // In case of tail call optimization mark all arguments mutable. Since they
1931 // could be overwritten by lowering of arguments in case of a tail call.
1932 if (Flags.isByVal()) {
1933 unsigned Bytes = Flags.getByValSize();
1934 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1935 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1936 return DAG.getFrameIndex(FI, getPointerTy());
1938 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1939 VA.getLocMemOffset(), isImmutable);
1940 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1941 return DAG.getLoad(ValVT, dl, Chain, FIN,
1942 MachinePointerInfo::getFixedStack(FI),
1943 false, false, false, 0);
1948 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1949 CallingConv::ID CallConv,
1951 const SmallVectorImpl<ISD::InputArg> &Ins,
1954 SmallVectorImpl<SDValue> &InVals)
1956 MachineFunction &MF = DAG.getMachineFunction();
1957 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1959 const Function* Fn = MF.getFunction();
1960 if (Fn->hasExternalLinkage() &&
1961 Subtarget->isTargetCygMing() &&
1962 Fn->getName() == "main")
1963 FuncInfo->setForceFramePointer(true);
1965 MachineFrameInfo *MFI = MF.getFrameInfo();
1966 bool Is64Bit = Subtarget->is64Bit();
1967 bool IsWindows = Subtarget->isTargetWindows();
1968 bool IsWin64 = Subtarget->isTargetWin64();
1970 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1971 "Var args not supported with calling convention fastcc, ghc or hipe");
1973 // Assign locations to all of the incoming arguments.
1974 SmallVector<CCValAssign, 16> ArgLocs;
1975 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1976 ArgLocs, *DAG.getContext());
1978 // Allocate shadow area for Win64
1980 CCInfo.AllocateStack(32, 8);
1983 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1985 unsigned LastVal = ~0U;
1987 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1988 CCValAssign &VA = ArgLocs[i];
1989 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1991 assert(VA.getValNo() != LastVal &&
1992 "Don't support value assigned to multiple locs yet");
1994 LastVal = VA.getValNo();
1996 if (VA.isRegLoc()) {
1997 EVT RegVT = VA.getLocVT();
1998 const TargetRegisterClass *RC;
1999 if (RegVT == MVT::i32)
2000 RC = &X86::GR32RegClass;
2001 else if (Is64Bit && RegVT == MVT::i64)
2002 RC = &X86::GR64RegClass;
2003 else if (RegVT == MVT::f32)
2004 RC = &X86::FR32RegClass;
2005 else if (RegVT == MVT::f64)
2006 RC = &X86::FR64RegClass;
2007 else if (RegVT.is256BitVector())
2008 RC = &X86::VR256RegClass;
2009 else if (RegVT.is128BitVector())
2010 RC = &X86::VR128RegClass;
2011 else if (RegVT == MVT::x86mmx)
2012 RC = &X86::VR64RegClass;
2014 llvm_unreachable("Unknown argument type!");
2016 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2017 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2019 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2020 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2022 if (VA.getLocInfo() == CCValAssign::SExt)
2023 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2024 DAG.getValueType(VA.getValVT()));
2025 else if (VA.getLocInfo() == CCValAssign::ZExt)
2026 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2027 DAG.getValueType(VA.getValVT()));
2028 else if (VA.getLocInfo() == CCValAssign::BCvt)
2029 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2031 if (VA.isExtInLoc()) {
2032 // Handle MMX values passed in XMM regs.
2033 if (RegVT.isVector())
2034 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2036 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2039 assert(VA.isMemLoc());
2040 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2043 // If value is passed via pointer - do a load.
2044 if (VA.getLocInfo() == CCValAssign::Indirect)
2045 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2046 MachinePointerInfo(), false, false, false, 0);
2048 InVals.push_back(ArgValue);
2051 // The x86-64 ABIs require that for returning structs by value we copy
2052 // the sret argument into %rax/%eax (depending on ABI) for the return.
2053 // Win32 requires us to put the sret argument to %eax as well.
2054 // Save the argument into a virtual register so that we can access it
2055 // from the return points.
2056 if (MF.getFunction()->hasStructRetAttr() &&
2057 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2058 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2059 unsigned Reg = FuncInfo->getSRetReturnReg();
2061 MVT PtrTy = getPointerTy();
2062 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2063 FuncInfo->setSRetReturnReg(Reg);
2065 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2066 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2069 unsigned StackSize = CCInfo.getNextStackOffset();
2070 // Align stack specially for tail calls.
2071 if (FuncIsMadeTailCallSafe(CallConv,
2072 MF.getTarget().Options.GuaranteedTailCallOpt))
2073 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2075 // If the function takes variable number of arguments, make a frame index for
2076 // the start of the first vararg value... for expansion of llvm.va_start.
2078 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2079 CallConv != CallingConv::X86_ThisCall)) {
2080 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2083 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2085 // FIXME: We should really autogenerate these arrays
2086 static const uint16_t GPR64ArgRegsWin64[] = {
2087 X86::RCX, X86::RDX, X86::R8, X86::R9
2089 static const uint16_t GPR64ArgRegs64Bit[] = {
2090 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2092 static const uint16_t XMMArgRegs64Bit[] = {
2093 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2094 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2096 const uint16_t *GPR64ArgRegs;
2097 unsigned NumXMMRegs = 0;
2100 // The XMM registers which might contain var arg parameters are shadowed
2101 // in their paired GPR. So we only need to save the GPR to their home
2103 TotalNumIntRegs = 4;
2104 GPR64ArgRegs = GPR64ArgRegsWin64;
2106 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2107 GPR64ArgRegs = GPR64ArgRegs64Bit;
2109 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2112 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2115 bool NoImplicitFloatOps = Fn->getAttributes().
2116 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2117 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2118 "SSE register cannot be used when SSE is disabled!");
2119 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2120 NoImplicitFloatOps) &&
2121 "SSE register cannot be used when SSE is disabled!");
2122 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2123 !Subtarget->hasSSE1())
2124 // Kernel mode asks for SSE to be disabled, so don't push them
2126 TotalNumXMMRegs = 0;
2129 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2130 // Get to the caller-allocated home save location. Add 8 to account
2131 // for the return address.
2132 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2133 FuncInfo->setRegSaveFrameIndex(
2134 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2135 // Fixup to set vararg frame on shadow area (4 x i64).
2137 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2139 // For X86-64, if there are vararg parameters that are passed via
2140 // registers, then we must store them to their spots on the stack so
2141 // they may be loaded by deferencing the result of va_next.
2142 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2143 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2144 FuncInfo->setRegSaveFrameIndex(
2145 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2149 // Store the integer parameter registers.
2150 SmallVector<SDValue, 8> MemOps;
2151 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2153 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2154 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2155 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2156 DAG.getIntPtrConstant(Offset));
2157 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2158 &X86::GR64RegClass);
2159 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2161 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2162 MachinePointerInfo::getFixedStack(
2163 FuncInfo->getRegSaveFrameIndex(), Offset),
2165 MemOps.push_back(Store);
2169 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2170 // Now store the XMM (fp + vector) parameter registers.
2171 SmallVector<SDValue, 11> SaveXMMOps;
2172 SaveXMMOps.push_back(Chain);
2174 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2175 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2176 SaveXMMOps.push_back(ALVal);
2178 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2179 FuncInfo->getRegSaveFrameIndex()));
2180 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2181 FuncInfo->getVarArgsFPOffset()));
2183 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2184 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2185 &X86::VR128RegClass);
2186 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2187 SaveXMMOps.push_back(Val);
2189 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2191 &SaveXMMOps[0], SaveXMMOps.size()));
2194 if (!MemOps.empty())
2195 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2196 &MemOps[0], MemOps.size());
2200 // Some CCs need callee pop.
2201 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2202 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2203 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2205 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2206 // If this is an sret function, the return should pop the hidden pointer.
2207 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2208 argsAreStructReturn(Ins) == StackStructReturn)
2209 FuncInfo->setBytesToPopOnReturn(4);
2213 // RegSaveFrameIndex is X86-64 only.
2214 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2215 if (CallConv == CallingConv::X86_FastCall ||
2216 CallConv == CallingConv::X86_ThisCall)
2217 // fastcc functions can't have varargs.
2218 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2221 FuncInfo->setArgumentStackSize(StackSize);
2227 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2228 SDValue StackPtr, SDValue Arg,
2229 SDLoc dl, SelectionDAG &DAG,
2230 const CCValAssign &VA,
2231 ISD::ArgFlagsTy Flags) const {
2232 unsigned LocMemOffset = VA.getLocMemOffset();
2233 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2234 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2235 if (Flags.isByVal())
2236 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2238 return DAG.getStore(Chain, dl, Arg, PtrOff,
2239 MachinePointerInfo::getStack(LocMemOffset),
2243 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2244 /// optimization is performed and it is required.
2246 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2247 SDValue &OutRetAddr, SDValue Chain,
2248 bool IsTailCall, bool Is64Bit,
2249 int FPDiff, SDLoc dl) const {
2250 // Adjust the Return address stack slot.
2251 EVT VT = getPointerTy();
2252 OutRetAddr = getReturnAddressFrameIndex(DAG);
2254 // Load the "old" Return address.
2255 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2256 false, false, false, 0);
2257 return SDValue(OutRetAddr.getNode(), 1);
2260 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2261 /// optimization is performed and it is required (FPDiff!=0).
2263 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2264 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2265 unsigned SlotSize, int FPDiff, SDLoc dl) {
2266 // Store the return address to the appropriate stack slot.
2267 if (!FPDiff) return Chain;
2268 // Calculate the new stack slot for the return address.
2269 int NewReturnAddrFI =
2270 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2271 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2272 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2273 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2279 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2280 SmallVectorImpl<SDValue> &InVals) const {
2281 SelectionDAG &DAG = CLI.DAG;
2283 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2284 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2285 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2286 SDValue Chain = CLI.Chain;
2287 SDValue Callee = CLI.Callee;
2288 CallingConv::ID CallConv = CLI.CallConv;
2289 bool &isTailCall = CLI.IsTailCall;
2290 bool isVarArg = CLI.IsVarArg;
2292 MachineFunction &MF = DAG.getMachineFunction();
2293 bool Is64Bit = Subtarget->is64Bit();
2294 bool IsWin64 = Subtarget->isTargetWin64();
2295 bool IsWindows = Subtarget->isTargetWindows();
2296 StructReturnType SR = callIsStructReturn(Outs);
2297 bool IsSibcall = false;
2299 if (MF.getTarget().Options.DisableTailCalls)
2303 // Check if it's really possible to do a tail call.
2304 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2305 isVarArg, SR != NotStructReturn,
2306 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2307 Outs, OutVals, Ins, DAG);
2309 // Sibcalls are automatically detected tailcalls which do not require
2311 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2318 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2319 "Var args not supported with calling convention fastcc, ghc or hipe");
2321 // Analyze operands of the call, assigning locations to each operand.
2322 SmallVector<CCValAssign, 16> ArgLocs;
2323 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2324 ArgLocs, *DAG.getContext());
2326 // Allocate shadow area for Win64
2328 CCInfo.AllocateStack(32, 8);
2331 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2333 // Get a count of how many bytes are to be pushed on the stack.
2334 unsigned NumBytes = CCInfo.getNextStackOffset();
2336 // This is a sibcall. The memory operands are available in caller's
2337 // own caller's stack.
2339 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2340 IsTailCallConvention(CallConv))
2341 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2344 if (isTailCall && !IsSibcall) {
2345 // Lower arguments at fp - stackoffset + fpdiff.
2346 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2347 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2349 FPDiff = NumBytesCallerPushed - NumBytes;
2351 // Set the delta of movement of the returnaddr stackslot.
2352 // But only set if delta is greater than previous delta.
2353 if (FPDiff < X86Info->getTCReturnAddrDelta())
2354 X86Info->setTCReturnAddrDelta(FPDiff);
2358 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2361 SDValue RetAddrFrIdx;
2362 // Load return address for tail calls.
2363 if (isTailCall && FPDiff)
2364 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2365 Is64Bit, FPDiff, dl);
2367 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2368 SmallVector<SDValue, 8> MemOpChains;
2371 // Walk the register/memloc assignments, inserting copies/loads. In the case
2372 // of tail call optimization arguments are handle later.
2373 const X86RegisterInfo *RegInfo =
2374 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2375 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2376 CCValAssign &VA = ArgLocs[i];
2377 EVT RegVT = VA.getLocVT();
2378 SDValue Arg = OutVals[i];
2379 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2380 bool isByVal = Flags.isByVal();
2382 // Promote the value if needed.
2383 switch (VA.getLocInfo()) {
2384 default: llvm_unreachable("Unknown loc info!");
2385 case CCValAssign::Full: break;
2386 case CCValAssign::SExt:
2387 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2389 case CCValAssign::ZExt:
2390 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2392 case CCValAssign::AExt:
2393 if (RegVT.is128BitVector()) {
2394 // Special case: passing MMX values in XMM registers.
2395 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2396 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2397 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2399 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2401 case CCValAssign::BCvt:
2402 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2404 case CCValAssign::Indirect: {
2405 // Store the argument.
2406 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2407 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2408 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2409 MachinePointerInfo::getFixedStack(FI),
2416 if (VA.isRegLoc()) {
2417 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2418 if (isVarArg && IsWin64) {
2419 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2420 // shadow reg if callee is a varargs function.
2421 unsigned ShadowReg = 0;
2422 switch (VA.getLocReg()) {
2423 case X86::XMM0: ShadowReg = X86::RCX; break;
2424 case X86::XMM1: ShadowReg = X86::RDX; break;
2425 case X86::XMM2: ShadowReg = X86::R8; break;
2426 case X86::XMM3: ShadowReg = X86::R9; break;
2429 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2431 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2432 assert(VA.isMemLoc());
2433 if (StackPtr.getNode() == 0)
2434 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2436 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2437 dl, DAG, VA, Flags));
2441 if (!MemOpChains.empty())
2442 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2443 &MemOpChains[0], MemOpChains.size());
2445 if (Subtarget->isPICStyleGOT()) {
2446 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2449 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2450 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2452 // If we are tail calling and generating PIC/GOT style code load the
2453 // address of the callee into ECX. The value in ecx is used as target of
2454 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2455 // for tail calls on PIC/GOT architectures. Normally we would just put the
2456 // address of GOT into ebx and then call target@PLT. But for tail calls
2457 // ebx would be restored (since ebx is callee saved) before jumping to the
2460 // Note: The actual moving to ECX is done further down.
2461 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2462 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2463 !G->getGlobal()->hasProtectedVisibility())
2464 Callee = LowerGlobalAddress(Callee, DAG);
2465 else if (isa<ExternalSymbolSDNode>(Callee))
2466 Callee = LowerExternalSymbol(Callee, DAG);
2470 if (Is64Bit && isVarArg && !IsWin64) {
2471 // From AMD64 ABI document:
2472 // For calls that may call functions that use varargs or stdargs
2473 // (prototype-less calls or calls to functions containing ellipsis (...) in
2474 // the declaration) %al is used as hidden argument to specify the number
2475 // of SSE registers used. The contents of %al do not need to match exactly
2476 // the number of registers, but must be an ubound on the number of SSE
2477 // registers used and is in the range 0 - 8 inclusive.
2479 // Count the number of XMM registers allocated.
2480 static const uint16_t XMMArgRegs[] = {
2481 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2482 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2484 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2485 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2486 && "SSE registers cannot be used when SSE is disabled");
2488 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2489 DAG.getConstant(NumXMMRegs, MVT::i8)));
2492 // For tail calls lower the arguments to the 'real' stack slot.
2494 // Force all the incoming stack arguments to be loaded from the stack
2495 // before any new outgoing arguments are stored to the stack, because the
2496 // outgoing stack slots may alias the incoming argument stack slots, and
2497 // the alias isn't otherwise explicit. This is slightly more conservative
2498 // than necessary, because it means that each store effectively depends
2499 // on every argument instead of just those arguments it would clobber.
2500 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2502 SmallVector<SDValue, 8> MemOpChains2;
2505 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2506 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2507 CCValAssign &VA = ArgLocs[i];
2510 assert(VA.isMemLoc());
2511 SDValue Arg = OutVals[i];
2512 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2513 // Create frame index.
2514 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2515 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2516 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2517 FIN = DAG.getFrameIndex(FI, getPointerTy());
2519 if (Flags.isByVal()) {
2520 // Copy relative to framepointer.
2521 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2522 if (StackPtr.getNode() == 0)
2523 StackPtr = DAG.getCopyFromReg(Chain, dl,
2524 RegInfo->getStackRegister(),
2526 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2528 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2532 // Store relative to framepointer.
2533 MemOpChains2.push_back(
2534 DAG.getStore(ArgChain, dl, Arg, FIN,
2535 MachinePointerInfo::getFixedStack(FI),
2541 if (!MemOpChains2.empty())
2542 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2543 &MemOpChains2[0], MemOpChains2.size());
2545 // Store the return address to the appropriate stack slot.
2546 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2547 getPointerTy(), RegInfo->getSlotSize(),
2551 // Build a sequence of copy-to-reg nodes chained together with token chain
2552 // and flag operands which copy the outgoing args into registers.
2554 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2555 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2556 RegsToPass[i].second, InFlag);
2557 InFlag = Chain.getValue(1);
2560 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2561 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2562 // In the 64-bit large code model, we have to make all calls
2563 // through a register, since the call instruction's 32-bit
2564 // pc-relative offset may not be large enough to hold the whole
2566 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2567 // If the callee is a GlobalAddress node (quite common, every direct call
2568 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2571 // We should use extra load for direct calls to dllimported functions in
2573 const GlobalValue *GV = G->getGlobal();
2574 if (!GV->hasDLLImportLinkage()) {
2575 unsigned char OpFlags = 0;
2576 bool ExtraLoad = false;
2577 unsigned WrapperKind = ISD::DELETED_NODE;
2579 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2580 // external symbols most go through the PLT in PIC mode. If the symbol
2581 // has hidden or protected visibility, or if it is static or local, then
2582 // we don't need to use the PLT - we can directly call it.
2583 if (Subtarget->isTargetELF() &&
2584 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2585 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2586 OpFlags = X86II::MO_PLT;
2587 } else if (Subtarget->isPICStyleStubAny() &&
2588 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2589 (!Subtarget->getTargetTriple().isMacOSX() ||
2590 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2591 // PC-relative references to external symbols should go through $stub,
2592 // unless we're building with the leopard linker or later, which
2593 // automatically synthesizes these stubs.
2594 OpFlags = X86II::MO_DARWIN_STUB;
2595 } else if (Subtarget->isPICStyleRIPRel() &&
2596 isa<Function>(GV) &&
2597 cast<Function>(GV)->getAttributes().
2598 hasAttribute(AttributeSet::FunctionIndex,
2599 Attribute::NonLazyBind)) {
2600 // If the function is marked as non-lazy, generate an indirect call
2601 // which loads from the GOT directly. This avoids runtime overhead
2602 // at the cost of eager binding (and one extra byte of encoding).
2603 OpFlags = X86II::MO_GOTPCREL;
2604 WrapperKind = X86ISD::WrapperRIP;
2608 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2609 G->getOffset(), OpFlags);
2611 // Add a wrapper if needed.
2612 if (WrapperKind != ISD::DELETED_NODE)
2613 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2614 // Add extra indirection if needed.
2616 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2617 MachinePointerInfo::getGOT(),
2618 false, false, false, 0);
2620 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2621 unsigned char OpFlags = 0;
2623 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2624 // external symbols should go through the PLT.
2625 if (Subtarget->isTargetELF() &&
2626 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2627 OpFlags = X86II::MO_PLT;
2628 } else if (Subtarget->isPICStyleStubAny() &&
2629 (!Subtarget->getTargetTriple().isMacOSX() ||
2630 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2631 // PC-relative references to external symbols should go through $stub,
2632 // unless we're building with the leopard linker or later, which
2633 // automatically synthesizes these stubs.
2634 OpFlags = X86II::MO_DARWIN_STUB;
2637 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2641 // Returns a chain & a flag for retval copy to use.
2642 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2643 SmallVector<SDValue, 8> Ops;
2645 if (!IsSibcall && isTailCall) {
2646 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2647 DAG.getIntPtrConstant(0, true), InFlag, dl);
2648 InFlag = Chain.getValue(1);
2651 Ops.push_back(Chain);
2652 Ops.push_back(Callee);
2655 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2657 // Add argument registers to the end of the list so that they are known live
2659 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2660 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2661 RegsToPass[i].second.getValueType()));
2663 // Add a register mask operand representing the call-preserved registers.
2664 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2665 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2666 assert(Mask && "Missing call preserved mask for calling convention");
2667 Ops.push_back(DAG.getRegisterMask(Mask));
2669 if (InFlag.getNode())
2670 Ops.push_back(InFlag);
2674 //// If this is the first return lowered for this function, add the regs
2675 //// to the liveout set for the function.
2676 // This isn't right, although it's probably harmless on x86; liveouts
2677 // should be computed from returns not tail calls. Consider a void
2678 // function making a tail call to a function returning int.
2679 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2682 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2683 InFlag = Chain.getValue(1);
2685 // Create the CALLSEQ_END node.
2686 unsigned NumBytesForCalleeToPush;
2687 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2688 getTargetMachine().Options.GuaranteedTailCallOpt))
2689 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2690 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2691 SR == StackStructReturn)
2692 // If this is a call to a struct-return function, the callee
2693 // pops the hidden struct pointer, so we have to push it back.
2694 // This is common for Darwin/X86, Linux & Mingw32 targets.
2695 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2696 NumBytesForCalleeToPush = 4;
2698 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2700 // Returns a flag for retval copy to use.
2702 Chain = DAG.getCALLSEQ_END(Chain,
2703 DAG.getIntPtrConstant(NumBytes, true),
2704 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2707 InFlag = Chain.getValue(1);
2710 // Handle result values, copying them out of physregs into vregs that we
2712 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2713 Ins, dl, DAG, InVals);
2716 //===----------------------------------------------------------------------===//
2717 // Fast Calling Convention (tail call) implementation
2718 //===----------------------------------------------------------------------===//
2720 // Like std call, callee cleans arguments, convention except that ECX is
2721 // reserved for storing the tail called function address. Only 2 registers are
2722 // free for argument passing (inreg). Tail call optimization is performed
2724 // * tailcallopt is enabled
2725 // * caller/callee are fastcc
2726 // On X86_64 architecture with GOT-style position independent code only local
2727 // (within module) calls are supported at the moment.
2728 // To keep the stack aligned according to platform abi the function
2729 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2730 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2731 // If a tail called function callee has more arguments than the caller the
2732 // caller needs to make sure that there is room to move the RETADDR to. This is
2733 // achieved by reserving an area the size of the argument delta right after the
2734 // original REtADDR, but before the saved framepointer or the spilled registers
2735 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2747 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2748 /// for a 16 byte align requirement.
2750 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2751 SelectionDAG& DAG) const {
2752 MachineFunction &MF = DAG.getMachineFunction();
2753 const TargetMachine &TM = MF.getTarget();
2754 const X86RegisterInfo *RegInfo =
2755 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2756 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2757 unsigned StackAlignment = TFI.getStackAlignment();
2758 uint64_t AlignMask = StackAlignment - 1;
2759 int64_t Offset = StackSize;
2760 unsigned SlotSize = RegInfo->getSlotSize();
2761 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2762 // Number smaller than 12 so just add the difference.
2763 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2765 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2766 Offset = ((~AlignMask) & Offset) + StackAlignment +
2767 (StackAlignment-SlotSize);
2772 /// MatchingStackOffset - Return true if the given stack call argument is
2773 /// already available in the same position (relatively) of the caller's
2774 /// incoming argument stack.
2776 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2777 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2778 const X86InstrInfo *TII) {
2779 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2781 if (Arg.getOpcode() == ISD::CopyFromReg) {
2782 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2783 if (!TargetRegisterInfo::isVirtualRegister(VR))
2785 MachineInstr *Def = MRI->getVRegDef(VR);
2788 if (!Flags.isByVal()) {
2789 if (!TII->isLoadFromStackSlot(Def, FI))
2792 unsigned Opcode = Def->getOpcode();
2793 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2794 Def->getOperand(1).isFI()) {
2795 FI = Def->getOperand(1).getIndex();
2796 Bytes = Flags.getByValSize();
2800 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2801 if (Flags.isByVal())
2802 // ByVal argument is passed in as a pointer but it's now being
2803 // dereferenced. e.g.
2804 // define @foo(%struct.X* %A) {
2805 // tail call @bar(%struct.X* byval %A)
2808 SDValue Ptr = Ld->getBasePtr();
2809 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2812 FI = FINode->getIndex();
2813 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2814 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2815 FI = FINode->getIndex();
2816 Bytes = Flags.getByValSize();
2820 assert(FI != INT_MAX);
2821 if (!MFI->isFixedObjectIndex(FI))
2823 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2826 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2827 /// for tail call optimization. Targets which want to do tail call
2828 /// optimization should implement this function.
2830 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2831 CallingConv::ID CalleeCC,
2833 bool isCalleeStructRet,
2834 bool isCallerStructRet,
2836 const SmallVectorImpl<ISD::OutputArg> &Outs,
2837 const SmallVectorImpl<SDValue> &OutVals,
2838 const SmallVectorImpl<ISD::InputArg> &Ins,
2839 SelectionDAG &DAG) const {
2840 if (!IsTailCallConvention(CalleeCC) &&
2841 CalleeCC != CallingConv::C)
2844 // If -tailcallopt is specified, make fastcc functions tail-callable.
2845 const MachineFunction &MF = DAG.getMachineFunction();
2846 const Function *CallerF = DAG.getMachineFunction().getFunction();
2848 // If the function return type is x86_fp80 and the callee return type is not,
2849 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2850 // perform a tailcall optimization here.
2851 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2854 CallingConv::ID CallerCC = CallerF->getCallingConv();
2855 bool CCMatch = CallerCC == CalleeCC;
2857 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2858 if (IsTailCallConvention(CalleeCC) && CCMatch)
2863 // Look for obvious safe cases to perform tail call optimization that do not
2864 // require ABI changes. This is what gcc calls sibcall.
2866 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2867 // emit a special epilogue.
2868 const X86RegisterInfo *RegInfo =
2869 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2870 if (RegInfo->needsStackRealignment(MF))
2873 // Also avoid sibcall optimization if either caller or callee uses struct
2874 // return semantics.
2875 if (isCalleeStructRet || isCallerStructRet)
2878 // An stdcall caller is expected to clean up its arguments; the callee
2879 // isn't going to do that.
2880 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2883 // Do not sibcall optimize vararg calls unless all arguments are passed via
2885 if (isVarArg && !Outs.empty()) {
2887 // Optimizing for varargs on Win64 is unlikely to be safe without
2888 // additional testing.
2889 if (Subtarget->isTargetWin64())
2892 SmallVector<CCValAssign, 16> ArgLocs;
2893 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2894 getTargetMachine(), ArgLocs, *DAG.getContext());
2896 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2897 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2898 if (!ArgLocs[i].isRegLoc())
2902 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2903 // stack. Therefore, if it's not used by the call it is not safe to optimize
2904 // this into a sibcall.
2905 bool Unused = false;
2906 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2913 SmallVector<CCValAssign, 16> RVLocs;
2914 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2915 getTargetMachine(), RVLocs, *DAG.getContext());
2916 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2917 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2918 CCValAssign &VA = RVLocs[i];
2919 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2924 // If the calling conventions do not match, then we'd better make sure the
2925 // results are returned in the same way as what the caller expects.
2927 SmallVector<CCValAssign, 16> RVLocs1;
2928 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2929 getTargetMachine(), RVLocs1, *DAG.getContext());
2930 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2932 SmallVector<CCValAssign, 16> RVLocs2;
2933 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2934 getTargetMachine(), RVLocs2, *DAG.getContext());
2935 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2937 if (RVLocs1.size() != RVLocs2.size())
2939 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2940 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2942 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2944 if (RVLocs1[i].isRegLoc()) {
2945 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2948 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2954 // If the callee takes no arguments then go on to check the results of the
2956 if (!Outs.empty()) {
2957 // Check if stack adjustment is needed. For now, do not do this if any
2958 // argument is passed on the stack.
2959 SmallVector<CCValAssign, 16> ArgLocs;
2960 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2961 getTargetMachine(), ArgLocs, *DAG.getContext());
2963 // Allocate shadow area for Win64
2964 if (Subtarget->isTargetWin64()) {
2965 CCInfo.AllocateStack(32, 8);
2968 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2969 if (CCInfo.getNextStackOffset()) {
2970 MachineFunction &MF = DAG.getMachineFunction();
2971 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2974 // Check if the arguments are already laid out in the right way as
2975 // the caller's fixed stack objects.
2976 MachineFrameInfo *MFI = MF.getFrameInfo();
2977 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2978 const X86InstrInfo *TII =
2979 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2980 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2981 CCValAssign &VA = ArgLocs[i];
2982 SDValue Arg = OutVals[i];
2983 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2984 if (VA.getLocInfo() == CCValAssign::Indirect)
2986 if (!VA.isRegLoc()) {
2987 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2994 // If the tailcall address may be in a register, then make sure it's
2995 // possible to register allocate for it. In 32-bit, the call address can
2996 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2997 // callee-saved registers are restored. These happen to be the same
2998 // registers used to pass 'inreg' arguments so watch out for those.
2999 if (!Subtarget->is64Bit() &&
3000 ((!isa<GlobalAddressSDNode>(Callee) &&
3001 !isa<ExternalSymbolSDNode>(Callee)) ||
3002 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3003 unsigned NumInRegs = 0;
3004 // In PIC we need an extra register to formulate the address computation
3006 unsigned MaxInRegs =
3007 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3009 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3010 CCValAssign &VA = ArgLocs[i];
3013 unsigned Reg = VA.getLocReg();
3016 case X86::EAX: case X86::EDX: case X86::ECX:
3017 if (++NumInRegs == MaxInRegs)
3029 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3030 const TargetLibraryInfo *libInfo) const {
3031 return X86::createFastISel(funcInfo, libInfo);
3034 //===----------------------------------------------------------------------===//
3035 // Other Lowering Hooks
3036 //===----------------------------------------------------------------------===//
3038 static bool MayFoldLoad(SDValue Op) {
3039 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3042 static bool MayFoldIntoStore(SDValue Op) {
3043 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3046 static bool isTargetShuffle(unsigned Opcode) {
3048 default: return false;
3049 case X86ISD::PSHUFD:
3050 case X86ISD::PSHUFHW:
3051 case X86ISD::PSHUFLW:
3053 case X86ISD::PALIGNR:
3054 case X86ISD::MOVLHPS:
3055 case X86ISD::MOVLHPD:
3056 case X86ISD::MOVHLPS:
3057 case X86ISD::MOVLPS:
3058 case X86ISD::MOVLPD:
3059 case X86ISD::MOVSHDUP:
3060 case X86ISD::MOVSLDUP:
3061 case X86ISD::MOVDDUP:
3064 case X86ISD::UNPCKL:
3065 case X86ISD::UNPCKH:
3066 case X86ISD::VPERMILP:
3067 case X86ISD::VPERM2X128:
3068 case X86ISD::VPERMI:
3073 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3074 SDValue V1, SelectionDAG &DAG) {
3076 default: llvm_unreachable("Unknown x86 shuffle node");
3077 case X86ISD::MOVSHDUP:
3078 case X86ISD::MOVSLDUP:
3079 case X86ISD::MOVDDUP:
3080 return DAG.getNode(Opc, dl, VT, V1);
3084 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3085 SDValue V1, unsigned TargetMask,
3086 SelectionDAG &DAG) {
3088 default: llvm_unreachable("Unknown x86 shuffle node");
3089 case X86ISD::PSHUFD:
3090 case X86ISD::PSHUFHW:
3091 case X86ISD::PSHUFLW:
3092 case X86ISD::VPERMILP:
3093 case X86ISD::VPERMI:
3094 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3098 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3099 SDValue V1, SDValue V2, unsigned TargetMask,
3100 SelectionDAG &DAG) {
3102 default: llvm_unreachable("Unknown x86 shuffle node");
3103 case X86ISD::PALIGNR:
3105 case X86ISD::VPERM2X128:
3106 return DAG.getNode(Opc, dl, VT, V1, V2,
3107 DAG.getConstant(TargetMask, MVT::i8));
3111 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3112 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3114 default: llvm_unreachable("Unknown x86 shuffle node");
3115 case X86ISD::MOVLHPS:
3116 case X86ISD::MOVLHPD:
3117 case X86ISD::MOVHLPS:
3118 case X86ISD::MOVLPS:
3119 case X86ISD::MOVLPD:
3122 case X86ISD::UNPCKL:
3123 case X86ISD::UNPCKH:
3124 return DAG.getNode(Opc, dl, VT, V1, V2);
3128 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3129 MachineFunction &MF = DAG.getMachineFunction();
3130 const X86RegisterInfo *RegInfo =
3131 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3132 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3133 int ReturnAddrIndex = FuncInfo->getRAIndex();
3135 if (ReturnAddrIndex == 0) {
3136 // Set up a frame object for the return address.
3137 unsigned SlotSize = RegInfo->getSlotSize();
3138 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3140 FuncInfo->setRAIndex(ReturnAddrIndex);
3143 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3146 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3147 bool hasSymbolicDisplacement) {
3148 // Offset should fit into 32 bit immediate field.
3149 if (!isInt<32>(Offset))
3152 // If we don't have a symbolic displacement - we don't have any extra
3154 if (!hasSymbolicDisplacement)
3157 // FIXME: Some tweaks might be needed for medium code model.
3158 if (M != CodeModel::Small && M != CodeModel::Kernel)
3161 // For small code model we assume that latest object is 16MB before end of 31
3162 // bits boundary. We may also accept pretty large negative constants knowing
3163 // that all objects are in the positive half of address space.
3164 if (M == CodeModel::Small && Offset < 16*1024*1024)
3167 // For kernel code model we know that all object resist in the negative half
3168 // of 32bits address space. We may not accept negative offsets, since they may
3169 // be just off and we may accept pretty large positive ones.
3170 if (M == CodeModel::Kernel && Offset > 0)
3176 /// isCalleePop - Determines whether the callee is required to pop its
3177 /// own arguments. Callee pop is necessary to support tail calls.
3178 bool X86::isCalleePop(CallingConv::ID CallingConv,
3179 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3183 switch (CallingConv) {
3186 case CallingConv::X86_StdCall:
3188 case CallingConv::X86_FastCall:
3190 case CallingConv::X86_ThisCall:
3192 case CallingConv::Fast:
3194 case CallingConv::GHC:
3196 case CallingConv::HiPE:
3201 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3202 /// specific condition code, returning the condition code and the LHS/RHS of the
3203 /// comparison to make.
3204 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3205 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3207 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3208 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3209 // X > -1 -> X == 0, jump !sign.
3210 RHS = DAG.getConstant(0, RHS.getValueType());
3211 return X86::COND_NS;
3213 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3214 // X < 0 -> X == 0, jump on sign.
3217 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3219 RHS = DAG.getConstant(0, RHS.getValueType());
3220 return X86::COND_LE;
3224 switch (SetCCOpcode) {
3225 default: llvm_unreachable("Invalid integer condition!");
3226 case ISD::SETEQ: return X86::COND_E;
3227 case ISD::SETGT: return X86::COND_G;
3228 case ISD::SETGE: return X86::COND_GE;
3229 case ISD::SETLT: return X86::COND_L;
3230 case ISD::SETLE: return X86::COND_LE;
3231 case ISD::SETNE: return X86::COND_NE;
3232 case ISD::SETULT: return X86::COND_B;
3233 case ISD::SETUGT: return X86::COND_A;
3234 case ISD::SETULE: return X86::COND_BE;
3235 case ISD::SETUGE: return X86::COND_AE;
3239 // First determine if it is required or is profitable to flip the operands.
3241 // If LHS is a foldable load, but RHS is not, flip the condition.
3242 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3243 !ISD::isNON_EXTLoad(RHS.getNode())) {
3244 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3245 std::swap(LHS, RHS);
3248 switch (SetCCOpcode) {
3254 std::swap(LHS, RHS);
3258 // On a floating point condition, the flags are set as follows:
3260 // 0 | 0 | 0 | X > Y
3261 // 0 | 0 | 1 | X < Y
3262 // 1 | 0 | 0 | X == Y
3263 // 1 | 1 | 1 | unordered
3264 switch (SetCCOpcode) {
3265 default: llvm_unreachable("Condcode should be pre-legalized away");
3267 case ISD::SETEQ: return X86::COND_E;
3268 case ISD::SETOLT: // flipped
3270 case ISD::SETGT: return X86::COND_A;
3271 case ISD::SETOLE: // flipped
3273 case ISD::SETGE: return X86::COND_AE;
3274 case ISD::SETUGT: // flipped
3276 case ISD::SETLT: return X86::COND_B;
3277 case ISD::SETUGE: // flipped
3279 case ISD::SETLE: return X86::COND_BE;
3281 case ISD::SETNE: return X86::COND_NE;
3282 case ISD::SETUO: return X86::COND_P;
3283 case ISD::SETO: return X86::COND_NP;
3285 case ISD::SETUNE: return X86::COND_INVALID;
3289 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3290 /// code. Current x86 isa includes the following FP cmov instructions:
3291 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3292 static bool hasFPCMov(unsigned X86CC) {
3308 /// isFPImmLegal - Returns true if the target can instruction select the
3309 /// specified FP immediate natively. If false, the legalizer will
3310 /// materialize the FP immediate as a load from a constant pool.
3311 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3312 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3313 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3319 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3320 /// the specified range (L, H].
3321 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3322 return (Val < 0) || (Val >= Low && Val < Hi);
3325 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3326 /// specified value.
3327 static bool isUndefOrEqual(int Val, int CmpVal) {
3328 return (Val < 0 || Val == CmpVal);
3331 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3332 /// from position Pos and ending in Pos+Size, falls within the specified
3333 /// sequential range (L, L+Pos]. or is undef.
3334 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3335 unsigned Pos, unsigned Size, int Low) {
3336 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3337 if (!isUndefOrEqual(Mask[i], Low))
3342 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3343 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3344 /// the second operand.
3345 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3346 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3347 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3348 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3349 return (Mask[0] < 2 && Mask[1] < 2);
3353 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3354 /// is suitable for input to PSHUFHW.
3355 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3356 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3359 // Lower quadword copied in order or undef.
3360 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3363 // Upper quadword shuffled.
3364 for (unsigned i = 4; i != 8; ++i)
3365 if (!isUndefOrInRange(Mask[i], 4, 8))
3368 if (VT == MVT::v16i16) {
3369 // Lower quadword copied in order or undef.
3370 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3373 // Upper quadword shuffled.
3374 for (unsigned i = 12; i != 16; ++i)
3375 if (!isUndefOrInRange(Mask[i], 12, 16))
3382 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3383 /// is suitable for input to PSHUFLW.
3384 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3385 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3388 // Upper quadword copied in order.
3389 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3392 // Lower quadword shuffled.
3393 for (unsigned i = 0; i != 4; ++i)
3394 if (!isUndefOrInRange(Mask[i], 0, 4))
3397 if (VT == MVT::v16i16) {
3398 // Upper quadword copied in order.
3399 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3402 // Lower quadword shuffled.
3403 for (unsigned i = 8; i != 12; ++i)
3404 if (!isUndefOrInRange(Mask[i], 8, 12))
3411 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3412 /// is suitable for input to PALIGNR.
3413 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3414 const X86Subtarget *Subtarget) {
3415 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3416 (VT.is256BitVector() && !Subtarget->hasInt256()))
3419 unsigned NumElts = VT.getVectorNumElements();
3420 unsigned NumLanes = VT.getSizeInBits()/128;
3421 unsigned NumLaneElts = NumElts/NumLanes;
3423 // Do not handle 64-bit element shuffles with palignr.
3424 if (NumLaneElts == 2)
3427 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3429 for (i = 0; i != NumLaneElts; ++i) {
3434 // Lane is all undef, go to next lane
3435 if (i == NumLaneElts)
3438 int Start = Mask[i+l];
3440 // Make sure its in this lane in one of the sources
3441 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3442 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3445 // If not lane 0, then we must match lane 0
3446 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3449 // Correct second source to be contiguous with first source
3450 if (Start >= (int)NumElts)
3451 Start -= NumElts - NumLaneElts;
3453 // Make sure we're shifting in the right direction.
3454 if (Start <= (int)(i+l))
3459 // Check the rest of the elements to see if they are consecutive.
3460 for (++i; i != NumLaneElts; ++i) {
3461 int Idx = Mask[i+l];
3463 // Make sure its in this lane
3464 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3465 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3468 // If not lane 0, then we must match lane 0
3469 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3472 if (Idx >= (int)NumElts)
3473 Idx -= NumElts - NumLaneElts;
3475 if (!isUndefOrEqual(Idx, Start+i))
3484 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3485 /// the two vector operands have swapped position.
3486 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3487 unsigned NumElems) {
3488 for (unsigned i = 0; i != NumElems; ++i) {
3492 else if (idx < (int)NumElems)
3493 Mask[i] = idx + NumElems;
3495 Mask[i] = idx - NumElems;
3499 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3500 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3501 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3502 /// reverse of what x86 shuffles want.
3503 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3504 bool Commuted = false) {
3505 if (!HasFp256 && VT.is256BitVector())
3508 unsigned NumElems = VT.getVectorNumElements();
3509 unsigned NumLanes = VT.getSizeInBits()/128;
3510 unsigned NumLaneElems = NumElems/NumLanes;
3512 if (NumLaneElems != 2 && NumLaneElems != 4)
3515 // VSHUFPSY divides the resulting vector into 4 chunks.
3516 // The sources are also splitted into 4 chunks, and each destination
3517 // chunk must come from a different source chunk.
3519 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3520 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3522 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3523 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3525 // VSHUFPDY divides the resulting vector into 4 chunks.
3526 // The sources are also splitted into 4 chunks, and each destination
3527 // chunk must come from a different source chunk.
3529 // SRC1 => X3 X2 X1 X0
3530 // SRC2 => Y3 Y2 Y1 Y0
3532 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3534 unsigned HalfLaneElems = NumLaneElems/2;
3535 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3536 for (unsigned i = 0; i != NumLaneElems; ++i) {
3537 int Idx = Mask[i+l];
3538 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3539 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3541 // For VSHUFPSY, the mask of the second half must be the same as the
3542 // first but with the appropriate offsets. This works in the same way as
3543 // VPERMILPS works with masks.
3544 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3546 if (!isUndefOrEqual(Idx, Mask[i]+l))
3554 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3555 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3556 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3557 if (!VT.is128BitVector())
3560 unsigned NumElems = VT.getVectorNumElements();
3565 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3566 return isUndefOrEqual(Mask[0], 6) &&
3567 isUndefOrEqual(Mask[1], 7) &&
3568 isUndefOrEqual(Mask[2], 2) &&
3569 isUndefOrEqual(Mask[3], 3);
3572 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3573 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3575 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3576 if (!VT.is128BitVector())
3579 unsigned NumElems = VT.getVectorNumElements();
3584 return isUndefOrEqual(Mask[0], 2) &&
3585 isUndefOrEqual(Mask[1], 3) &&
3586 isUndefOrEqual(Mask[2], 2) &&
3587 isUndefOrEqual(Mask[3], 3);
3590 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3591 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3592 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3593 if (!VT.is128BitVector())
3596 unsigned NumElems = VT.getVectorNumElements();
3598 if (NumElems != 2 && NumElems != 4)
3601 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3602 if (!isUndefOrEqual(Mask[i], i + NumElems))
3605 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3606 if (!isUndefOrEqual(Mask[i], i))
3612 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3613 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3614 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3615 if (!VT.is128BitVector())
3618 unsigned NumElems = VT.getVectorNumElements();
3620 if (NumElems != 2 && NumElems != 4)
3623 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3624 if (!isUndefOrEqual(Mask[i], i))
3627 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3628 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3635 // Some special combinations that can be optimized.
3638 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3639 SelectionDAG &DAG) {
3640 MVT VT = SVOp->getValueType(0).getSimpleVT();
3643 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3646 ArrayRef<int> Mask = SVOp->getMask();
3648 // These are the special masks that may be optimized.
3649 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3650 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3651 bool MatchEvenMask = true;
3652 bool MatchOddMask = true;
3653 for (int i=0; i<8; ++i) {
3654 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3655 MatchEvenMask = false;
3656 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3657 MatchOddMask = false;
3660 if (!MatchEvenMask && !MatchOddMask)
3663 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3665 SDValue Op0 = SVOp->getOperand(0);
3666 SDValue Op1 = SVOp->getOperand(1);
3668 if (MatchEvenMask) {
3669 // Shift the second operand right to 32 bits.
3670 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3671 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3673 // Shift the first operand left to 32 bits.
3674 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3675 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3677 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3678 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3681 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3682 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3683 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3684 bool HasInt256, bool V2IsSplat = false) {
3685 unsigned NumElts = VT.getVectorNumElements();
3687 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3688 "Unsupported vector type for unpckh");
3690 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3691 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3694 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3695 // independently on 128-bit lanes.
3696 unsigned NumLanes = VT.getSizeInBits()/128;
3697 unsigned NumLaneElts = NumElts/NumLanes;
3699 for (unsigned l = 0; l != NumLanes; ++l) {
3700 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3701 i != (l+1)*NumLaneElts;
3704 int BitI1 = Mask[i+1];
3705 if (!isUndefOrEqual(BitI, j))
3708 if (!isUndefOrEqual(BitI1, NumElts))
3711 if (!isUndefOrEqual(BitI1, j + NumElts))
3720 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3721 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3722 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3723 bool HasInt256, bool V2IsSplat = false) {
3724 unsigned NumElts = VT.getVectorNumElements();
3726 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3727 "Unsupported vector type for unpckh");
3729 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3730 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3733 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3734 // independently on 128-bit lanes.
3735 unsigned NumLanes = VT.getSizeInBits()/128;
3736 unsigned NumLaneElts = NumElts/NumLanes;
3738 for (unsigned l = 0; l != NumLanes; ++l) {
3739 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3740 i != (l+1)*NumLaneElts; i += 2, ++j) {
3742 int BitI1 = Mask[i+1];
3743 if (!isUndefOrEqual(BitI, j))
3746 if (isUndefOrEqual(BitI1, NumElts))
3749 if (!isUndefOrEqual(BitI1, j+NumElts))
3757 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3758 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3760 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3761 unsigned NumElts = VT.getVectorNumElements();
3762 bool Is256BitVec = VT.is256BitVector();
3764 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3765 "Unsupported vector type for unpckh");
3767 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3768 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3771 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3772 // FIXME: Need a better way to get rid of this, there's no latency difference
3773 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3774 // the former later. We should also remove the "_undef" special mask.
3775 if (NumElts == 4 && Is256BitVec)
3778 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3779 // independently on 128-bit lanes.
3780 unsigned NumLanes = VT.getSizeInBits()/128;
3781 unsigned NumLaneElts = NumElts/NumLanes;
3783 for (unsigned l = 0; l != NumLanes; ++l) {
3784 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3785 i != (l+1)*NumLaneElts;
3788 int BitI1 = Mask[i+1];
3790 if (!isUndefOrEqual(BitI, j))
3792 if (!isUndefOrEqual(BitI1, j))
3800 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3801 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3803 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3804 unsigned NumElts = VT.getVectorNumElements();
3806 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3807 "Unsupported vector type for unpckh");
3809 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3810 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3813 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3814 // independently on 128-bit lanes.
3815 unsigned NumLanes = VT.getSizeInBits()/128;
3816 unsigned NumLaneElts = NumElts/NumLanes;
3818 for (unsigned l = 0; l != NumLanes; ++l) {
3819 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3820 i != (l+1)*NumLaneElts; i += 2, ++j) {
3822 int BitI1 = Mask[i+1];
3823 if (!isUndefOrEqual(BitI, j))
3825 if (!isUndefOrEqual(BitI1, j))
3832 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3833 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3834 /// MOVSD, and MOVD, i.e. setting the lowest element.
3835 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3836 if (VT.getVectorElementType().getSizeInBits() < 32)
3838 if (!VT.is128BitVector())
3841 unsigned NumElts = VT.getVectorNumElements();
3843 if (!isUndefOrEqual(Mask[0], NumElts))
3846 for (unsigned i = 1; i != NumElts; ++i)
3847 if (!isUndefOrEqual(Mask[i], i))
3853 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3854 /// as permutations between 128-bit chunks or halves. As an example: this
3856 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3857 /// The first half comes from the second half of V1 and the second half from the
3858 /// the second half of V2.
3859 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3860 if (!HasFp256 || !VT.is256BitVector())
3863 // The shuffle result is divided into half A and half B. In total the two
3864 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3865 // B must come from C, D, E or F.
3866 unsigned HalfSize = VT.getVectorNumElements()/2;
3867 bool MatchA = false, MatchB = false;
3869 // Check if A comes from one of C, D, E, F.
3870 for (unsigned Half = 0; Half != 4; ++Half) {
3871 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3877 // Check if B comes from one of C, D, E, F.
3878 for (unsigned Half = 0; Half != 4; ++Half) {
3879 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3885 return MatchA && MatchB;
3888 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3889 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3890 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3891 MVT VT = SVOp->getValueType(0).getSimpleVT();
3893 unsigned HalfSize = VT.getVectorNumElements()/2;
3895 unsigned FstHalf = 0, SndHalf = 0;
3896 for (unsigned i = 0; i < HalfSize; ++i) {
3897 if (SVOp->getMaskElt(i) > 0) {
3898 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3902 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3903 if (SVOp->getMaskElt(i) > 0) {
3904 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3909 return (FstHalf | (SndHalf << 4));
3912 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3914 /// Note that VPERMIL mask matching is different depending whether theunderlying
3915 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3916 /// to the same elements of the low, but to the higher half of the source.
3917 /// In VPERMILPD the two lanes could be shuffled independently of each other
3918 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3919 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3923 unsigned NumElts = VT.getVectorNumElements();
3924 // Only match 256-bit with 32/64-bit types
3925 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3928 unsigned NumLanes = VT.getSizeInBits()/128;
3929 unsigned LaneSize = NumElts/NumLanes;
3930 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3931 for (unsigned i = 0; i != LaneSize; ++i) {
3932 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3934 if (NumElts != 8 || l == 0)
3936 // VPERMILPS handling
3939 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3947 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3948 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3949 /// element of vector 2 and the other elements to come from vector 1 in order.
3950 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3951 bool V2IsSplat = false, bool V2IsUndef = false) {
3952 if (!VT.is128BitVector())
3955 unsigned NumOps = VT.getVectorNumElements();
3956 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3959 if (!isUndefOrEqual(Mask[0], 0))
3962 for (unsigned i = 1; i != NumOps; ++i)
3963 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3964 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3965 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3971 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3973 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3974 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3975 const X86Subtarget *Subtarget) {
3976 if (!Subtarget->hasSSE3())
3979 unsigned NumElems = VT.getVectorNumElements();
3981 if ((VT.is128BitVector() && NumElems != 4) ||
3982 (VT.is256BitVector() && NumElems != 8))
3985 // "i+1" is the value the indexed mask element must have
3986 for (unsigned i = 0; i != NumElems; i += 2)
3987 if (!isUndefOrEqual(Mask[i], i+1) ||
3988 !isUndefOrEqual(Mask[i+1], i+1))
3994 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3995 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3996 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3997 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3998 const X86Subtarget *Subtarget) {
3999 if (!Subtarget->hasSSE3())
4002 unsigned NumElems = VT.getVectorNumElements();
4004 if ((VT.is128BitVector() && NumElems != 4) ||
4005 (VT.is256BitVector() && NumElems != 8))
4008 // "i" is the value the indexed mask element must have
4009 for (unsigned i = 0; i != NumElems; i += 2)
4010 if (!isUndefOrEqual(Mask[i], i) ||
4011 !isUndefOrEqual(Mask[i+1], i))
4017 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4018 /// specifies a shuffle of elements that is suitable for input to 256-bit
4019 /// version of MOVDDUP.
4020 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4021 if (!HasFp256 || !VT.is256BitVector())
4024 unsigned NumElts = VT.getVectorNumElements();
4028 for (unsigned i = 0; i != NumElts/2; ++i)
4029 if (!isUndefOrEqual(Mask[i], 0))
4031 for (unsigned i = NumElts/2; i != NumElts; ++i)
4032 if (!isUndefOrEqual(Mask[i], NumElts/2))
4037 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4038 /// specifies a shuffle of elements that is suitable for input to 128-bit
4039 /// version of MOVDDUP.
4040 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4041 if (!VT.is128BitVector())
4044 unsigned e = VT.getVectorNumElements() / 2;
4045 for (unsigned i = 0; i != e; ++i)
4046 if (!isUndefOrEqual(Mask[i], i))
4048 for (unsigned i = 0; i != e; ++i)
4049 if (!isUndefOrEqual(Mask[e+i], i))
4054 /// isVEXTRACTF128Index - Return true if the specified
4055 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4056 /// suitable for input to VEXTRACTF128.
4057 bool X86::isVEXTRACTF128Index(SDNode *N) {
4058 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4061 // The index should be aligned on a 128-bit boundary.
4063 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4065 MVT VT = N->getValueType(0).getSimpleVT();
4066 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4067 bool Result = (Index * ElSize) % 128 == 0;
4072 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4073 /// operand specifies a subvector insert that is suitable for input to
4075 bool X86::isVINSERTF128Index(SDNode *N) {
4076 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4079 // The index should be aligned on a 128-bit boundary.
4081 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4083 MVT VT = N->getValueType(0).getSimpleVT();
4084 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4085 bool Result = (Index * ElSize) % 128 == 0;
4090 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4091 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4092 /// Handles 128-bit and 256-bit.
4093 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4094 MVT VT = N->getValueType(0).getSimpleVT();
4096 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4097 "Unsupported vector type for PSHUF/SHUFP");
4099 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4100 // independently on 128-bit lanes.
4101 unsigned NumElts = VT.getVectorNumElements();
4102 unsigned NumLanes = VT.getSizeInBits()/128;
4103 unsigned NumLaneElts = NumElts/NumLanes;
4105 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4106 "Only supports 2 or 4 elements per lane");
4108 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4110 for (unsigned i = 0; i != NumElts; ++i) {
4111 int Elt = N->getMaskElt(i);
4112 if (Elt < 0) continue;
4113 Elt &= NumLaneElts - 1;
4114 unsigned ShAmt = (i << Shift) % 8;
4115 Mask |= Elt << ShAmt;
4121 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4122 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4123 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4124 MVT VT = N->getValueType(0).getSimpleVT();
4126 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4127 "Unsupported vector type for PSHUFHW");
4129 unsigned NumElts = VT.getVectorNumElements();
4132 for (unsigned l = 0; l != NumElts; l += 8) {
4133 // 8 nodes per lane, but we only care about the last 4.
4134 for (unsigned i = 0; i < 4; ++i) {
4135 int Elt = N->getMaskElt(l+i+4);
4136 if (Elt < 0) continue;
4137 Elt &= 0x3; // only 2-bits.
4138 Mask |= Elt << (i * 2);
4145 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4146 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4147 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4148 MVT VT = N->getValueType(0).getSimpleVT();
4150 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4151 "Unsupported vector type for PSHUFHW");
4153 unsigned NumElts = VT.getVectorNumElements();
4156 for (unsigned l = 0; l != NumElts; l += 8) {
4157 // 8 nodes per lane, but we only care about the first 4.
4158 for (unsigned i = 0; i < 4; ++i) {
4159 int Elt = N->getMaskElt(l+i);
4160 if (Elt < 0) continue;
4161 Elt &= 0x3; // only 2-bits
4162 Mask |= Elt << (i * 2);
4169 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4170 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4171 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4172 MVT VT = SVOp->getValueType(0).getSimpleVT();
4173 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4175 unsigned NumElts = VT.getVectorNumElements();
4176 unsigned NumLanes = VT.getSizeInBits()/128;
4177 unsigned NumLaneElts = NumElts/NumLanes;
4181 for (i = 0; i != NumElts; ++i) {
4182 Val = SVOp->getMaskElt(i);
4186 if (Val >= (int)NumElts)
4187 Val -= NumElts - NumLaneElts;
4189 assert(Val - i > 0 && "PALIGNR imm should be positive");
4190 return (Val - i) * EltSize;
4193 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4194 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4196 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4197 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4198 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4201 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4203 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4204 MVT ElVT = VecVT.getVectorElementType();
4206 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4207 return Index / NumElemsPerChunk;
4210 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4211 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4213 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4214 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4215 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4218 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4220 MVT VecVT = N->getValueType(0).getSimpleVT();
4221 MVT ElVT = VecVT.getVectorElementType();
4223 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4224 return Index / NumElemsPerChunk;
4227 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4228 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4229 /// Handles 256-bit.
4230 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4231 MVT VT = N->getValueType(0).getSimpleVT();
4233 unsigned NumElts = VT.getVectorNumElements();
4235 assert((VT.is256BitVector() && NumElts == 4) &&
4236 "Unsupported vector type for VPERMQ/VPERMPD");
4239 for (unsigned i = 0; i != NumElts; ++i) {
4240 int Elt = N->getMaskElt(i);
4243 Mask |= Elt << (i*2);
4248 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4250 bool X86::isZeroNode(SDValue Elt) {
4251 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4252 return CN->isNullValue();
4253 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4254 return CFP->getValueAPF().isPosZero();
4258 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4259 /// their permute mask.
4260 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4261 SelectionDAG &DAG) {
4262 MVT VT = SVOp->getValueType(0).getSimpleVT();
4263 unsigned NumElems = VT.getVectorNumElements();
4264 SmallVector<int, 8> MaskVec;
4266 for (unsigned i = 0; i != NumElems; ++i) {
4267 int Idx = SVOp->getMaskElt(i);
4269 if (Idx < (int)NumElems)
4274 MaskVec.push_back(Idx);
4276 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4277 SVOp->getOperand(0), &MaskVec[0]);
4280 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4281 /// match movhlps. The lower half elements should come from upper half of
4282 /// V1 (and in order), and the upper half elements should come from the upper
4283 /// half of V2 (and in order).
4284 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4285 if (!VT.is128BitVector())
4287 if (VT.getVectorNumElements() != 4)
4289 for (unsigned i = 0, e = 2; i != e; ++i)
4290 if (!isUndefOrEqual(Mask[i], i+2))
4292 for (unsigned i = 2; i != 4; ++i)
4293 if (!isUndefOrEqual(Mask[i], i+4))
4298 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4299 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4301 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4302 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4304 N = N->getOperand(0).getNode();
4305 if (!ISD::isNON_EXTLoad(N))
4308 *LD = cast<LoadSDNode>(N);
4312 // Test whether the given value is a vector value which will be legalized
4314 static bool WillBeConstantPoolLoad(SDNode *N) {
4315 if (N->getOpcode() != ISD::BUILD_VECTOR)
4318 // Check for any non-constant elements.
4319 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4320 switch (N->getOperand(i).getNode()->getOpcode()) {
4322 case ISD::ConstantFP:
4329 // Vectors of all-zeros and all-ones are materialized with special
4330 // instructions rather than being loaded.
4331 return !ISD::isBuildVectorAllZeros(N) &&
4332 !ISD::isBuildVectorAllOnes(N);
4335 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4336 /// match movlp{s|d}. The lower half elements should come from lower half of
4337 /// V1 (and in order), and the upper half elements should come from the upper
4338 /// half of V2 (and in order). And since V1 will become the source of the
4339 /// MOVLP, it must be either a vector load or a scalar load to vector.
4340 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4341 ArrayRef<int> Mask, EVT VT) {
4342 if (!VT.is128BitVector())
4345 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4347 // Is V2 is a vector load, don't do this transformation. We will try to use
4348 // load folding shufps op.
4349 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4352 unsigned NumElems = VT.getVectorNumElements();
4354 if (NumElems != 2 && NumElems != 4)
4356 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4357 if (!isUndefOrEqual(Mask[i], i))
4359 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4360 if (!isUndefOrEqual(Mask[i], i+NumElems))
4365 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4367 static bool isSplatVector(SDNode *N) {
4368 if (N->getOpcode() != ISD::BUILD_VECTOR)
4371 SDValue SplatValue = N->getOperand(0);
4372 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4373 if (N->getOperand(i) != SplatValue)
4378 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4379 /// to an zero vector.
4380 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4381 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4382 SDValue V1 = N->getOperand(0);
4383 SDValue V2 = N->getOperand(1);
4384 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4385 for (unsigned i = 0; i != NumElems; ++i) {
4386 int Idx = N->getMaskElt(i);
4387 if (Idx >= (int)NumElems) {
4388 unsigned Opc = V2.getOpcode();
4389 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4391 if (Opc != ISD::BUILD_VECTOR ||
4392 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4394 } else if (Idx >= 0) {
4395 unsigned Opc = V1.getOpcode();
4396 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4398 if (Opc != ISD::BUILD_VECTOR ||
4399 !X86::isZeroNode(V1.getOperand(Idx)))
4406 /// getZeroVector - Returns a vector of specified type with all zero elements.
4408 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4409 SelectionDAG &DAG, SDLoc dl) {
4410 assert(VT.isVector() && "Expected a vector type");
4412 // Always build SSE zero vectors as <4 x i32> bitcasted
4413 // to their dest type. This ensures they get CSE'd.
4415 if (VT.is128BitVector()) { // SSE
4416 if (Subtarget->hasSSE2()) { // SSE2
4417 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4418 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4420 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4421 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4423 } else if (VT.is256BitVector()) { // AVX
4424 if (Subtarget->hasInt256()) { // AVX2
4425 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4426 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4427 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4428 array_lengthof(Ops));
4430 // 256-bit logic and arithmetic instructions in AVX are all
4431 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4432 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4433 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4434 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4435 array_lengthof(Ops));
4438 llvm_unreachable("Unexpected vector type");
4440 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4443 /// getOnesVector - Returns a vector of specified type with all bits set.
4444 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4445 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4446 /// Then bitcast to their original type, ensuring they get CSE'd.
4447 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4449 assert(VT.isVector() && "Expected a vector type");
4451 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4453 if (VT.is256BitVector()) {
4454 if (HasInt256) { // AVX2
4455 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4456 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4457 array_lengthof(Ops));
4459 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4460 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4462 } else if (VT.is128BitVector()) {
4463 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4465 llvm_unreachable("Unexpected vector type");
4467 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4470 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4471 /// that point to V2 points to its first element.
4472 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4473 for (unsigned i = 0; i != NumElems; ++i) {
4474 if (Mask[i] > (int)NumElems) {
4480 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4481 /// operation of specified width.
4482 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4484 unsigned NumElems = VT.getVectorNumElements();
4485 SmallVector<int, 8> Mask;
4486 Mask.push_back(NumElems);
4487 for (unsigned i = 1; i != NumElems; ++i)
4489 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4492 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4493 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4495 unsigned NumElems = VT.getVectorNumElements();
4496 SmallVector<int, 8> Mask;
4497 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4499 Mask.push_back(i + NumElems);
4501 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4504 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4505 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4507 unsigned NumElems = VT.getVectorNumElements();
4508 SmallVector<int, 8> Mask;
4509 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4510 Mask.push_back(i + Half);
4511 Mask.push_back(i + NumElems + Half);
4513 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4516 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4517 // a generic shuffle instruction because the target has no such instructions.
4518 // Generate shuffles which repeat i16 and i8 several times until they can be
4519 // represented by v4f32 and then be manipulated by target suported shuffles.
4520 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4521 EVT VT = V.getValueType();
4522 int NumElems = VT.getVectorNumElements();
4525 while (NumElems > 4) {
4526 if (EltNo < NumElems/2) {
4527 V = getUnpackl(DAG, dl, VT, V, V);
4529 V = getUnpackh(DAG, dl, VT, V, V);
4530 EltNo -= NumElems/2;
4537 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4538 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4539 EVT VT = V.getValueType();
4542 if (VT.is128BitVector()) {
4543 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4544 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4545 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4547 } else if (VT.is256BitVector()) {
4548 // To use VPERMILPS to splat scalars, the second half of indicies must
4549 // refer to the higher part, which is a duplication of the lower one,
4550 // because VPERMILPS can only handle in-lane permutations.
4551 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4552 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4554 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4555 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4558 llvm_unreachable("Vector size not supported");
4560 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4563 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4564 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4565 EVT SrcVT = SV->getValueType(0);
4566 SDValue V1 = SV->getOperand(0);
4569 int EltNo = SV->getSplatIndex();
4570 int NumElems = SrcVT.getVectorNumElements();
4571 bool Is256BitVec = SrcVT.is256BitVector();
4573 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4574 "Unknown how to promote splat for type");
4576 // Extract the 128-bit part containing the splat element and update
4577 // the splat element index when it refers to the higher register.
4579 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4580 if (EltNo >= NumElems/2)
4581 EltNo -= NumElems/2;
4584 // All i16 and i8 vector types can't be used directly by a generic shuffle
4585 // instruction because the target has no such instruction. Generate shuffles
4586 // which repeat i16 and i8 several times until they fit in i32, and then can
4587 // be manipulated by target suported shuffles.
4588 EVT EltVT = SrcVT.getVectorElementType();
4589 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4590 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4592 // Recreate the 256-bit vector and place the same 128-bit vector
4593 // into the low and high part. This is necessary because we want
4594 // to use VPERM* to shuffle the vectors
4596 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4599 return getLegalSplat(DAG, V1, EltNo);
4602 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4603 /// vector of zero or undef vector. This produces a shuffle where the low
4604 /// element of V2 is swizzled into the zero/undef vector, landing at element
4605 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4606 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4608 const X86Subtarget *Subtarget,
4609 SelectionDAG &DAG) {
4610 EVT VT = V2.getValueType();
4612 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4613 unsigned NumElems = VT.getVectorNumElements();
4614 SmallVector<int, 16> MaskVec;
4615 for (unsigned i = 0; i != NumElems; ++i)
4616 // If this is the insertion idx, put the low elt of V2 here.
4617 MaskVec.push_back(i == Idx ? NumElems : i);
4618 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4621 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4622 /// target specific opcode. Returns true if the Mask could be calculated.
4623 /// Sets IsUnary to true if only uses one source.
4624 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4625 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4626 unsigned NumElems = VT.getVectorNumElements();
4630 switch(N->getOpcode()) {
4632 ImmN = N->getOperand(N->getNumOperands()-1);
4633 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4635 case X86ISD::UNPCKH:
4636 DecodeUNPCKHMask(VT, Mask);
4638 case X86ISD::UNPCKL:
4639 DecodeUNPCKLMask(VT, Mask);
4641 case X86ISD::MOVHLPS:
4642 DecodeMOVHLPSMask(NumElems, Mask);
4644 case X86ISD::MOVLHPS:
4645 DecodeMOVLHPSMask(NumElems, Mask);
4647 case X86ISD::PALIGNR:
4648 ImmN = N->getOperand(N->getNumOperands()-1);
4649 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4651 case X86ISD::PSHUFD:
4652 case X86ISD::VPERMILP:
4653 ImmN = N->getOperand(N->getNumOperands()-1);
4654 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4657 case X86ISD::PSHUFHW:
4658 ImmN = N->getOperand(N->getNumOperands()-1);
4659 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4662 case X86ISD::PSHUFLW:
4663 ImmN = N->getOperand(N->getNumOperands()-1);
4664 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4667 case X86ISD::VPERMI:
4668 ImmN = N->getOperand(N->getNumOperands()-1);
4669 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4673 case X86ISD::MOVSD: {
4674 // The index 0 always comes from the first element of the second source,
4675 // this is why MOVSS and MOVSD are used in the first place. The other
4676 // elements come from the other positions of the first source vector
4677 Mask.push_back(NumElems);
4678 for (unsigned i = 1; i != NumElems; ++i) {
4683 case X86ISD::VPERM2X128:
4684 ImmN = N->getOperand(N->getNumOperands()-1);
4685 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4686 if (Mask.empty()) return false;
4688 case X86ISD::MOVDDUP:
4689 case X86ISD::MOVLHPD:
4690 case X86ISD::MOVLPD:
4691 case X86ISD::MOVLPS:
4692 case X86ISD::MOVSHDUP:
4693 case X86ISD::MOVSLDUP:
4694 // Not yet implemented
4696 default: llvm_unreachable("unknown target shuffle node");
4702 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4703 /// element of the result of the vector shuffle.
4704 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4707 return SDValue(); // Limit search depth.
4709 SDValue V = SDValue(N, 0);
4710 EVT VT = V.getValueType();
4711 unsigned Opcode = V.getOpcode();
4713 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4714 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4715 int Elt = SV->getMaskElt(Index);
4718 return DAG.getUNDEF(VT.getVectorElementType());
4720 unsigned NumElems = VT.getVectorNumElements();
4721 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4722 : SV->getOperand(1);
4723 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4726 // Recurse into target specific vector shuffles to find scalars.
4727 if (isTargetShuffle(Opcode)) {
4728 MVT ShufVT = V.getValueType().getSimpleVT();
4729 unsigned NumElems = ShufVT.getVectorNumElements();
4730 SmallVector<int, 16> ShuffleMask;
4733 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4736 int Elt = ShuffleMask[Index];
4738 return DAG.getUNDEF(ShufVT.getVectorElementType());
4740 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4742 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4746 // Actual nodes that may contain scalar elements
4747 if (Opcode == ISD::BITCAST) {
4748 V = V.getOperand(0);
4749 EVT SrcVT = V.getValueType();
4750 unsigned NumElems = VT.getVectorNumElements();
4752 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4756 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4757 return (Index == 0) ? V.getOperand(0)
4758 : DAG.getUNDEF(VT.getVectorElementType());
4760 if (V.getOpcode() == ISD::BUILD_VECTOR)
4761 return V.getOperand(Index);
4766 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4767 /// shuffle operation which come from a consecutively from a zero. The
4768 /// search can start in two different directions, from left or right.
4769 /// We count undefs as zeros until PreferredNum is reached.
4770 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4771 unsigned NumElems, bool ZerosFromLeft,
4773 unsigned PreferredNum = -1U) {
4774 unsigned NumZeros = 0;
4775 for (unsigned i = 0; i != NumElems; ++i) {
4776 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
4777 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4781 if (X86::isZeroNode(Elt))
4783 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
4784 NumZeros = std::min(NumZeros + 1, PreferredNum);
4792 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4793 /// correspond consecutively to elements from one of the vector operands,
4794 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4796 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4797 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4798 unsigned NumElems, unsigned &OpNum) {
4799 bool SeenV1 = false;
4800 bool SeenV2 = false;
4802 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4803 int Idx = SVOp->getMaskElt(i);
4804 // Ignore undef indicies
4808 if (Idx < (int)NumElems)
4813 // Only accept consecutive elements from the same vector
4814 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4818 OpNum = SeenV1 ? 0 : 1;
4822 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4823 /// logical left shift of a vector.
4824 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4825 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4826 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4827 unsigned NumZeros = getNumOfConsecutiveZeros(
4828 SVOp, NumElems, false /* check zeros from right */, DAG,
4829 SVOp->getMaskElt(0));
4835 // Considering the elements in the mask that are not consecutive zeros,
4836 // check if they consecutively come from only one of the source vectors.
4838 // V1 = {X, A, B, C} 0
4840 // vector_shuffle V1, V2 <1, 2, 3, X>
4842 if (!isShuffleMaskConsecutive(SVOp,
4843 0, // Mask Start Index
4844 NumElems-NumZeros, // Mask End Index(exclusive)
4845 NumZeros, // Where to start looking in the src vector
4846 NumElems, // Number of elements in vector
4847 OpSrc)) // Which source operand ?
4852 ShVal = SVOp->getOperand(OpSrc);
4856 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4857 /// logical left shift of a vector.
4858 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4859 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4860 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4861 unsigned NumZeros = getNumOfConsecutiveZeros(
4862 SVOp, NumElems, true /* check zeros from left */, DAG,
4863 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
4869 // Considering the elements in the mask that are not consecutive zeros,
4870 // check if they consecutively come from only one of the source vectors.
4872 // 0 { A, B, X, X } = V2
4874 // vector_shuffle V1, V2 <X, X, 4, 5>
4876 if (!isShuffleMaskConsecutive(SVOp,
4877 NumZeros, // Mask Start Index
4878 NumElems, // Mask End Index(exclusive)
4879 0, // Where to start looking in the src vector
4880 NumElems, // Number of elements in vector
4881 OpSrc)) // Which source operand ?
4886 ShVal = SVOp->getOperand(OpSrc);
4890 /// isVectorShift - Returns true if the shuffle can be implemented as a
4891 /// logical left or right shift of a vector.
4892 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4893 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4894 // Although the logic below support any bitwidth size, there are no
4895 // shift instructions which handle more than 128-bit vectors.
4896 if (!SVOp->getValueType(0).is128BitVector())
4899 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4900 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4906 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4908 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4909 unsigned NumNonZero, unsigned NumZero,
4911 const X86Subtarget* Subtarget,
4912 const TargetLowering &TLI) {
4919 for (unsigned i = 0; i < 16; ++i) {
4920 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4921 if (ThisIsNonZero && First) {
4923 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4925 V = DAG.getUNDEF(MVT::v8i16);
4930 SDValue ThisElt(0, 0), LastElt(0, 0);
4931 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4932 if (LastIsNonZero) {
4933 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4934 MVT::i16, Op.getOperand(i-1));
4936 if (ThisIsNonZero) {
4937 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4938 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4939 ThisElt, DAG.getConstant(8, MVT::i8));
4941 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4945 if (ThisElt.getNode())
4946 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4947 DAG.getIntPtrConstant(i/2));
4951 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4954 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4956 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4957 unsigned NumNonZero, unsigned NumZero,
4959 const X86Subtarget* Subtarget,
4960 const TargetLowering &TLI) {
4967 for (unsigned i = 0; i < 8; ++i) {
4968 bool isNonZero = (NonZeros & (1 << i)) != 0;
4972 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4974 V = DAG.getUNDEF(MVT::v8i16);
4977 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4978 MVT::v8i16, V, Op.getOperand(i),
4979 DAG.getIntPtrConstant(i));
4986 /// getVShift - Return a vector logical shift node.
4988 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4989 unsigned NumBits, SelectionDAG &DAG,
4990 const TargetLowering &TLI, SDLoc dl) {
4991 assert(VT.is128BitVector() && "Unknown type for VShift");
4992 EVT ShVT = MVT::v2i64;
4993 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4994 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4995 return DAG.getNode(ISD::BITCAST, dl, VT,
4996 DAG.getNode(Opc, dl, ShVT, SrcOp,
4997 DAG.getConstant(NumBits,
4998 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5002 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5003 SelectionDAG &DAG) const {
5005 // Check if the scalar load can be widened into a vector load. And if
5006 // the address is "base + cst" see if the cst can be "absorbed" into
5007 // the shuffle mask.
5008 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5009 SDValue Ptr = LD->getBasePtr();
5010 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5012 EVT PVT = LD->getValueType(0);
5013 if (PVT != MVT::i32 && PVT != MVT::f32)
5018 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5019 FI = FINode->getIndex();
5021 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5022 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5023 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5024 Offset = Ptr.getConstantOperandVal(1);
5025 Ptr = Ptr.getOperand(0);
5030 // FIXME: 256-bit vector instructions don't require a strict alignment,
5031 // improve this code to support it better.
5032 unsigned RequiredAlign = VT.getSizeInBits()/8;
5033 SDValue Chain = LD->getChain();
5034 // Make sure the stack object alignment is at least 16 or 32.
5035 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5036 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5037 if (MFI->isFixedObjectIndex(FI)) {
5038 // Can't change the alignment. FIXME: It's possible to compute
5039 // the exact stack offset and reference FI + adjust offset instead.
5040 // If someone *really* cares about this. That's the way to implement it.
5043 MFI->setObjectAlignment(FI, RequiredAlign);
5047 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5048 // Ptr + (Offset & ~15).
5051 if ((Offset % RequiredAlign) & 3)
5053 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5055 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5056 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5058 int EltNo = (Offset - StartOffset) >> 2;
5059 unsigned NumElems = VT.getVectorNumElements();
5061 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5062 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5063 LD->getPointerInfo().getWithOffset(StartOffset),
5064 false, false, false, 0);
5066 SmallVector<int, 8> Mask;
5067 for (unsigned i = 0; i != NumElems; ++i)
5068 Mask.push_back(EltNo);
5070 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5076 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5077 /// vector of type 'VT', see if the elements can be replaced by a single large
5078 /// load which has the same value as a build_vector whose operands are 'elts'.
5080 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5082 /// FIXME: we'd also like to handle the case where the last elements are zero
5083 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5084 /// There's even a handy isZeroNode for that purpose.
5085 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5086 SDLoc &DL, SelectionDAG &DAG) {
5087 EVT EltVT = VT.getVectorElementType();
5088 unsigned NumElems = Elts.size();
5090 LoadSDNode *LDBase = NULL;
5091 unsigned LastLoadedElt = -1U;
5093 // For each element in the initializer, see if we've found a load or an undef.
5094 // If we don't find an initial load element, or later load elements are
5095 // non-consecutive, bail out.
5096 for (unsigned i = 0; i < NumElems; ++i) {
5097 SDValue Elt = Elts[i];
5099 if (!Elt.getNode() ||
5100 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5103 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5105 LDBase = cast<LoadSDNode>(Elt.getNode());
5109 if (Elt.getOpcode() == ISD::UNDEF)
5112 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5113 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5118 // If we have found an entire vector of loads and undefs, then return a large
5119 // load of the entire vector width starting at the base pointer. If we found
5120 // consecutive loads for the low half, generate a vzext_load node.
5121 if (LastLoadedElt == NumElems - 1) {
5122 SDValue NewLd = SDValue();
5123 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5124 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5125 LDBase->getPointerInfo(),
5126 LDBase->isVolatile(), LDBase->isNonTemporal(),
5127 LDBase->isInvariant(), 0);
5128 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5129 LDBase->getPointerInfo(),
5130 LDBase->isVolatile(), LDBase->isNonTemporal(),
5131 LDBase->isInvariant(), LDBase->getAlignment());
5133 if (LDBase->hasAnyUseOfValue(1)) {
5134 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5136 SDValue(NewLd.getNode(), 1));
5137 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5138 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5139 SDValue(NewLd.getNode(), 1));
5144 if (NumElems == 4 && LastLoadedElt == 1 &&
5145 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5146 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5147 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5149 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5150 array_lengthof(Ops), MVT::i64,
5151 LDBase->getPointerInfo(),
5152 LDBase->getAlignment(),
5153 false/*isVolatile*/, true/*ReadMem*/,
5156 // Make sure the newly-created LOAD is in the same position as LDBase in
5157 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5158 // update uses of LDBase's output chain to use the TokenFactor.
5159 if (LDBase->hasAnyUseOfValue(1)) {
5160 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5161 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5162 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5163 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5164 SDValue(ResNode.getNode(), 1));
5167 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5172 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5173 /// to generate a splat value for the following cases:
5174 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5175 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5176 /// a scalar load, or a constant.
5177 /// The VBROADCAST node is returned when a pattern is found,
5178 /// or SDValue() otherwise.
5180 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5181 if (!Subtarget->hasFp256())
5184 MVT VT = Op.getValueType().getSimpleVT();
5187 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5188 "Unsupported vector type for broadcast.");
5193 switch (Op.getOpcode()) {
5195 // Unknown pattern found.
5198 case ISD::BUILD_VECTOR: {
5199 // The BUILD_VECTOR node must be a splat.
5200 if (!isSplatVector(Op.getNode()))
5203 Ld = Op.getOperand(0);
5204 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5205 Ld.getOpcode() == ISD::ConstantFP);
5207 // The suspected load node has several users. Make sure that all
5208 // of its users are from the BUILD_VECTOR node.
5209 // Constants may have multiple users.
5210 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5215 case ISD::VECTOR_SHUFFLE: {
5216 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5218 // Shuffles must have a splat mask where the first element is
5220 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5223 SDValue Sc = Op.getOperand(0);
5224 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5225 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5227 if (!Subtarget->hasInt256())
5230 // Use the register form of the broadcast instruction available on AVX2.
5231 if (VT.is256BitVector())
5232 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5233 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5236 Ld = Sc.getOperand(0);
5237 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5238 Ld.getOpcode() == ISD::ConstantFP);
5240 // The scalar_to_vector node and the suspected
5241 // load node must have exactly one user.
5242 // Constants may have multiple users.
5243 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5249 bool Is256 = VT.is256BitVector();
5251 // Handle the broadcasting a single constant scalar from the constant pool
5252 // into a vector. On Sandybridge it is still better to load a constant vector
5253 // from the constant pool and not to broadcast it from a scalar.
5254 if (ConstSplatVal && Subtarget->hasInt256()) {
5255 EVT CVT = Ld.getValueType();
5256 assert(!CVT.isVector() && "Must not broadcast a vector type");
5257 unsigned ScalarSize = CVT.getSizeInBits();
5259 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5260 const Constant *C = 0;
5261 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5262 C = CI->getConstantIntValue();
5263 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5264 C = CF->getConstantFPValue();
5266 assert(C && "Invalid constant type");
5268 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5269 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5270 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5271 MachinePointerInfo::getConstantPool(),
5272 false, false, false, Alignment);
5274 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5278 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5279 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5281 // Handle AVX2 in-register broadcasts.
5282 if (!IsLoad && Subtarget->hasInt256() &&
5283 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5284 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5286 // The scalar source must be a normal load.
5290 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5291 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5293 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5294 // double since there is no vbroadcastsd xmm
5295 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5296 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5297 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5300 // Unsupported broadcast.
5305 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5306 EVT VT = Op.getValueType();
5308 // Skip if insert_vec_elt is not supported.
5309 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5313 unsigned NumElems = Op.getNumOperands();
5317 SmallVector<unsigned, 4> InsertIndices;
5318 SmallVector<int, 8> Mask(NumElems, -1);
5320 for (unsigned i = 0; i != NumElems; ++i) {
5321 unsigned Opc = Op.getOperand(i).getOpcode();
5323 if (Opc == ISD::UNDEF)
5326 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5327 // Quit if more than 1 elements need inserting.
5328 if (InsertIndices.size() > 1)
5331 InsertIndices.push_back(i);
5335 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5336 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5338 // Quit if extracted from vector of different type.
5339 if (ExtractedFromVec.getValueType() != VT)
5342 // Quit if non-constant index.
5343 if (!isa<ConstantSDNode>(ExtIdx))
5346 if (VecIn1.getNode() == 0)
5347 VecIn1 = ExtractedFromVec;
5348 else if (VecIn1 != ExtractedFromVec) {
5349 if (VecIn2.getNode() == 0)
5350 VecIn2 = ExtractedFromVec;
5351 else if (VecIn2 != ExtractedFromVec)
5352 // Quit if more than 2 vectors to shuffle
5356 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5358 if (ExtractedFromVec == VecIn1)
5360 else if (ExtractedFromVec == VecIn2)
5361 Mask[i] = Idx + NumElems;
5364 if (VecIn1.getNode() == 0)
5367 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5368 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5369 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5370 unsigned Idx = InsertIndices[i];
5371 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5372 DAG.getIntPtrConstant(Idx));
5379 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5382 MVT VT = Op.getValueType().getSimpleVT();
5383 MVT ExtVT = VT.getVectorElementType();
5384 unsigned NumElems = Op.getNumOperands();
5386 // Vectors containing all zeros can be matched by pxor and xorps later
5387 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5388 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5389 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5390 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5393 return getZeroVector(VT, Subtarget, DAG, dl);
5396 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5397 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5398 // vpcmpeqd on 256-bit vectors.
5399 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5400 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5403 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5406 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5407 if (Broadcast.getNode())
5410 unsigned EVTBits = ExtVT.getSizeInBits();
5412 unsigned NumZero = 0;
5413 unsigned NumNonZero = 0;
5414 unsigned NonZeros = 0;
5415 bool IsAllConstants = true;
5416 SmallSet<SDValue, 8> Values;
5417 for (unsigned i = 0; i < NumElems; ++i) {
5418 SDValue Elt = Op.getOperand(i);
5419 if (Elt.getOpcode() == ISD::UNDEF)
5422 if (Elt.getOpcode() != ISD::Constant &&
5423 Elt.getOpcode() != ISD::ConstantFP)
5424 IsAllConstants = false;
5425 if (X86::isZeroNode(Elt))
5428 NonZeros |= (1 << i);
5433 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5434 if (NumNonZero == 0)
5435 return DAG.getUNDEF(VT);
5437 // Special case for single non-zero, non-undef, element.
5438 if (NumNonZero == 1) {
5439 unsigned Idx = countTrailingZeros(NonZeros);
5440 SDValue Item = Op.getOperand(Idx);
5442 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5443 // the value are obviously zero, truncate the value to i32 and do the
5444 // insertion that way. Only do this if the value is non-constant or if the
5445 // value is a constant being inserted into element 0. It is cheaper to do
5446 // a constant pool load than it is to do a movd + shuffle.
5447 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5448 (!IsAllConstants || Idx == 0)) {
5449 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5451 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5452 EVT VecVT = MVT::v4i32;
5453 unsigned VecElts = 4;
5455 // Truncate the value (which may itself be a constant) to i32, and
5456 // convert it to a vector with movd (S2V+shuffle to zero extend).
5457 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5458 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5459 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5461 // Now we have our 32-bit value zero extended in the low element of
5462 // a vector. If Idx != 0, swizzle it into place.
5464 SmallVector<int, 4> Mask;
5465 Mask.push_back(Idx);
5466 for (unsigned i = 1; i != VecElts; ++i)
5468 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5471 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5475 // If we have a constant or non-constant insertion into the low element of
5476 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5477 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5478 // depending on what the source datatype is.
5481 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5483 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5484 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5485 if (VT.is256BitVector()) {
5486 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5487 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5488 Item, DAG.getIntPtrConstant(0));
5490 assert(VT.is128BitVector() && "Expected an SSE value type!");
5491 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5492 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5493 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5496 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5497 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5498 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5499 if (VT.is256BitVector()) {
5500 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5501 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5503 assert(VT.is128BitVector() && "Expected an SSE value type!");
5504 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5506 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5510 // Is it a vector logical left shift?
5511 if (NumElems == 2 && Idx == 1 &&
5512 X86::isZeroNode(Op.getOperand(0)) &&
5513 !X86::isZeroNode(Op.getOperand(1))) {
5514 unsigned NumBits = VT.getSizeInBits();
5515 return getVShift(true, VT,
5516 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5517 VT, Op.getOperand(1)),
5518 NumBits/2, DAG, *this, dl);
5521 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5524 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5525 // is a non-constant being inserted into an element other than the low one,
5526 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5527 // movd/movss) to move this into the low element, then shuffle it into
5529 if (EVTBits == 32) {
5530 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5532 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5533 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5534 SmallVector<int, 8> MaskVec;
5535 for (unsigned i = 0; i != NumElems; ++i)
5536 MaskVec.push_back(i == Idx ? 0 : 1);
5537 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5541 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5542 if (Values.size() == 1) {
5543 if (EVTBits == 32) {
5544 // Instead of a shuffle like this:
5545 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5546 // Check if it's possible to issue this instead.
5547 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5548 unsigned Idx = countTrailingZeros(NonZeros);
5549 SDValue Item = Op.getOperand(Idx);
5550 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5551 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5556 // A vector full of immediates; various special cases are already
5557 // handled, so this is best done with a single constant-pool load.
5561 // For AVX-length vectors, build the individual 128-bit pieces and use
5562 // shuffles to put them in place.
5563 if (VT.is256BitVector()) {
5564 SmallVector<SDValue, 32> V;
5565 for (unsigned i = 0; i != NumElems; ++i)
5566 V.push_back(Op.getOperand(i));
5568 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5570 // Build both the lower and upper subvector.
5571 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5572 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5575 // Recreate the wider vector with the lower and upper part.
5576 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5579 // Let legalizer expand 2-wide build_vectors.
5580 if (EVTBits == 64) {
5581 if (NumNonZero == 1) {
5582 // One half is zero or undef.
5583 unsigned Idx = countTrailingZeros(NonZeros);
5584 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5585 Op.getOperand(Idx));
5586 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5591 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5592 if (EVTBits == 8 && NumElems == 16) {
5593 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5595 if (V.getNode()) return V;
5598 if (EVTBits == 16 && NumElems == 8) {
5599 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5601 if (V.getNode()) return V;
5604 // If element VT is == 32 bits, turn it into a number of shuffles.
5605 SmallVector<SDValue, 8> V(NumElems);
5606 if (NumElems == 4 && NumZero > 0) {
5607 for (unsigned i = 0; i < 4; ++i) {
5608 bool isZero = !(NonZeros & (1 << i));
5610 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5612 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5615 for (unsigned i = 0; i < 2; ++i) {
5616 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5619 V[i] = V[i*2]; // Must be a zero vector.
5622 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5625 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5628 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5633 bool Reverse1 = (NonZeros & 0x3) == 2;
5634 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5638 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5639 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5641 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5644 if (Values.size() > 1 && VT.is128BitVector()) {
5645 // Check for a build vector of consecutive loads.
5646 for (unsigned i = 0; i < NumElems; ++i)
5647 V[i] = Op.getOperand(i);
5649 // Check for elements which are consecutive loads.
5650 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5654 // Check for a build vector from mostly shuffle plus few inserting.
5655 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5659 // For SSE 4.1, use insertps to put the high elements into the low element.
5660 if (getSubtarget()->hasSSE41()) {
5662 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5663 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5665 Result = DAG.getUNDEF(VT);
5667 for (unsigned i = 1; i < NumElems; ++i) {
5668 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5669 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5670 Op.getOperand(i), DAG.getIntPtrConstant(i));
5675 // Otherwise, expand into a number of unpckl*, start by extending each of
5676 // our (non-undef) elements to the full vector width with the element in the
5677 // bottom slot of the vector (which generates no code for SSE).
5678 for (unsigned i = 0; i < NumElems; ++i) {
5679 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5680 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5682 V[i] = DAG.getUNDEF(VT);
5685 // Next, we iteratively mix elements, e.g. for v4f32:
5686 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5687 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5688 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5689 unsigned EltStride = NumElems >> 1;
5690 while (EltStride != 0) {
5691 for (unsigned i = 0; i < EltStride; ++i) {
5692 // If V[i+EltStride] is undef and this is the first round of mixing,
5693 // then it is safe to just drop this shuffle: V[i] is already in the
5694 // right place, the one element (since it's the first round) being
5695 // inserted as undef can be dropped. This isn't safe for successive
5696 // rounds because they will permute elements within both vectors.
5697 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5698 EltStride == NumElems/2)
5701 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5710 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5711 // to create 256-bit vectors from two other 128-bit ones.
5712 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5714 MVT ResVT = Op.getValueType().getSimpleVT();
5716 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5718 SDValue V1 = Op.getOperand(0);
5719 SDValue V2 = Op.getOperand(1);
5720 unsigned NumElems = ResVT.getVectorNumElements();
5722 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5725 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5726 assert(Op.getNumOperands() == 2);
5728 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5729 // from two other 128-bit ones.
5730 return LowerAVXCONCAT_VECTORS(Op, DAG);
5733 // Try to lower a shuffle node into a simple blend instruction.
5735 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5736 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5737 SDValue V1 = SVOp->getOperand(0);
5738 SDValue V2 = SVOp->getOperand(1);
5740 MVT VT = SVOp->getValueType(0).getSimpleVT();
5741 MVT EltVT = VT.getVectorElementType();
5742 unsigned NumElems = VT.getVectorNumElements();
5744 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5746 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5749 // Check the mask for BLEND and build the value.
5750 unsigned MaskValue = 0;
5751 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5752 unsigned NumLanes = (NumElems-1)/8 + 1;
5753 unsigned NumElemsInLane = NumElems / NumLanes;
5755 // Blend for v16i16 should be symetric for the both lanes.
5756 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5758 int SndLaneEltIdx = (NumLanes == 2) ?
5759 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5760 int EltIdx = SVOp->getMaskElt(i);
5762 if ((EltIdx < 0 || EltIdx == (int)i) &&
5763 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5766 if (((unsigned)EltIdx == (i + NumElems)) &&
5767 (SndLaneEltIdx < 0 ||
5768 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5769 MaskValue |= (1<<i);
5774 // Convert i32 vectors to floating point if it is not AVX2.
5775 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5777 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5778 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5780 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5781 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5784 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5785 DAG.getConstant(MaskValue, MVT::i32));
5786 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5789 // v8i16 shuffles - Prefer shuffles in the following order:
5790 // 1. [all] pshuflw, pshufhw, optional move
5791 // 2. [ssse3] 1 x pshufb
5792 // 3. [ssse3] 2 x pshufb + 1 x por
5793 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5795 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5796 SelectionDAG &DAG) {
5797 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5798 SDValue V1 = SVOp->getOperand(0);
5799 SDValue V2 = SVOp->getOperand(1);
5801 SmallVector<int, 8> MaskVals;
5803 // Determine if more than 1 of the words in each of the low and high quadwords
5804 // of the result come from the same quadword of one of the two inputs. Undef
5805 // mask values count as coming from any quadword, for better codegen.
5806 unsigned LoQuad[] = { 0, 0, 0, 0 };
5807 unsigned HiQuad[] = { 0, 0, 0, 0 };
5808 std::bitset<4> InputQuads;
5809 for (unsigned i = 0; i < 8; ++i) {
5810 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5811 int EltIdx = SVOp->getMaskElt(i);
5812 MaskVals.push_back(EltIdx);
5821 InputQuads.set(EltIdx / 4);
5824 int BestLoQuad = -1;
5825 unsigned MaxQuad = 1;
5826 for (unsigned i = 0; i < 4; ++i) {
5827 if (LoQuad[i] > MaxQuad) {
5829 MaxQuad = LoQuad[i];
5833 int BestHiQuad = -1;
5835 for (unsigned i = 0; i < 4; ++i) {
5836 if (HiQuad[i] > MaxQuad) {
5838 MaxQuad = HiQuad[i];
5842 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5843 // of the two input vectors, shuffle them into one input vector so only a
5844 // single pshufb instruction is necessary. If There are more than 2 input
5845 // quads, disable the next transformation since it does not help SSSE3.
5846 bool V1Used = InputQuads[0] || InputQuads[1];
5847 bool V2Used = InputQuads[2] || InputQuads[3];
5848 if (Subtarget->hasSSSE3()) {
5849 if (InputQuads.count() == 2 && V1Used && V2Used) {
5850 BestLoQuad = InputQuads[0] ? 0 : 1;
5851 BestHiQuad = InputQuads[2] ? 2 : 3;
5853 if (InputQuads.count() > 2) {
5859 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5860 // the shuffle mask. If a quad is scored as -1, that means that it contains
5861 // words from all 4 input quadwords.
5863 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5865 BestLoQuad < 0 ? 0 : BestLoQuad,
5866 BestHiQuad < 0 ? 1 : BestHiQuad
5868 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5869 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5870 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5871 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5873 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5874 // source words for the shuffle, to aid later transformations.
5875 bool AllWordsInNewV = true;
5876 bool InOrder[2] = { true, true };
5877 for (unsigned i = 0; i != 8; ++i) {
5878 int idx = MaskVals[i];
5880 InOrder[i/4] = false;
5881 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5883 AllWordsInNewV = false;
5887 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5888 if (AllWordsInNewV) {
5889 for (int i = 0; i != 8; ++i) {
5890 int idx = MaskVals[i];
5893 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5894 if ((idx != i) && idx < 4)
5896 if ((idx != i) && idx > 3)
5905 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5906 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5907 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5908 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5909 unsigned TargetMask = 0;
5910 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5911 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5912 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5913 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5914 getShufflePSHUFLWImmediate(SVOp);
5915 V1 = NewV.getOperand(0);
5916 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5920 // Promote splats to a larger type which usually leads to more efficient code.
5921 // FIXME: Is this true if pshufb is available?
5922 if (SVOp->isSplat())
5923 return PromoteSplat(SVOp, DAG);
5925 // If we have SSSE3, and all words of the result are from 1 input vector,
5926 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5927 // is present, fall back to case 4.
5928 if (Subtarget->hasSSSE3()) {
5929 SmallVector<SDValue,16> pshufbMask;
5931 // If we have elements from both input vectors, set the high bit of the
5932 // shuffle mask element to zero out elements that come from V2 in the V1
5933 // mask, and elements that come from V1 in the V2 mask, so that the two
5934 // results can be OR'd together.
5935 bool TwoInputs = V1Used && V2Used;
5936 for (unsigned i = 0; i != 8; ++i) {
5937 int EltIdx = MaskVals[i] * 2;
5938 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5939 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5940 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5941 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5943 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5944 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5945 DAG.getNode(ISD::BUILD_VECTOR, dl,
5946 MVT::v16i8, &pshufbMask[0], 16));
5948 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5950 // Calculate the shuffle mask for the second input, shuffle it, and
5951 // OR it with the first shuffled input.
5953 for (unsigned i = 0; i != 8; ++i) {
5954 int EltIdx = MaskVals[i] * 2;
5955 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5956 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5957 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5958 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5960 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5961 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5962 DAG.getNode(ISD::BUILD_VECTOR, dl,
5963 MVT::v16i8, &pshufbMask[0], 16));
5964 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5965 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5968 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5969 // and update MaskVals with new element order.
5970 std::bitset<8> InOrder;
5971 if (BestLoQuad >= 0) {
5972 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5973 for (int i = 0; i != 4; ++i) {
5974 int idx = MaskVals[i];
5977 } else if ((idx / 4) == BestLoQuad) {
5982 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5985 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5986 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5987 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5989 getShufflePSHUFLWImmediate(SVOp), DAG);
5993 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5994 // and update MaskVals with the new element order.
5995 if (BestHiQuad >= 0) {
5996 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5997 for (unsigned i = 4; i != 8; ++i) {
5998 int idx = MaskVals[i];
6001 } else if ((idx / 4) == BestHiQuad) {
6002 MaskV[i] = (idx & 3) + 4;
6006 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6009 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6010 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6011 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6013 getShufflePSHUFHWImmediate(SVOp), DAG);
6017 // In case BestHi & BestLo were both -1, which means each quadword has a word
6018 // from each of the four input quadwords, calculate the InOrder bitvector now
6019 // before falling through to the insert/extract cleanup.
6020 if (BestLoQuad == -1 && BestHiQuad == -1) {
6022 for (int i = 0; i != 8; ++i)
6023 if (MaskVals[i] < 0 || MaskVals[i] == i)
6027 // The other elements are put in the right place using pextrw and pinsrw.
6028 for (unsigned i = 0; i != 8; ++i) {
6031 int EltIdx = MaskVals[i];
6034 SDValue ExtOp = (EltIdx < 8) ?
6035 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6036 DAG.getIntPtrConstant(EltIdx)) :
6037 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6038 DAG.getIntPtrConstant(EltIdx - 8));
6039 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6040 DAG.getIntPtrConstant(i));
6045 // v16i8 shuffles - Prefer shuffles in the following order:
6046 // 1. [ssse3] 1 x pshufb
6047 // 2. [ssse3] 2 x pshufb + 1 x por
6048 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6050 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6052 const X86TargetLowering &TLI) {
6053 SDValue V1 = SVOp->getOperand(0);
6054 SDValue V2 = SVOp->getOperand(1);
6056 ArrayRef<int> MaskVals = SVOp->getMask();
6058 // Promote splats to a larger type which usually leads to more efficient code.
6059 // FIXME: Is this true if pshufb is available?
6060 if (SVOp->isSplat())
6061 return PromoteSplat(SVOp, DAG);
6063 // If we have SSSE3, case 1 is generated when all result bytes come from
6064 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6065 // present, fall back to case 3.
6067 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6068 if (TLI.getSubtarget()->hasSSSE3()) {
6069 SmallVector<SDValue,16> pshufbMask;
6071 // If all result elements are from one input vector, then only translate
6072 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6074 // Otherwise, we have elements from both input vectors, and must zero out
6075 // elements that come from V2 in the first mask, and V1 in the second mask
6076 // so that we can OR them together.
6077 for (unsigned i = 0; i != 16; ++i) {
6078 int EltIdx = MaskVals[i];
6079 if (EltIdx < 0 || EltIdx >= 16)
6081 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6083 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6084 DAG.getNode(ISD::BUILD_VECTOR, dl,
6085 MVT::v16i8, &pshufbMask[0], 16));
6087 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6088 // the 2nd operand if it's undefined or zero.
6089 if (V2.getOpcode() == ISD::UNDEF ||
6090 ISD::isBuildVectorAllZeros(V2.getNode()))
6093 // Calculate the shuffle mask for the second input, shuffle it, and
6094 // OR it with the first shuffled input.
6096 for (unsigned i = 0; i != 16; ++i) {
6097 int EltIdx = MaskVals[i];
6098 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6099 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6101 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6102 DAG.getNode(ISD::BUILD_VECTOR, dl,
6103 MVT::v16i8, &pshufbMask[0], 16));
6104 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6107 // No SSSE3 - Calculate in place words and then fix all out of place words
6108 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6109 // the 16 different words that comprise the two doublequadword input vectors.
6110 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6111 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6113 for (int i = 0; i != 8; ++i) {
6114 int Elt0 = MaskVals[i*2];
6115 int Elt1 = MaskVals[i*2+1];
6117 // This word of the result is all undef, skip it.
6118 if (Elt0 < 0 && Elt1 < 0)
6121 // This word of the result is already in the correct place, skip it.
6122 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6125 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6126 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6129 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6130 // using a single extract together, load it and store it.
6131 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6132 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6133 DAG.getIntPtrConstant(Elt1 / 2));
6134 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6135 DAG.getIntPtrConstant(i));
6139 // If Elt1 is defined, extract it from the appropriate source. If the
6140 // source byte is not also odd, shift the extracted word left 8 bits
6141 // otherwise clear the bottom 8 bits if we need to do an or.
6143 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6144 DAG.getIntPtrConstant(Elt1 / 2));
6145 if ((Elt1 & 1) == 0)
6146 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6148 TLI.getShiftAmountTy(InsElt.getValueType())));
6150 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6151 DAG.getConstant(0xFF00, MVT::i16));
6153 // If Elt0 is defined, extract it from the appropriate source. If the
6154 // source byte is not also even, shift the extracted word right 8 bits. If
6155 // Elt1 was also defined, OR the extracted values together before
6156 // inserting them in the result.
6158 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6159 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6160 if ((Elt0 & 1) != 0)
6161 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6163 TLI.getShiftAmountTy(InsElt0.getValueType())));
6165 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6166 DAG.getConstant(0x00FF, MVT::i16));
6167 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6170 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6171 DAG.getIntPtrConstant(i));
6173 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6176 // v32i8 shuffles - Translate to VPSHUFB if possible.
6178 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6179 const X86Subtarget *Subtarget,
6180 SelectionDAG &DAG) {
6181 MVT VT = SVOp->getValueType(0).getSimpleVT();
6182 SDValue V1 = SVOp->getOperand(0);
6183 SDValue V2 = SVOp->getOperand(1);
6185 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6187 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6188 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6189 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6191 // VPSHUFB may be generated if
6192 // (1) one of input vector is undefined or zeroinitializer.
6193 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6194 // And (2) the mask indexes don't cross the 128-bit lane.
6195 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6196 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6199 if (V1IsAllZero && !V2IsAllZero) {
6200 CommuteVectorShuffleMask(MaskVals, 32);
6203 SmallVector<SDValue, 32> pshufbMask;
6204 for (unsigned i = 0; i != 32; i++) {
6205 int EltIdx = MaskVals[i];
6206 if (EltIdx < 0 || EltIdx >= 32)
6209 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6210 // Cross lane is not allowed.
6214 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6216 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6217 DAG.getNode(ISD::BUILD_VECTOR, dl,
6218 MVT::v32i8, &pshufbMask[0], 32));
6221 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6222 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6223 /// done when every pair / quad of shuffle mask elements point to elements in
6224 /// the right sequence. e.g.
6225 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6227 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6228 SelectionDAG &DAG) {
6229 MVT VT = SVOp->getValueType(0).getSimpleVT();
6231 unsigned NumElems = VT.getVectorNumElements();
6234 switch (VT.SimpleTy) {
6235 default: llvm_unreachable("Unexpected!");
6236 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6237 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6238 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6239 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6240 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6241 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6244 SmallVector<int, 8> MaskVec;
6245 for (unsigned i = 0; i != NumElems; i += Scale) {
6247 for (unsigned j = 0; j != Scale; ++j) {
6248 int EltIdx = SVOp->getMaskElt(i+j);
6252 StartIdx = (EltIdx / Scale);
6253 if (EltIdx != (int)(StartIdx*Scale + j))
6256 MaskVec.push_back(StartIdx);
6259 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6260 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6261 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6264 /// getVZextMovL - Return a zero-extending vector move low node.
6266 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6267 SDValue SrcOp, SelectionDAG &DAG,
6268 const X86Subtarget *Subtarget, SDLoc dl) {
6269 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6270 LoadSDNode *LD = NULL;
6271 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6272 LD = dyn_cast<LoadSDNode>(SrcOp);
6274 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6276 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6277 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6278 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6279 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6280 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6282 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6283 return DAG.getNode(ISD::BITCAST, dl, VT,
6284 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6285 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6293 return DAG.getNode(ISD::BITCAST, dl, VT,
6294 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6295 DAG.getNode(ISD::BITCAST, dl,
6299 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6300 /// which could not be matched by any known target speficic shuffle
6302 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6304 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6305 if (NewOp.getNode())
6308 MVT VT = SVOp->getValueType(0).getSimpleVT();
6310 unsigned NumElems = VT.getVectorNumElements();
6311 unsigned NumLaneElems = NumElems / 2;
6314 MVT EltVT = VT.getVectorElementType();
6315 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6318 SmallVector<int, 16> Mask;
6319 for (unsigned l = 0; l < 2; ++l) {
6320 // Build a shuffle mask for the output, discovering on the fly which
6321 // input vectors to use as shuffle operands (recorded in InputUsed).
6322 // If building a suitable shuffle vector proves too hard, then bail
6323 // out with UseBuildVector set.
6324 bool UseBuildVector = false;
6325 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6326 unsigned LaneStart = l * NumLaneElems;
6327 for (unsigned i = 0; i != NumLaneElems; ++i) {
6328 // The mask element. This indexes into the input.
6329 int Idx = SVOp->getMaskElt(i+LaneStart);
6331 // the mask element does not index into any input vector.
6336 // The input vector this mask element indexes into.
6337 int Input = Idx / NumLaneElems;
6339 // Turn the index into an offset from the start of the input vector.
6340 Idx -= Input * NumLaneElems;
6342 // Find or create a shuffle vector operand to hold this input.
6344 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6345 if (InputUsed[OpNo] == Input)
6346 // This input vector is already an operand.
6348 if (InputUsed[OpNo] < 0) {
6349 // Create a new operand for this input vector.
6350 InputUsed[OpNo] = Input;
6355 if (OpNo >= array_lengthof(InputUsed)) {
6356 // More than two input vectors used! Give up on trying to create a
6357 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6358 UseBuildVector = true;
6362 // Add the mask index for the new shuffle vector.
6363 Mask.push_back(Idx + OpNo * NumLaneElems);
6366 if (UseBuildVector) {
6367 SmallVector<SDValue, 16> SVOps;
6368 for (unsigned i = 0; i != NumLaneElems; ++i) {
6369 // The mask element. This indexes into the input.
6370 int Idx = SVOp->getMaskElt(i+LaneStart);
6372 SVOps.push_back(DAG.getUNDEF(EltVT));
6376 // The input vector this mask element indexes into.
6377 int Input = Idx / NumElems;
6379 // Turn the index into an offset from the start of the input vector.
6380 Idx -= Input * NumElems;
6382 // Extract the vector element by hand.
6383 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6384 SVOp->getOperand(Input),
6385 DAG.getIntPtrConstant(Idx)));
6388 // Construct the output using a BUILD_VECTOR.
6389 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6391 } else if (InputUsed[0] < 0) {
6392 // No input vectors were used! The result is undefined.
6393 Output[l] = DAG.getUNDEF(NVT);
6395 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6396 (InputUsed[0] % 2) * NumLaneElems,
6398 // If only one input was used, use an undefined vector for the other.
6399 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6400 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6401 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6402 // At least one input vector was used. Create a new shuffle vector.
6403 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6409 // Concatenate the result back
6410 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6413 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6414 /// 4 elements, and match them with several different shuffle types.
6416 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6417 SDValue V1 = SVOp->getOperand(0);
6418 SDValue V2 = SVOp->getOperand(1);
6420 MVT VT = SVOp->getValueType(0).getSimpleVT();
6422 assert(VT.is128BitVector() && "Unsupported vector size");
6424 std::pair<int, int> Locs[4];
6425 int Mask1[] = { -1, -1, -1, -1 };
6426 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6430 for (unsigned i = 0; i != 4; ++i) {
6431 int Idx = PermMask[i];
6433 Locs[i] = std::make_pair(-1, -1);
6435 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6437 Locs[i] = std::make_pair(0, NumLo);
6441 Locs[i] = std::make_pair(1, NumHi);
6443 Mask1[2+NumHi] = Idx;
6449 if (NumLo <= 2 && NumHi <= 2) {
6450 // If no more than two elements come from either vector. This can be
6451 // implemented with two shuffles. First shuffle gather the elements.
6452 // The second shuffle, which takes the first shuffle as both of its
6453 // vector operands, put the elements into the right order.
6454 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6456 int Mask2[] = { -1, -1, -1, -1 };
6458 for (unsigned i = 0; i != 4; ++i)
6459 if (Locs[i].first != -1) {
6460 unsigned Idx = (i < 2) ? 0 : 4;
6461 Idx += Locs[i].first * 2 + Locs[i].second;
6465 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6468 if (NumLo == 3 || NumHi == 3) {
6469 // Otherwise, we must have three elements from one vector, call it X, and
6470 // one element from the other, call it Y. First, use a shufps to build an
6471 // intermediate vector with the one element from Y and the element from X
6472 // that will be in the same half in the final destination (the indexes don't
6473 // matter). Then, use a shufps to build the final vector, taking the half
6474 // containing the element from Y from the intermediate, and the other half
6477 // Normalize it so the 3 elements come from V1.
6478 CommuteVectorShuffleMask(PermMask, 4);
6482 // Find the element from V2.
6484 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6485 int Val = PermMask[HiIndex];
6492 Mask1[0] = PermMask[HiIndex];
6494 Mask1[2] = PermMask[HiIndex^1];
6496 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6499 Mask1[0] = PermMask[0];
6500 Mask1[1] = PermMask[1];
6501 Mask1[2] = HiIndex & 1 ? 6 : 4;
6502 Mask1[3] = HiIndex & 1 ? 4 : 6;
6503 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6506 Mask1[0] = HiIndex & 1 ? 2 : 0;
6507 Mask1[1] = HiIndex & 1 ? 0 : 2;
6508 Mask1[2] = PermMask[2];
6509 Mask1[3] = PermMask[3];
6514 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6517 // Break it into (shuffle shuffle_hi, shuffle_lo).
6518 int LoMask[] = { -1, -1, -1, -1 };
6519 int HiMask[] = { -1, -1, -1, -1 };
6521 int *MaskPtr = LoMask;
6522 unsigned MaskIdx = 0;
6525 for (unsigned i = 0; i != 4; ++i) {
6532 int Idx = PermMask[i];
6534 Locs[i] = std::make_pair(-1, -1);
6535 } else if (Idx < 4) {
6536 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6537 MaskPtr[LoIdx] = Idx;
6540 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6541 MaskPtr[HiIdx] = Idx;
6546 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6547 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6548 int MaskOps[] = { -1, -1, -1, -1 };
6549 for (unsigned i = 0; i != 4; ++i)
6550 if (Locs[i].first != -1)
6551 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6552 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6555 static bool MayFoldVectorLoad(SDValue V) {
6556 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6557 V = V.getOperand(0);
6559 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6560 V = V.getOperand(0);
6561 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6562 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6563 // BUILD_VECTOR (load), undef
6564 V = V.getOperand(0);
6566 return MayFoldLoad(V);
6570 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6571 EVT VT = Op.getValueType();
6573 // Canonizalize to v2f64.
6574 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6575 return DAG.getNode(ISD::BITCAST, dl, VT,
6576 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6581 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6583 SDValue V1 = Op.getOperand(0);
6584 SDValue V2 = Op.getOperand(1);
6585 EVT VT = Op.getValueType();
6587 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6589 if (HasSSE2 && VT == MVT::v2f64)
6590 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6592 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6593 return DAG.getNode(ISD::BITCAST, dl, VT,
6594 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6595 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6596 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6600 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6601 SDValue V1 = Op.getOperand(0);
6602 SDValue V2 = Op.getOperand(1);
6603 EVT VT = Op.getValueType();
6605 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6606 "unsupported shuffle type");
6608 if (V2.getOpcode() == ISD::UNDEF)
6612 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6616 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6617 SDValue V1 = Op.getOperand(0);
6618 SDValue V2 = Op.getOperand(1);
6619 EVT VT = Op.getValueType();
6620 unsigned NumElems = VT.getVectorNumElements();
6622 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6623 // operand of these instructions is only memory, so check if there's a
6624 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6626 bool CanFoldLoad = false;
6628 // Trivial case, when V2 comes from a load.
6629 if (MayFoldVectorLoad(V2))
6632 // When V1 is a load, it can be folded later into a store in isel, example:
6633 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6635 // (MOVLPSmr addr:$src1, VR128:$src2)
6636 // So, recognize this potential and also use MOVLPS or MOVLPD
6637 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6640 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6642 if (HasSSE2 && NumElems == 2)
6643 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6646 // If we don't care about the second element, proceed to use movss.
6647 if (SVOp->getMaskElt(1) != -1)
6648 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6651 // movl and movlp will both match v2i64, but v2i64 is never matched by
6652 // movl earlier because we make it strict to avoid messing with the movlp load
6653 // folding logic (see the code above getMOVLP call). Match it here then,
6654 // this is horrible, but will stay like this until we move all shuffle
6655 // matching to x86 specific nodes. Note that for the 1st condition all
6656 // types are matched with movsd.
6658 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6659 // as to remove this logic from here, as much as possible
6660 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6661 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6662 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6665 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6667 // Invert the operand order and use SHUFPS to match it.
6668 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6669 getShuffleSHUFImmediate(SVOp), DAG);
6672 // Reduce a vector shuffle to zext.
6674 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6675 // PMOVZX is only available from SSE41.
6676 if (!Subtarget->hasSSE41())
6679 EVT VT = Op.getValueType();
6681 // Only AVX2 support 256-bit vector integer extending.
6682 if (!Subtarget->hasInt256() && VT.is256BitVector())
6685 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6687 SDValue V1 = Op.getOperand(0);
6688 SDValue V2 = Op.getOperand(1);
6689 unsigned NumElems = VT.getVectorNumElements();
6691 // Extending is an unary operation and the element type of the source vector
6692 // won't be equal to or larger than i64.
6693 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6694 VT.getVectorElementType() == MVT::i64)
6697 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6698 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6699 while ((1U << Shift) < NumElems) {
6700 if (SVOp->getMaskElt(1U << Shift) == 1)
6703 // The maximal ratio is 8, i.e. from i8 to i64.
6708 // Check the shuffle mask.
6709 unsigned Mask = (1U << Shift) - 1;
6710 for (unsigned i = 0; i != NumElems; ++i) {
6711 int EltIdx = SVOp->getMaskElt(i);
6712 if ((i & Mask) != 0 && EltIdx != -1)
6714 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6718 LLVMContext *Context = DAG.getContext();
6719 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6720 EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6721 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6723 if (!isTypeLegal(NVT))
6726 // Simplify the operand as it's prepared to be fed into shuffle.
6727 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6728 if (V1.getOpcode() == ISD::BITCAST &&
6729 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6730 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6732 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6733 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6734 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6735 ConstantSDNode *CIdx =
6736 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6737 // If it's foldable, i.e. normal load with single use, we will let code
6738 // selection to fold it. Otherwise, we will short the conversion sequence.
6739 if (CIdx && CIdx->getZExtValue() == 0 &&
6740 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6741 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6742 // The "ext_vec_elt" node is wider than the result node.
6743 // In this case we should extract subvector from V.
6744 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6745 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6746 EVT FullVT = V.getValueType();
6747 EVT SubVecVT = EVT::getVectorVT(*Context,
6748 FullVT.getVectorElementType(),
6749 FullVT.getVectorNumElements()/Ratio);
6750 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6751 DAG.getIntPtrConstant(0));
6753 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6757 return DAG.getNode(ISD::BITCAST, DL, VT,
6758 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6762 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6763 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6764 MVT VT = Op.getValueType().getSimpleVT();
6766 SDValue V1 = Op.getOperand(0);
6767 SDValue V2 = Op.getOperand(1);
6769 if (isZeroShuffle(SVOp))
6770 return getZeroVector(VT, Subtarget, DAG, dl);
6772 // Handle splat operations
6773 if (SVOp->isSplat()) {
6774 // Use vbroadcast whenever the splat comes from a foldable load
6775 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6776 if (Broadcast.getNode())
6780 // Check integer expanding shuffles.
6781 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6782 if (NewOp.getNode())
6785 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6787 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6788 VT == MVT::v16i16 || VT == MVT::v32i8) {
6789 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6790 if (NewOp.getNode())
6791 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6792 } else if ((VT == MVT::v4i32 ||
6793 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6794 // FIXME: Figure out a cleaner way to do this.
6795 // Try to make use of movq to zero out the top part.
6796 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6797 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6798 if (NewOp.getNode()) {
6799 MVT NewVT = NewOp.getValueType().getSimpleVT();
6800 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6801 NewVT, true, false))
6802 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6803 DAG, Subtarget, dl);
6805 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6806 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6807 if (NewOp.getNode()) {
6808 MVT NewVT = NewOp.getValueType().getSimpleVT();
6809 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6810 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6811 DAG, Subtarget, dl);
6819 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6820 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6821 SDValue V1 = Op.getOperand(0);
6822 SDValue V2 = Op.getOperand(1);
6823 MVT VT = Op.getValueType().getSimpleVT();
6825 unsigned NumElems = VT.getVectorNumElements();
6826 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6827 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6828 bool V1IsSplat = false;
6829 bool V2IsSplat = false;
6830 bool HasSSE2 = Subtarget->hasSSE2();
6831 bool HasFp256 = Subtarget->hasFp256();
6832 bool HasInt256 = Subtarget->hasInt256();
6833 MachineFunction &MF = DAG.getMachineFunction();
6834 bool OptForSize = MF.getFunction()->getAttributes().
6835 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6837 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6839 if (V1IsUndef && V2IsUndef)
6840 return DAG.getUNDEF(VT);
6842 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6844 // Vector shuffle lowering takes 3 steps:
6846 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6847 // narrowing and commutation of operands should be handled.
6848 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6850 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6851 // so the shuffle can be broken into other shuffles and the legalizer can
6852 // try the lowering again.
6854 // The general idea is that no vector_shuffle operation should be left to
6855 // be matched during isel, all of them must be converted to a target specific
6858 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6859 // narrowing and commutation of operands should be handled. The actual code
6860 // doesn't include all of those, work in progress...
6861 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6862 if (NewOp.getNode())
6865 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6867 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6868 // unpckh_undef). Only use pshufd if speed is more important than size.
6869 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6870 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6871 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6872 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6874 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6875 V2IsUndef && MayFoldVectorLoad(V1))
6876 return getMOVDDup(Op, dl, V1, DAG);
6878 if (isMOVHLPS_v_undef_Mask(M, VT))
6879 return getMOVHighToLow(Op, dl, DAG);
6881 // Use to match splats
6882 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6883 (VT == MVT::v2f64 || VT == MVT::v2i64))
6884 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6886 if (isPSHUFDMask(M, VT)) {
6887 // The actual implementation will match the mask in the if above and then
6888 // during isel it can match several different instructions, not only pshufd
6889 // as its name says, sad but true, emulate the behavior for now...
6890 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6891 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6893 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6895 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6896 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6898 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6899 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6902 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6906 if (isPALIGNRMask(M, VT, Subtarget))
6907 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6908 getShufflePALIGNRImmediate(SVOp),
6911 // Check if this can be converted into a logical shift.
6912 bool isLeft = false;
6915 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6916 if (isShift && ShVal.hasOneUse()) {
6917 // If the shifted value has multiple uses, it may be cheaper to use
6918 // v_set0 + movlhps or movhlps, etc.
6919 MVT EltVT = VT.getVectorElementType();
6920 ShAmt *= EltVT.getSizeInBits();
6921 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6924 if (isMOVLMask(M, VT)) {
6925 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6926 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6927 if (!isMOVLPMask(M, VT)) {
6928 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6929 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6931 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6932 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6936 // FIXME: fold these into legal mask.
6937 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6938 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6940 if (isMOVHLPSMask(M, VT))
6941 return getMOVHighToLow(Op, dl, DAG);
6943 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6944 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6946 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6947 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6949 if (isMOVLPMask(M, VT))
6950 return getMOVLP(Op, dl, DAG, HasSSE2);
6952 if (ShouldXformToMOVHLPS(M, VT) ||
6953 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6954 return CommuteVectorShuffle(SVOp, DAG);
6957 // No better options. Use a vshldq / vsrldq.
6958 MVT EltVT = VT.getVectorElementType();
6959 ShAmt *= EltVT.getSizeInBits();
6960 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6963 bool Commuted = false;
6964 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6965 // 1,1,1,1 -> v8i16 though.
6966 V1IsSplat = isSplatVector(V1.getNode());
6967 V2IsSplat = isSplatVector(V2.getNode());
6969 // Canonicalize the splat or undef, if present, to be on the RHS.
6970 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6971 CommuteVectorShuffleMask(M, NumElems);
6973 std::swap(V1IsSplat, V2IsSplat);
6977 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6978 // Shuffling low element of v1 into undef, just return v1.
6981 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6982 // the instruction selector will not match, so get a canonical MOVL with
6983 // swapped operands to undo the commute.
6984 return getMOVL(DAG, dl, VT, V2, V1);
6987 if (isUNPCKLMask(M, VT, HasInt256))
6988 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6990 if (isUNPCKHMask(M, VT, HasInt256))
6991 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6994 // Normalize mask so all entries that point to V2 points to its first
6995 // element then try to match unpck{h|l} again. If match, return a
6996 // new vector_shuffle with the corrected mask.p
6997 SmallVector<int, 8> NewMask(M.begin(), M.end());
6998 NormalizeMask(NewMask, NumElems);
6999 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7000 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7001 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7002 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7006 // Commute is back and try unpck* again.
7007 // FIXME: this seems wrong.
7008 CommuteVectorShuffleMask(M, NumElems);
7010 std::swap(V1IsSplat, V2IsSplat);
7013 if (isUNPCKLMask(M, VT, HasInt256))
7014 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7016 if (isUNPCKHMask(M, VT, HasInt256))
7017 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7020 // Normalize the node to match x86 shuffle ops if needed
7021 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7022 return CommuteVectorShuffle(SVOp, DAG);
7024 // The checks below are all present in isShuffleMaskLegal, but they are
7025 // inlined here right now to enable us to directly emit target specific
7026 // nodes, and remove one by one until they don't return Op anymore.
7028 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7029 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7030 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7031 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7034 if (isPSHUFHWMask(M, VT, HasInt256))
7035 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7036 getShufflePSHUFHWImmediate(SVOp),
7039 if (isPSHUFLWMask(M, VT, HasInt256))
7040 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7041 getShufflePSHUFLWImmediate(SVOp),
7044 if (isSHUFPMask(M, VT, HasFp256))
7045 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7046 getShuffleSHUFImmediate(SVOp), DAG);
7048 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7049 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7050 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7051 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7053 //===--------------------------------------------------------------------===//
7054 // Generate target specific nodes for 128 or 256-bit shuffles only
7055 // supported in the AVX instruction set.
7058 // Handle VMOVDDUPY permutations
7059 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7060 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7062 // Handle VPERMILPS/D* permutations
7063 if (isVPERMILPMask(M, VT, HasFp256)) {
7064 if (HasInt256 && VT == MVT::v8i32)
7065 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7066 getShuffleSHUFImmediate(SVOp), DAG);
7067 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7068 getShuffleSHUFImmediate(SVOp), DAG);
7071 // Handle VPERM2F128/VPERM2I128 permutations
7072 if (isVPERM2X128Mask(M, VT, HasFp256))
7073 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7074 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7076 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7077 if (BlendOp.getNode())
7080 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7081 SmallVector<SDValue, 8> permclMask;
7082 for (unsigned i = 0; i != 8; ++i) {
7083 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7085 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7087 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7088 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7089 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7092 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7093 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7094 getShuffleCLImmediate(SVOp), DAG);
7096 //===--------------------------------------------------------------------===//
7097 // Since no target specific shuffle was selected for this generic one,
7098 // lower it into other known shuffles. FIXME: this isn't true yet, but
7099 // this is the plan.
7102 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7103 if (VT == MVT::v8i16) {
7104 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7105 if (NewOp.getNode())
7109 if (VT == MVT::v16i8) {
7110 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7111 if (NewOp.getNode())
7115 if (VT == MVT::v32i8) {
7116 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7117 if (NewOp.getNode())
7121 // Handle all 128-bit wide vectors with 4 elements, and match them with
7122 // several different shuffle types.
7123 if (NumElems == 4 && VT.is128BitVector())
7124 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7126 // Handle general 256-bit shuffles
7127 if (VT.is256BitVector())
7128 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7133 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7134 MVT VT = Op.getValueType().getSimpleVT();
7137 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7140 if (VT.getSizeInBits() == 8) {
7141 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7142 Op.getOperand(0), Op.getOperand(1));
7143 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7144 DAG.getValueType(VT));
7145 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7148 if (VT.getSizeInBits() == 16) {
7149 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7150 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7152 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7153 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7154 DAG.getNode(ISD::BITCAST, dl,
7158 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7159 Op.getOperand(0), Op.getOperand(1));
7160 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7161 DAG.getValueType(VT));
7162 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7165 if (VT == MVT::f32) {
7166 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7167 // the result back to FR32 register. It's only worth matching if the
7168 // result has a single use which is a store or a bitcast to i32. And in
7169 // the case of a store, it's not worth it if the index is a constant 0,
7170 // because a MOVSSmr can be used instead, which is smaller and faster.
7171 if (!Op.hasOneUse())
7173 SDNode *User = *Op.getNode()->use_begin();
7174 if ((User->getOpcode() != ISD::STORE ||
7175 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7176 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7177 (User->getOpcode() != ISD::BITCAST ||
7178 User->getValueType(0) != MVT::i32))
7180 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7181 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7184 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7187 if (VT == MVT::i32 || VT == MVT::i64) {
7188 // ExtractPS/pextrq works with constant index.
7189 if (isa<ConstantSDNode>(Op.getOperand(1)))
7196 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7197 SelectionDAG &DAG) const {
7198 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7201 SDValue Vec = Op.getOperand(0);
7202 MVT VecVT = Vec.getValueType().getSimpleVT();
7204 // If this is a 256-bit vector result, first extract the 128-bit vector and
7205 // then extract the element from the 128-bit vector.
7206 if (VecVT.is256BitVector()) {
7207 SDLoc dl(Op.getNode());
7208 unsigned NumElems = VecVT.getVectorNumElements();
7209 SDValue Idx = Op.getOperand(1);
7210 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7212 // Get the 128-bit vector.
7213 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7215 if (IdxVal >= NumElems/2)
7216 IdxVal -= NumElems/2;
7217 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7218 DAG.getConstant(IdxVal, MVT::i32));
7221 assert(VecVT.is128BitVector() && "Unexpected vector length");
7223 if (Subtarget->hasSSE41()) {
7224 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7229 MVT VT = Op.getValueType().getSimpleVT();
7231 // TODO: handle v16i8.
7232 if (VT.getSizeInBits() == 16) {
7233 SDValue Vec = Op.getOperand(0);
7234 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7236 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7237 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7238 DAG.getNode(ISD::BITCAST, dl,
7241 // Transform it so it match pextrw which produces a 32-bit result.
7242 MVT EltVT = MVT::i32;
7243 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7244 Op.getOperand(0), Op.getOperand(1));
7245 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7246 DAG.getValueType(VT));
7247 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7250 if (VT.getSizeInBits() == 32) {
7251 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7255 // SHUFPS the element to the lowest double word, then movss.
7256 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7257 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7258 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7259 DAG.getUNDEF(VVT), Mask);
7260 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7261 DAG.getIntPtrConstant(0));
7264 if (VT.getSizeInBits() == 64) {
7265 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7266 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7267 // to match extract_elt for f64.
7268 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7272 // UNPCKHPD the element to the lowest double word, then movsd.
7273 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7274 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7275 int Mask[2] = { 1, -1 };
7276 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7277 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7278 DAG.getUNDEF(VVT), Mask);
7279 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7280 DAG.getIntPtrConstant(0));
7286 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7287 MVT VT = Op.getValueType().getSimpleVT();
7288 MVT EltVT = VT.getVectorElementType();
7291 SDValue N0 = Op.getOperand(0);
7292 SDValue N1 = Op.getOperand(1);
7293 SDValue N2 = Op.getOperand(2);
7295 if (!VT.is128BitVector())
7298 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7299 isa<ConstantSDNode>(N2)) {
7301 if (VT == MVT::v8i16)
7302 Opc = X86ISD::PINSRW;
7303 else if (VT == MVT::v16i8)
7304 Opc = X86ISD::PINSRB;
7306 Opc = X86ISD::PINSRB;
7308 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7310 if (N1.getValueType() != MVT::i32)
7311 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7312 if (N2.getValueType() != MVT::i32)
7313 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7314 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7317 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7318 // Bits [7:6] of the constant are the source select. This will always be
7319 // zero here. The DAG Combiner may combine an extract_elt index into these
7320 // bits. For example (insert (extract, 3), 2) could be matched by putting
7321 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7322 // Bits [5:4] of the constant are the destination select. This is the
7323 // value of the incoming immediate.
7324 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7325 // combine either bitwise AND or insert of float 0.0 to set these bits.
7326 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7327 // Create this as a scalar to vector..
7328 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7329 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7332 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7333 // PINSR* works with constant index.
7340 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7341 MVT VT = Op.getValueType().getSimpleVT();
7342 MVT EltVT = VT.getVectorElementType();
7345 SDValue N0 = Op.getOperand(0);
7346 SDValue N1 = Op.getOperand(1);
7347 SDValue N2 = Op.getOperand(2);
7349 // If this is a 256-bit vector result, first extract the 128-bit vector,
7350 // insert the element into the extracted half and then place it back.
7351 if (VT.is256BitVector()) {
7352 if (!isa<ConstantSDNode>(N2))
7355 // Get the desired 128-bit vector half.
7356 unsigned NumElems = VT.getVectorNumElements();
7357 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7358 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7360 // Insert the element into the desired half.
7361 bool Upper = IdxVal >= NumElems/2;
7362 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7363 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7365 // Insert the changed part back to the 256-bit vector
7366 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7369 if (Subtarget->hasSSE41())
7370 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7372 if (EltVT == MVT::i8)
7375 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7376 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7377 // as its second argument.
7378 if (N1.getValueType() != MVT::i32)
7379 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7380 if (N2.getValueType() != MVT::i32)
7381 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7382 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7387 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7388 LLVMContext *Context = DAG.getContext();
7390 MVT OpVT = Op.getValueType().getSimpleVT();
7392 // If this is a 256-bit vector result, first insert into a 128-bit
7393 // vector and then insert into the 256-bit vector.
7394 if (!OpVT.is128BitVector()) {
7395 // Insert into a 128-bit vector.
7396 EVT VT128 = EVT::getVectorVT(*Context,
7397 OpVT.getVectorElementType(),
7398 OpVT.getVectorNumElements() / 2);
7400 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7402 // Insert the 128-bit vector.
7403 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7406 if (OpVT == MVT::v1i64 &&
7407 Op.getOperand(0).getValueType() == MVT::i64)
7408 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7410 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7411 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7412 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7413 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7416 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7417 // a simple subregister reference or explicit instructions to grab
7418 // upper bits of a vector.
7419 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7420 SelectionDAG &DAG) {
7421 if (Subtarget->hasFp256()) {
7422 SDLoc dl(Op.getNode());
7423 SDValue Vec = Op.getNode()->getOperand(0);
7424 SDValue Idx = Op.getNode()->getOperand(1);
7426 if (Op.getNode()->getValueType(0).is128BitVector() &&
7427 Vec.getNode()->getValueType(0).is256BitVector() &&
7428 isa<ConstantSDNode>(Idx)) {
7429 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7430 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7436 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7437 // simple superregister reference or explicit instructions to insert
7438 // the upper bits of a vector.
7439 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7440 SelectionDAG &DAG) {
7441 if (Subtarget->hasFp256()) {
7442 SDLoc dl(Op.getNode());
7443 SDValue Vec = Op.getNode()->getOperand(0);
7444 SDValue SubVec = Op.getNode()->getOperand(1);
7445 SDValue Idx = Op.getNode()->getOperand(2);
7447 if (Op.getNode()->getValueType(0).is256BitVector() &&
7448 SubVec.getNode()->getValueType(0).is128BitVector() &&
7449 isa<ConstantSDNode>(Idx)) {
7450 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7451 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7457 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7458 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7459 // one of the above mentioned nodes. It has to be wrapped because otherwise
7460 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7461 // be used to form addressing mode. These wrapped nodes will be selected
7464 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7465 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7467 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7469 unsigned char OpFlag = 0;
7470 unsigned WrapperKind = X86ISD::Wrapper;
7471 CodeModel::Model M = getTargetMachine().getCodeModel();
7473 if (Subtarget->isPICStyleRIPRel() &&
7474 (M == CodeModel::Small || M == CodeModel::Kernel))
7475 WrapperKind = X86ISD::WrapperRIP;
7476 else if (Subtarget->isPICStyleGOT())
7477 OpFlag = X86II::MO_GOTOFF;
7478 else if (Subtarget->isPICStyleStubPIC())
7479 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7481 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7483 CP->getOffset(), OpFlag);
7485 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7486 // With PIC, the address is actually $g + Offset.
7488 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7489 DAG.getNode(X86ISD::GlobalBaseReg,
7490 SDLoc(), getPointerTy()),
7497 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7498 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7500 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7502 unsigned char OpFlag = 0;
7503 unsigned WrapperKind = X86ISD::Wrapper;
7504 CodeModel::Model M = getTargetMachine().getCodeModel();
7506 if (Subtarget->isPICStyleRIPRel() &&
7507 (M == CodeModel::Small || M == CodeModel::Kernel))
7508 WrapperKind = X86ISD::WrapperRIP;
7509 else if (Subtarget->isPICStyleGOT())
7510 OpFlag = X86II::MO_GOTOFF;
7511 else if (Subtarget->isPICStyleStubPIC())
7512 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7514 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7517 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7519 // With PIC, the address is actually $g + Offset.
7521 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7522 DAG.getNode(X86ISD::GlobalBaseReg,
7523 SDLoc(), getPointerTy()),
7530 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7531 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7533 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7535 unsigned char OpFlag = 0;
7536 unsigned WrapperKind = X86ISD::Wrapper;
7537 CodeModel::Model M = getTargetMachine().getCodeModel();
7539 if (Subtarget->isPICStyleRIPRel() &&
7540 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7541 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7542 OpFlag = X86II::MO_GOTPCREL;
7543 WrapperKind = X86ISD::WrapperRIP;
7544 } else if (Subtarget->isPICStyleGOT()) {
7545 OpFlag = X86II::MO_GOT;
7546 } else if (Subtarget->isPICStyleStubPIC()) {
7547 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7548 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7549 OpFlag = X86II::MO_DARWIN_NONLAZY;
7552 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7555 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7557 // With PIC, the address is actually $g + Offset.
7558 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7559 !Subtarget->is64Bit()) {
7560 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7561 DAG.getNode(X86ISD::GlobalBaseReg,
7562 SDLoc(), getPointerTy()),
7566 // For symbols that require a load from a stub to get the address, emit the
7568 if (isGlobalStubReference(OpFlag))
7569 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7570 MachinePointerInfo::getGOT(), false, false, false, 0);
7576 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7577 // Create the TargetBlockAddressAddress node.
7578 unsigned char OpFlags =
7579 Subtarget->ClassifyBlockAddressReference();
7580 CodeModel::Model M = getTargetMachine().getCodeModel();
7581 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7582 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7584 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7587 if (Subtarget->isPICStyleRIPRel() &&
7588 (M == CodeModel::Small || M == CodeModel::Kernel))
7589 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7591 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7593 // With PIC, the address is actually $g + Offset.
7594 if (isGlobalRelativeToPICBase(OpFlags)) {
7595 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7596 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7604 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7605 int64_t Offset, SelectionDAG &DAG) const {
7606 // Create the TargetGlobalAddress node, folding in the constant
7607 // offset if it is legal.
7608 unsigned char OpFlags =
7609 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7610 CodeModel::Model M = getTargetMachine().getCodeModel();
7612 if (OpFlags == X86II::MO_NO_FLAG &&
7613 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7614 // A direct static reference to a global.
7615 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7618 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7621 if (Subtarget->isPICStyleRIPRel() &&
7622 (M == CodeModel::Small || M == CodeModel::Kernel))
7623 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7625 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7627 // With PIC, the address is actually $g + Offset.
7628 if (isGlobalRelativeToPICBase(OpFlags)) {
7629 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7630 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7634 // For globals that require a load from a stub to get the address, emit the
7636 if (isGlobalStubReference(OpFlags))
7637 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7638 MachinePointerInfo::getGOT(), false, false, false, 0);
7640 // If there was a non-zero offset that we didn't fold, create an explicit
7643 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7644 DAG.getConstant(Offset, getPointerTy()));
7650 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7651 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7652 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7653 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7657 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7658 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7659 unsigned char OperandFlags, bool LocalDynamic = false) {
7660 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7661 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7663 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7664 GA->getValueType(0),
7668 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7672 SDValue Ops[] = { Chain, TGA, *InFlag };
7673 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7675 SDValue Ops[] = { Chain, TGA };
7676 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7679 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7680 MFI->setAdjustsStack(true);
7682 SDValue Flag = Chain.getValue(1);
7683 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7686 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7688 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7691 SDLoc dl(GA); // ? function entry point might be better
7692 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7693 DAG.getNode(X86ISD::GlobalBaseReg,
7694 SDLoc(), PtrVT), InFlag);
7695 InFlag = Chain.getValue(1);
7697 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7700 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7702 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7704 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7705 X86::RAX, X86II::MO_TLSGD);
7708 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7714 // Get the start address of the TLS block for this module.
7715 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7716 .getInfo<X86MachineFunctionInfo>();
7717 MFI->incNumLocalDynamicTLSAccesses();
7721 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7722 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7725 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7726 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7727 InFlag = Chain.getValue(1);
7728 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7729 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7732 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7736 unsigned char OperandFlags = X86II::MO_DTPOFF;
7737 unsigned WrapperKind = X86ISD::Wrapper;
7738 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7739 GA->getValueType(0),
7740 GA->getOffset(), OperandFlags);
7741 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7743 // Add x@dtpoff with the base.
7744 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7747 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7748 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7749 const EVT PtrVT, TLSModel::Model model,
7750 bool is64Bit, bool isPIC) {
7753 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7754 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7755 is64Bit ? 257 : 256));
7757 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7758 DAG.getIntPtrConstant(0),
7759 MachinePointerInfo(Ptr),
7760 false, false, false, 0);
7762 unsigned char OperandFlags = 0;
7763 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7765 unsigned WrapperKind = X86ISD::Wrapper;
7766 if (model == TLSModel::LocalExec) {
7767 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7768 } else if (model == TLSModel::InitialExec) {
7770 OperandFlags = X86II::MO_GOTTPOFF;
7771 WrapperKind = X86ISD::WrapperRIP;
7773 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7776 llvm_unreachable("Unexpected model");
7779 // emit "addl x@ntpoff,%eax" (local exec)
7780 // or "addl x@indntpoff,%eax" (initial exec)
7781 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7782 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7783 GA->getValueType(0),
7784 GA->getOffset(), OperandFlags);
7785 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7787 if (model == TLSModel::InitialExec) {
7788 if (isPIC && !is64Bit) {
7789 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7790 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
7794 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7795 MachinePointerInfo::getGOT(), false, false, false,
7799 // The address of the thread local variable is the add of the thread
7800 // pointer with the offset of the variable.
7801 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7805 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7807 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7808 const GlobalValue *GV = GA->getGlobal();
7810 if (Subtarget->isTargetELF()) {
7811 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7814 case TLSModel::GeneralDynamic:
7815 if (Subtarget->is64Bit())
7816 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7817 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7818 case TLSModel::LocalDynamic:
7819 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7820 Subtarget->is64Bit());
7821 case TLSModel::InitialExec:
7822 case TLSModel::LocalExec:
7823 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7824 Subtarget->is64Bit(),
7825 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7827 llvm_unreachable("Unknown TLS model.");
7830 if (Subtarget->isTargetDarwin()) {
7831 // Darwin only has one model of TLS. Lower to that.
7832 unsigned char OpFlag = 0;
7833 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7834 X86ISD::WrapperRIP : X86ISD::Wrapper;
7836 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7838 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7839 !Subtarget->is64Bit();
7841 OpFlag = X86II::MO_TLVP_PIC_BASE;
7843 OpFlag = X86II::MO_TLVP;
7845 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7846 GA->getValueType(0),
7847 GA->getOffset(), OpFlag);
7848 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7850 // With PIC32, the address is actually $g + Offset.
7852 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7853 DAG.getNode(X86ISD::GlobalBaseReg,
7854 SDLoc(), getPointerTy()),
7857 // Lowering the machine isd will make sure everything is in the right
7859 SDValue Chain = DAG.getEntryNode();
7860 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7861 SDValue Args[] = { Chain, Offset };
7862 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7864 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7865 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7866 MFI->setAdjustsStack(true);
7868 // And our return value (tls address) is in the standard call return value
7870 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7871 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7875 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7876 // Just use the implicit TLS architecture
7877 // Need to generate someting similar to:
7878 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7880 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7881 // mov rcx, qword [rdx+rcx*8]
7882 // mov eax, .tls$:tlsvar
7883 // [rax+rcx] contains the address
7884 // Windows 64bit: gs:0x58
7885 // Windows 32bit: fs:__tls_array
7887 // If GV is an alias then use the aliasee for determining
7888 // thread-localness.
7889 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7890 GV = GA->resolveAliasedGlobal(false);
7892 SDValue Chain = DAG.getEntryNode();
7894 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7895 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7896 // use its literal value of 0x2C.
7897 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7898 ? Type::getInt8PtrTy(*DAG.getContext(),
7900 : Type::getInt32PtrTy(*DAG.getContext(),
7903 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7904 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7905 DAG.getExternalSymbol("_tls_array", getPointerTy()));
7907 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7908 MachinePointerInfo(Ptr),
7909 false, false, false, 0);
7911 // Load the _tls_index variable
7912 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7913 if (Subtarget->is64Bit())
7914 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7915 IDX, MachinePointerInfo(), MVT::i32,
7918 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7919 false, false, false, 0);
7921 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7923 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7925 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7926 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7927 false, false, false, 0);
7929 // Get the offset of start of .tls section
7930 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7931 GA->getValueType(0),
7932 GA->getOffset(), X86II::MO_SECREL);
7933 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7935 // The address of the thread local variable is the add of the thread
7936 // pointer with the offset of the variable.
7937 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7940 llvm_unreachable("TLS not implemented for this target.");
7943 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7944 /// and take a 2 x i32 value to shift plus a shift amount.
7945 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7946 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7947 EVT VT = Op.getValueType();
7948 unsigned VTBits = VT.getSizeInBits();
7950 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7951 SDValue ShOpLo = Op.getOperand(0);
7952 SDValue ShOpHi = Op.getOperand(1);
7953 SDValue ShAmt = Op.getOperand(2);
7954 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7955 DAG.getConstant(VTBits - 1, MVT::i8))
7956 : DAG.getConstant(0, VT);
7959 if (Op.getOpcode() == ISD::SHL_PARTS) {
7960 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7961 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7963 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7964 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7967 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7968 DAG.getConstant(VTBits, MVT::i8));
7969 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7970 AndNode, DAG.getConstant(0, MVT::i8));
7973 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7974 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7975 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7977 if (Op.getOpcode() == ISD::SHL_PARTS) {
7978 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7979 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7981 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7982 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7985 SDValue Ops[2] = { Lo, Hi };
7986 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7989 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7990 SelectionDAG &DAG) const {
7991 EVT SrcVT = Op.getOperand(0).getValueType();
7993 if (SrcVT.isVector())
7996 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7997 "Unknown SINT_TO_FP to lower!");
7999 // These are really Legal; return the operand so the caller accepts it as
8001 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8003 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8004 Subtarget->is64Bit()) {
8009 unsigned Size = SrcVT.getSizeInBits()/8;
8010 MachineFunction &MF = DAG.getMachineFunction();
8011 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8012 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8013 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8015 MachinePointerInfo::getFixedStack(SSFI),
8017 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8020 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8022 SelectionDAG &DAG) const {
8026 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8028 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8030 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8032 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8034 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8035 MachineMemOperand *MMO;
8037 int SSFI = FI->getIndex();
8039 DAG.getMachineFunction()
8040 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8041 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8043 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8044 StackSlot = StackSlot.getOperand(1);
8046 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8047 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8049 Tys, Ops, array_lengthof(Ops),
8053 Chain = Result.getValue(1);
8054 SDValue InFlag = Result.getValue(2);
8056 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8057 // shouldn't be necessary except that RFP cannot be live across
8058 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8059 MachineFunction &MF = DAG.getMachineFunction();
8060 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8061 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8062 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8063 Tys = DAG.getVTList(MVT::Other);
8065 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8067 MachineMemOperand *MMO =
8068 DAG.getMachineFunction()
8069 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8070 MachineMemOperand::MOStore, SSFISize, SSFISize);
8072 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8073 Ops, array_lengthof(Ops),
8074 Op.getValueType(), MMO);
8075 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8076 MachinePointerInfo::getFixedStack(SSFI),
8077 false, false, false, 0);
8083 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8084 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8085 SelectionDAG &DAG) const {
8086 // This algorithm is not obvious. Here it is what we're trying to output:
8089 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8090 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8094 pshufd $0x4e, %xmm0, %xmm1
8100 LLVMContext *Context = DAG.getContext();
8102 // Build some magic constants.
8103 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8104 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8105 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8107 SmallVector<Constant*,2> CV1;
8109 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8110 APInt(64, 0x4330000000000000ULL))));
8112 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8113 APInt(64, 0x4530000000000000ULL))));
8114 Constant *C1 = ConstantVector::get(CV1);
8115 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8117 // Load the 64-bit value into an XMM register.
8118 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8120 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8121 MachinePointerInfo::getConstantPool(),
8122 false, false, false, 16);
8123 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8124 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8127 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8128 MachinePointerInfo::getConstantPool(),
8129 false, false, false, 16);
8130 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8131 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8134 if (Subtarget->hasSSE3()) {
8135 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8136 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8138 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8139 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8141 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8142 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8146 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8147 DAG.getIntPtrConstant(0));
8150 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8151 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8152 SelectionDAG &DAG) const {
8154 // FP constant to bias correct the final result.
8155 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8158 // Load the 32-bit value into an XMM register.
8159 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8162 // Zero out the upper parts of the register.
8163 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8165 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8166 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8167 DAG.getIntPtrConstant(0));
8169 // Or the load with the bias.
8170 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8171 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8172 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8174 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8175 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8176 MVT::v2f64, Bias)));
8177 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8178 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8179 DAG.getIntPtrConstant(0));
8181 // Subtract the bias.
8182 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8184 // Handle final rounding.
8185 EVT DestVT = Op.getValueType();
8187 if (DestVT.bitsLT(MVT::f64))
8188 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8189 DAG.getIntPtrConstant(0));
8190 if (DestVT.bitsGT(MVT::f64))
8191 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8193 // Handle final rounding.
8197 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8198 SelectionDAG &DAG) const {
8199 SDValue N0 = Op.getOperand(0);
8200 EVT SVT = N0.getValueType();
8203 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8204 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8205 "Custom UINT_TO_FP is not supported!");
8207 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8208 SVT.getVectorNumElements());
8209 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8210 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8213 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8214 SelectionDAG &DAG) const {
8215 SDValue N0 = Op.getOperand(0);
8218 if (Op.getValueType().isVector())
8219 return lowerUINT_TO_FP_vec(Op, DAG);
8221 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8222 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8223 // the optimization here.
8224 if (DAG.SignBitIsZero(N0))
8225 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8227 EVT SrcVT = N0.getValueType();
8228 EVT DstVT = Op.getValueType();
8229 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8230 return LowerUINT_TO_FP_i64(Op, DAG);
8231 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8232 return LowerUINT_TO_FP_i32(Op, DAG);
8233 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8236 // Make a 64-bit buffer, and use it to build an FILD.
8237 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8238 if (SrcVT == MVT::i32) {
8239 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8240 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8241 getPointerTy(), StackSlot, WordOff);
8242 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8243 StackSlot, MachinePointerInfo(),
8245 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8246 OffsetSlot, MachinePointerInfo(),
8248 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8252 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8253 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8254 StackSlot, MachinePointerInfo(),
8256 // For i64 source, we need to add the appropriate power of 2 if the input
8257 // was negative. This is the same as the optimization in
8258 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8259 // we must be careful to do the computation in x87 extended precision, not
8260 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8261 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8262 MachineMemOperand *MMO =
8263 DAG.getMachineFunction()
8264 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8265 MachineMemOperand::MOLoad, 8, 8);
8267 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8268 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8269 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8270 array_lengthof(Ops), MVT::i64, MMO);
8272 APInt FF(32, 0x5F800000ULL);
8274 // Check whether the sign bit is set.
8275 SDValue SignSet = DAG.getSetCC(dl,
8276 getSetCCResultType(*DAG.getContext(), MVT::i64),
8277 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8280 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8281 SDValue FudgePtr = DAG.getConstantPool(
8282 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8285 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8286 SDValue Zero = DAG.getIntPtrConstant(0);
8287 SDValue Four = DAG.getIntPtrConstant(4);
8288 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8290 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8292 // Load the value out, extending it from f32 to f80.
8293 // FIXME: Avoid the extend by constructing the right constant pool?
8294 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8295 FudgePtr, MachinePointerInfo::getConstantPool(),
8296 MVT::f32, false, false, 4);
8297 // Extend everything to 80 bits to force it to be done on x87.
8298 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8299 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8302 std::pair<SDValue,SDValue>
8303 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8304 bool IsSigned, bool IsReplace) const {
8307 EVT DstTy = Op.getValueType();
8309 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8310 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8314 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8315 DstTy.getSimpleVT() >= MVT::i16 &&
8316 "Unknown FP_TO_INT to lower!");
8318 // These are really Legal.
8319 if (DstTy == MVT::i32 &&
8320 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8321 return std::make_pair(SDValue(), SDValue());
8322 if (Subtarget->is64Bit() &&
8323 DstTy == MVT::i64 &&
8324 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8325 return std::make_pair(SDValue(), SDValue());
8327 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8328 // stack slot, or into the FTOL runtime function.
8329 MachineFunction &MF = DAG.getMachineFunction();
8330 unsigned MemSize = DstTy.getSizeInBits()/8;
8331 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8332 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8335 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8336 Opc = X86ISD::WIN_FTOL;
8338 switch (DstTy.getSimpleVT().SimpleTy) {
8339 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8340 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8341 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8342 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8345 SDValue Chain = DAG.getEntryNode();
8346 SDValue Value = Op.getOperand(0);
8347 EVT TheVT = Op.getOperand(0).getValueType();
8348 // FIXME This causes a redundant load/store if the SSE-class value is already
8349 // in memory, such as if it is on the callstack.
8350 if (isScalarFPTypeInSSEReg(TheVT)) {
8351 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8352 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8353 MachinePointerInfo::getFixedStack(SSFI),
8355 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8357 Chain, StackSlot, DAG.getValueType(TheVT)
8360 MachineMemOperand *MMO =
8361 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8362 MachineMemOperand::MOLoad, MemSize, MemSize);
8363 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8364 array_lengthof(Ops), DstTy, MMO);
8365 Chain = Value.getValue(1);
8366 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8367 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8370 MachineMemOperand *MMO =
8371 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8372 MachineMemOperand::MOStore, MemSize, MemSize);
8374 if (Opc != X86ISD::WIN_FTOL) {
8375 // Build the FP_TO_INT*_IN_MEM
8376 SDValue Ops[] = { Chain, Value, StackSlot };
8377 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8378 Ops, array_lengthof(Ops), DstTy,
8380 return std::make_pair(FIST, StackSlot);
8382 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8383 DAG.getVTList(MVT::Other, MVT::Glue),
8385 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8386 MVT::i32, ftol.getValue(1));
8387 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8388 MVT::i32, eax.getValue(2));
8389 SDValue Ops[] = { eax, edx };
8390 SDValue pair = IsReplace
8391 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8392 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8393 return std::make_pair(pair, SDValue());
8397 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8398 const X86Subtarget *Subtarget) {
8399 MVT VT = Op->getValueType(0).getSimpleVT();
8400 SDValue In = Op->getOperand(0);
8401 MVT InVT = In.getValueType().getSimpleVT();
8404 // Optimize vectors in AVX mode:
8407 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8408 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8409 // Concat upper and lower parts.
8412 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8413 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8414 // Concat upper and lower parts.
8417 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8418 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8421 if (Subtarget->hasInt256())
8422 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8424 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8425 SDValue Undef = DAG.getUNDEF(InVT);
8426 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8427 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8428 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8430 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8431 VT.getVectorNumElements()/2);
8433 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8434 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8436 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8439 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8440 SelectionDAG &DAG) const {
8441 if (Subtarget->hasFp256()) {
8442 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8449 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8450 SelectionDAG &DAG) const {
8452 MVT VT = Op.getValueType().getSimpleVT();
8453 SDValue In = Op.getOperand(0);
8454 MVT SVT = In.getValueType().getSimpleVT();
8456 if (Subtarget->hasFp256()) {
8457 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8462 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8463 VT.getVectorNumElements() != SVT.getVectorNumElements())
8466 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8468 // AVX2 has better support of integer extending.
8469 if (Subtarget->hasInt256())
8470 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8472 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8473 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8474 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8475 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8476 DAG.getUNDEF(MVT::v8i16),
8479 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8482 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8484 MVT VT = Op.getValueType().getSimpleVT();
8485 SDValue In = Op.getOperand(0);
8486 MVT SVT = In.getValueType().getSimpleVT();
8488 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8489 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8490 if (Subtarget->hasInt256()) {
8491 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8492 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8493 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8495 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8496 DAG.getIntPtrConstant(0));
8499 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8500 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8501 DAG.getIntPtrConstant(0));
8502 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8503 DAG.getIntPtrConstant(2));
8505 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8506 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8509 static const int ShufMask1[] = {0, 2, 0, 0};
8510 SDValue Undef = DAG.getUNDEF(VT);
8511 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8512 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8514 // The MOVLHPS mask:
8515 static const int ShufMask2[] = {0, 1, 4, 5};
8516 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8519 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8520 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8521 if (Subtarget->hasInt256()) {
8522 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8524 SmallVector<SDValue,32> pshufbMask;
8525 for (unsigned i = 0; i < 2; ++i) {
8526 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8527 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8528 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8529 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8530 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8531 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8532 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8533 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8534 for (unsigned j = 0; j < 8; ++j)
8535 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8537 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8538 &pshufbMask[0], 32);
8539 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8540 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8542 static const int ShufMask[] = {0, 2, -1, -1};
8543 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8545 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8546 DAG.getIntPtrConstant(0));
8547 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8550 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8551 DAG.getIntPtrConstant(0));
8553 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8554 DAG.getIntPtrConstant(4));
8556 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8557 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8560 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8561 -1, -1, -1, -1, -1, -1, -1, -1};
8563 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8564 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8565 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8567 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8568 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8570 // The MOVLHPS Mask:
8571 static const int ShufMask2[] = {0, 1, 4, 5};
8572 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8573 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8576 // Handle truncation of V256 to V128 using shuffles.
8577 if (!VT.is128BitVector() || !SVT.is256BitVector())
8580 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8582 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8584 unsigned NumElems = VT.getVectorNumElements();
8585 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8588 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8589 // Prepare truncation shuffle mask
8590 for (unsigned i = 0; i != NumElems; ++i)
8592 SDValue V = DAG.getVectorShuffle(NVT, DL,
8593 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8594 DAG.getUNDEF(NVT), &MaskVec[0]);
8595 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8596 DAG.getIntPtrConstant(0));
8599 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8600 SelectionDAG &DAG) const {
8601 MVT VT = Op.getValueType().getSimpleVT();
8602 if (VT.isVector()) {
8603 if (VT == MVT::v8i16)
8604 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8605 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8606 MVT::v8i32, Op.getOperand(0)));
8610 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8611 /*IsSigned=*/ true, /*IsReplace=*/ false);
8612 SDValue FIST = Vals.first, StackSlot = Vals.second;
8613 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8614 if (FIST.getNode() == 0) return Op;
8616 if (StackSlot.getNode())
8618 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8619 FIST, StackSlot, MachinePointerInfo(),
8620 false, false, false, 0);
8622 // The node is the result.
8626 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8627 SelectionDAG &DAG) const {
8628 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8629 /*IsSigned=*/ false, /*IsReplace=*/ false);
8630 SDValue FIST = Vals.first, StackSlot = Vals.second;
8631 assert(FIST.getNode() && "Unexpected failure");
8633 if (StackSlot.getNode())
8635 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8636 FIST, StackSlot, MachinePointerInfo(),
8637 false, false, false, 0);
8639 // The node is the result.
8643 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8645 MVT VT = Op.getValueType().getSimpleVT();
8646 SDValue In = Op.getOperand(0);
8647 MVT SVT = In.getValueType().getSimpleVT();
8649 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8651 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8652 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8653 In, DAG.getUNDEF(SVT)));
8656 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8657 LLVMContext *Context = DAG.getContext();
8659 MVT VT = Op.getValueType().getSimpleVT();
8661 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8662 if (VT.isVector()) {
8663 EltVT = VT.getVectorElementType();
8664 NumElts = VT.getVectorNumElements();
8667 if (EltVT == MVT::f64)
8668 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8669 APInt(64, ~(1ULL << 63))));
8671 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8672 APInt(32, ~(1U << 31))));
8673 C = ConstantVector::getSplat(NumElts, C);
8674 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8675 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8676 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8677 MachinePointerInfo::getConstantPool(),
8678 false, false, false, Alignment);
8679 if (VT.isVector()) {
8680 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8681 return DAG.getNode(ISD::BITCAST, dl, VT,
8682 DAG.getNode(ISD::AND, dl, ANDVT,
8683 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8685 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8687 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8690 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8691 LLVMContext *Context = DAG.getContext();
8693 MVT VT = Op.getValueType().getSimpleVT();
8695 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8696 if (VT.isVector()) {
8697 EltVT = VT.getVectorElementType();
8698 NumElts = VT.getVectorNumElements();
8701 if (EltVT == MVT::f64)
8702 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8703 APInt(64, 1ULL << 63)));
8705 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8706 APInt(32, 1U << 31)));
8707 C = ConstantVector::getSplat(NumElts, C);
8708 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8709 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8710 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8711 MachinePointerInfo::getConstantPool(),
8712 false, false, false, Alignment);
8713 if (VT.isVector()) {
8714 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8715 return DAG.getNode(ISD::BITCAST, dl, VT,
8716 DAG.getNode(ISD::XOR, dl, XORVT,
8717 DAG.getNode(ISD::BITCAST, dl, XORVT,
8719 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8722 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8725 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8726 LLVMContext *Context = DAG.getContext();
8727 SDValue Op0 = Op.getOperand(0);
8728 SDValue Op1 = Op.getOperand(1);
8730 MVT VT = Op.getValueType().getSimpleVT();
8731 MVT SrcVT = Op1.getValueType().getSimpleVT();
8733 // If second operand is smaller, extend it first.
8734 if (SrcVT.bitsLT(VT)) {
8735 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8738 // And if it is bigger, shrink it first.
8739 if (SrcVT.bitsGT(VT)) {
8740 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8744 // At this point the operands and the result should have the same
8745 // type, and that won't be f80 since that is not custom lowered.
8747 // First get the sign bit of second operand.
8748 SmallVector<Constant*,4> CV;
8749 if (SrcVT == MVT::f64) {
8750 const fltSemantics &Sem = APFloat::IEEEdouble;
8751 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8752 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8754 const fltSemantics &Sem = APFloat::IEEEsingle;
8755 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8756 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8757 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8758 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8760 Constant *C = ConstantVector::get(CV);
8761 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8762 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8763 MachinePointerInfo::getConstantPool(),
8764 false, false, false, 16);
8765 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8767 // Shift sign bit right or left if the two operands have different types.
8768 if (SrcVT.bitsGT(VT)) {
8769 // Op0 is MVT::f32, Op1 is MVT::f64.
8770 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8771 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8772 DAG.getConstant(32, MVT::i32));
8773 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8774 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8775 DAG.getIntPtrConstant(0));
8778 // Clear first operand sign bit.
8780 if (VT == MVT::f64) {
8781 const fltSemantics &Sem = APFloat::IEEEdouble;
8782 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8783 APInt(64, ~(1ULL << 63)))));
8784 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8786 const fltSemantics &Sem = APFloat::IEEEsingle;
8787 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8788 APInt(32, ~(1U << 31)))));
8789 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8790 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8791 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8793 C = ConstantVector::get(CV);
8794 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8795 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8796 MachinePointerInfo::getConstantPool(),
8797 false, false, false, 16);
8798 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8800 // Or the value with the sign bit.
8801 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8804 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8805 SDValue N0 = Op.getOperand(0);
8807 MVT VT = Op.getValueType().getSimpleVT();
8809 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8810 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8811 DAG.getConstant(1, VT));
8812 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8815 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8817 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8818 SelectionDAG &DAG) const {
8819 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8821 if (!Subtarget->hasSSE41())
8824 if (!Op->hasOneUse())
8827 SDNode *N = Op.getNode();
8830 SmallVector<SDValue, 8> Opnds;
8831 DenseMap<SDValue, unsigned> VecInMap;
8832 EVT VT = MVT::Other;
8834 // Recognize a special case where a vector is casted into wide integer to
8836 Opnds.push_back(N->getOperand(0));
8837 Opnds.push_back(N->getOperand(1));
8839 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8840 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
8841 // BFS traverse all OR'd operands.
8842 if (I->getOpcode() == ISD::OR) {
8843 Opnds.push_back(I->getOperand(0));
8844 Opnds.push_back(I->getOperand(1));
8845 // Re-evaluate the number of nodes to be traversed.
8846 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8850 // Quit if a non-EXTRACT_VECTOR_ELT
8851 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8854 // Quit if without a constant index.
8855 SDValue Idx = I->getOperand(1);
8856 if (!isa<ConstantSDNode>(Idx))
8859 SDValue ExtractedFromVec = I->getOperand(0);
8860 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8861 if (M == VecInMap.end()) {
8862 VT = ExtractedFromVec.getValueType();
8863 // Quit if not 128/256-bit vector.
8864 if (!VT.is128BitVector() && !VT.is256BitVector())
8866 // Quit if not the same type.
8867 if (VecInMap.begin() != VecInMap.end() &&
8868 VT != VecInMap.begin()->first.getValueType())
8870 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8872 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8875 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8876 "Not extracted from 128-/256-bit vector.");
8878 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8879 SmallVector<SDValue, 8> VecIns;
8881 for (DenseMap<SDValue, unsigned>::const_iterator
8882 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8883 // Quit if not all elements are used.
8884 if (I->second != FullMask)
8886 VecIns.push_back(I->first);
8889 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8891 // Cast all vectors into TestVT for PTEST.
8892 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8893 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8895 // If more than one full vectors are evaluated, OR them first before PTEST.
8896 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8897 // Each iteration will OR 2 nodes and append the result until there is only
8898 // 1 node left, i.e. the final OR'd value of all vectors.
8899 SDValue LHS = VecIns[Slot];
8900 SDValue RHS = VecIns[Slot + 1];
8901 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8904 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8905 VecIns.back(), VecIns.back());
8908 /// Emit nodes that will be selected as "test Op0,Op0", or something
8910 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8911 SelectionDAG &DAG) const {
8914 // CF and OF aren't always set the way we want. Determine which
8915 // of these we need.
8916 bool NeedCF = false;
8917 bool NeedOF = false;
8920 case X86::COND_A: case X86::COND_AE:
8921 case X86::COND_B: case X86::COND_BE:
8924 case X86::COND_G: case X86::COND_GE:
8925 case X86::COND_L: case X86::COND_LE:
8926 case X86::COND_O: case X86::COND_NO:
8931 // See if we can use the EFLAGS value from the operand instead of
8932 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8933 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8934 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8935 // Emit a CMP with 0, which is the TEST pattern.
8936 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8937 DAG.getConstant(0, Op.getValueType()));
8939 unsigned Opcode = 0;
8940 unsigned NumOperands = 0;
8942 // Truncate operations may prevent the merge of the SETCC instruction
8943 // and the arithmetic intruction before it. Attempt to truncate the operands
8944 // of the arithmetic instruction and use a reduced bit-width instruction.
8945 bool NeedTruncation = false;
8946 SDValue ArithOp = Op;
8947 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8948 SDValue Arith = Op->getOperand(0);
8949 // Both the trunc and the arithmetic op need to have one user each.
8950 if (Arith->hasOneUse())
8951 switch (Arith.getOpcode()) {
8958 NeedTruncation = true;
8964 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8965 // which may be the result of a CAST. We use the variable 'Op', which is the
8966 // non-casted variable when we check for possible users.
8967 switch (ArithOp.getOpcode()) {
8969 // Due to an isel shortcoming, be conservative if this add is likely to be
8970 // selected as part of a load-modify-store instruction. When the root node
8971 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8972 // uses of other nodes in the match, such as the ADD in this case. This
8973 // leads to the ADD being left around and reselected, with the result being
8974 // two adds in the output. Alas, even if none our users are stores, that
8975 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8976 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8977 // climbing the DAG back to the root, and it doesn't seem to be worth the
8979 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8980 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8981 if (UI->getOpcode() != ISD::CopyToReg &&
8982 UI->getOpcode() != ISD::SETCC &&
8983 UI->getOpcode() != ISD::STORE)
8986 if (ConstantSDNode *C =
8987 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8988 // An add of one will be selected as an INC.
8989 if (C->getAPIntValue() == 1) {
8990 Opcode = X86ISD::INC;
8995 // An add of negative one (subtract of one) will be selected as a DEC.
8996 if (C->getAPIntValue().isAllOnesValue()) {
8997 Opcode = X86ISD::DEC;
9003 // Otherwise use a regular EFLAGS-setting add.
9004 Opcode = X86ISD::ADD;
9008 // If the primary and result isn't used, don't bother using X86ISD::AND,
9009 // because a TEST instruction will be better.
9010 bool NonFlagUse = false;
9011 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9012 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9014 unsigned UOpNo = UI.getOperandNo();
9015 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9016 // Look pass truncate.
9017 UOpNo = User->use_begin().getOperandNo();
9018 User = *User->use_begin();
9021 if (User->getOpcode() != ISD::BRCOND &&
9022 User->getOpcode() != ISD::SETCC &&
9023 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9036 // Due to the ISEL shortcoming noted above, be conservative if this op is
9037 // likely to be selected as part of a load-modify-store instruction.
9038 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9039 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9040 if (UI->getOpcode() == ISD::STORE)
9043 // Otherwise use a regular EFLAGS-setting instruction.
9044 switch (ArithOp.getOpcode()) {
9045 default: llvm_unreachable("unexpected operator!");
9046 case ISD::SUB: Opcode = X86ISD::SUB; break;
9047 case ISD::XOR: Opcode = X86ISD::XOR; break;
9048 case ISD::AND: Opcode = X86ISD::AND; break;
9050 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9051 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9052 if (EFLAGS.getNode())
9055 Opcode = X86ISD::OR;
9069 return SDValue(Op.getNode(), 1);
9075 // If we found that truncation is beneficial, perform the truncation and
9077 if (NeedTruncation) {
9078 EVT VT = Op.getValueType();
9079 SDValue WideVal = Op->getOperand(0);
9080 EVT WideVT = WideVal.getValueType();
9081 unsigned ConvertedOp = 0;
9082 // Use a target machine opcode to prevent further DAGCombine
9083 // optimizations that may separate the arithmetic operations
9084 // from the setcc node.
9085 switch (WideVal.getOpcode()) {
9087 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9088 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9089 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9090 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9091 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9095 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9096 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9097 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9098 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9099 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9105 // Emit a CMP with 0, which is the TEST pattern.
9106 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9107 DAG.getConstant(0, Op.getValueType()));
9109 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9110 SmallVector<SDValue, 4> Ops;
9111 for (unsigned i = 0; i != NumOperands; ++i)
9112 Ops.push_back(Op.getOperand(i));
9114 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9115 DAG.ReplaceAllUsesWith(Op, New);
9116 return SDValue(New.getNode(), 1);
9119 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9121 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9122 SelectionDAG &DAG) const {
9123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9124 if (C->getAPIntValue() == 0)
9125 return EmitTest(Op0, X86CC, DAG);
9128 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9129 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9130 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9131 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9132 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9134 return SDValue(Sub.getNode(), 1);
9136 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9139 /// Convert a comparison if required by the subtarget.
9140 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9141 SelectionDAG &DAG) const {
9142 // If the subtarget does not support the FUCOMI instruction, floating-point
9143 // comparisons have to be converted.
9144 if (Subtarget->hasCMov() ||
9145 Cmp.getOpcode() != X86ISD::CMP ||
9146 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9147 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9150 // The instruction selector will select an FUCOM instruction instead of
9151 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9152 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9153 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9155 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9156 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9157 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9158 DAG.getConstant(8, MVT::i8));
9159 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9160 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9163 static bool isAllOnes(SDValue V) {
9164 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9165 return C && C->isAllOnesValue();
9168 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9169 /// if it's possible.
9170 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9171 SDLoc dl, SelectionDAG &DAG) const {
9172 SDValue Op0 = And.getOperand(0);
9173 SDValue Op1 = And.getOperand(1);
9174 if (Op0.getOpcode() == ISD::TRUNCATE)
9175 Op0 = Op0.getOperand(0);
9176 if (Op1.getOpcode() == ISD::TRUNCATE)
9177 Op1 = Op1.getOperand(0);
9180 if (Op1.getOpcode() == ISD::SHL)
9181 std::swap(Op0, Op1);
9182 if (Op0.getOpcode() == ISD::SHL) {
9183 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9184 if (And00C->getZExtValue() == 1) {
9185 // If we looked past a truncate, check that it's only truncating away
9187 unsigned BitWidth = Op0.getValueSizeInBits();
9188 unsigned AndBitWidth = And.getValueSizeInBits();
9189 if (BitWidth > AndBitWidth) {
9191 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9192 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9196 RHS = Op0.getOperand(1);
9198 } else if (Op1.getOpcode() == ISD::Constant) {
9199 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9200 uint64_t AndRHSVal = AndRHS->getZExtValue();
9201 SDValue AndLHS = Op0;
9203 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9204 LHS = AndLHS.getOperand(0);
9205 RHS = AndLHS.getOperand(1);
9208 // Use BT if the immediate can't be encoded in a TEST instruction.
9209 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9211 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9215 if (LHS.getNode()) {
9216 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9217 // instruction. Since the shift amount is in-range-or-undefined, we know
9218 // that doing a bittest on the i32 value is ok. We extend to i32 because
9219 // the encoding for the i16 version is larger than the i32 version.
9220 // Also promote i16 to i32 for performance / code size reason.
9221 if (LHS.getValueType() == MVT::i8 ||
9222 LHS.getValueType() == MVT::i16)
9223 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9225 // If the operand types disagree, extend the shift amount to match. Since
9226 // BT ignores high bits (like shifts) we can use anyextend.
9227 if (LHS.getValueType() != RHS.getValueType())
9228 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9230 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9231 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9232 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9233 DAG.getConstant(Cond, MVT::i8), BT);
9239 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9240 // ones, and then concatenate the result back.
9241 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9242 MVT VT = Op.getValueType().getSimpleVT();
9244 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9245 "Unsupported value type for operation");
9247 unsigned NumElems = VT.getVectorNumElements();
9249 SDValue CC = Op.getOperand(2);
9251 // Extract the LHS vectors
9252 SDValue LHS = Op.getOperand(0);
9253 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9254 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9256 // Extract the RHS vectors
9257 SDValue RHS = Op.getOperand(1);
9258 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9259 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9261 // Issue the operation on the smaller types and concatenate the result back
9262 MVT EltVT = VT.getVectorElementType();
9263 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9264 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9265 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9266 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9269 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9270 SelectionDAG &DAG) {
9272 SDValue Op0 = Op.getOperand(0);
9273 SDValue Op1 = Op.getOperand(1);
9274 SDValue CC = Op.getOperand(2);
9275 MVT VT = Op.getValueType().getSimpleVT();
9276 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9277 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9282 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9283 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9289 // SSE Condition code mapping:
9298 switch (SetCCOpcode) {
9299 default: llvm_unreachable("Unexpected SETCC condition");
9301 case ISD::SETEQ: SSECC = 0; break;
9303 case ISD::SETGT: Swap = true; // Fallthrough
9305 case ISD::SETOLT: SSECC = 1; break;
9307 case ISD::SETGE: Swap = true; // Fallthrough
9309 case ISD::SETOLE: SSECC = 2; break;
9310 case ISD::SETUO: SSECC = 3; break;
9312 case ISD::SETNE: SSECC = 4; break;
9313 case ISD::SETULE: Swap = true; // Fallthrough
9314 case ISD::SETUGE: SSECC = 5; break;
9315 case ISD::SETULT: Swap = true; // Fallthrough
9316 case ISD::SETUGT: SSECC = 6; break;
9317 case ISD::SETO: SSECC = 7; break;
9319 case ISD::SETONE: SSECC = 8; break;
9322 std::swap(Op0, Op1);
9324 // In the two special cases we can't handle, emit two comparisons.
9327 unsigned CombineOpc;
9328 if (SetCCOpcode == ISD::SETUEQ) {
9329 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9331 assert(SetCCOpcode == ISD::SETONE);
9332 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9335 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9336 DAG.getConstant(CC0, MVT::i8));
9337 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9338 DAG.getConstant(CC1, MVT::i8));
9339 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9341 // Handle all other FP comparisons here.
9342 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9343 DAG.getConstant(SSECC, MVT::i8));
9346 // Break 256-bit integer vector compare into smaller ones.
9347 if (VT.is256BitVector() && !Subtarget->hasInt256())
9348 return Lower256IntVSETCC(Op, DAG);
9350 // We are handling one of the integer comparisons here. Since SSE only has
9351 // GT and EQ comparisons for integer, swapping operands and multiple
9352 // operations may be required for some comparisons.
9354 bool Swap = false, Invert = false, FlipSigns = false;
9356 switch (SetCCOpcode) {
9357 default: llvm_unreachable("Unexpected SETCC condition");
9358 case ISD::SETNE: Invert = true;
9359 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9360 case ISD::SETLT: Swap = true;
9361 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9362 case ISD::SETGE: Swap = true;
9363 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9364 case ISD::SETULT: Swap = true;
9365 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9366 case ISD::SETUGE: Swap = true;
9367 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9370 std::swap(Op0, Op1);
9372 // Check that the operation in question is available (most are plain SSE2,
9373 // but PCMPGTQ and PCMPEQQ have different requirements).
9374 if (VT == MVT::v2i64) {
9375 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9376 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9378 // First cast everything to the right type.
9379 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9380 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9382 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9383 // bits of the inputs before performing those operations. The lower
9384 // compare is always unsigned.
9387 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9389 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9390 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9391 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9392 Sign, Zero, Sign, Zero);
9394 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9395 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9397 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9398 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9399 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9401 // Create masks for only the low parts/high parts of the 64 bit integers.
9402 const int MaskHi[] = { 1, 1, 3, 3 };
9403 const int MaskLo[] = { 0, 0, 2, 2 };
9404 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9405 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9406 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9408 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9409 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9412 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9414 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9417 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9418 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9419 // pcmpeqd + pshufd + pand.
9420 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9422 // First cast everything to the right type.
9423 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9424 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9427 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9429 // Make sure the lower and upper halves are both all-ones.
9430 const int Mask[] = { 1, 0, 3, 2 };
9431 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9432 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9435 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9437 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9441 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9442 // bits of the inputs before performing those operations.
9444 EVT EltVT = VT.getVectorElementType();
9445 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9446 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9447 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9450 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9452 // If the logical-not of the result is required, perform that now.
9454 Result = DAG.getNOT(dl, Result, VT);
9459 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9461 MVT VT = Op.getValueType().getSimpleVT();
9463 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9465 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9466 SDValue Op0 = Op.getOperand(0);
9467 SDValue Op1 = Op.getOperand(1);
9469 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9471 // Optimize to BT if possible.
9472 // Lower (X & (1 << N)) == 0 to BT(X, N).
9473 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9474 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9475 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9476 Op1.getOpcode() == ISD::Constant &&
9477 cast<ConstantSDNode>(Op1)->isNullValue() &&
9478 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9479 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9480 if (NewSetCC.getNode())
9484 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9486 if (Op1.getOpcode() == ISD::Constant &&
9487 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9488 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9489 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9491 // If the input is a setcc, then reuse the input setcc or use a new one with
9492 // the inverted condition.
9493 if (Op0.getOpcode() == X86ISD::SETCC) {
9494 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9495 bool Invert = (CC == ISD::SETNE) ^
9496 cast<ConstantSDNode>(Op1)->isNullValue();
9497 if (!Invert) return Op0;
9499 CCode = X86::GetOppositeBranchCondition(CCode);
9500 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9501 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9505 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9506 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9507 if (X86CC == X86::COND_INVALID)
9510 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9511 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9512 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9513 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9516 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9517 static bool isX86LogicalCmp(SDValue Op) {
9518 unsigned Opc = Op.getNode()->getOpcode();
9519 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9520 Opc == X86ISD::SAHF)
9522 if (Op.getResNo() == 1 &&
9523 (Opc == X86ISD::ADD ||
9524 Opc == X86ISD::SUB ||
9525 Opc == X86ISD::ADC ||
9526 Opc == X86ISD::SBB ||
9527 Opc == X86ISD::SMUL ||
9528 Opc == X86ISD::UMUL ||
9529 Opc == X86ISD::INC ||
9530 Opc == X86ISD::DEC ||
9531 Opc == X86ISD::OR ||
9532 Opc == X86ISD::XOR ||
9533 Opc == X86ISD::AND))
9536 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9542 static bool isZero(SDValue V) {
9543 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9544 return C && C->isNullValue();
9547 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9548 if (V.getOpcode() != ISD::TRUNCATE)
9551 SDValue VOp0 = V.getOperand(0);
9552 unsigned InBits = VOp0.getValueSizeInBits();
9553 unsigned Bits = V.getValueSizeInBits();
9554 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9557 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9558 bool addTest = true;
9559 SDValue Cond = Op.getOperand(0);
9560 SDValue Op1 = Op.getOperand(1);
9561 SDValue Op2 = Op.getOperand(2);
9565 if (Cond.getOpcode() == ISD::SETCC) {
9566 SDValue NewCond = LowerSETCC(Cond, DAG);
9567 if (NewCond.getNode())
9571 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9572 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9573 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9574 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9575 if (Cond.getOpcode() == X86ISD::SETCC &&
9576 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9577 isZero(Cond.getOperand(1).getOperand(1))) {
9578 SDValue Cmp = Cond.getOperand(1);
9580 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9582 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9583 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9584 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9586 SDValue CmpOp0 = Cmp.getOperand(0);
9587 // Apply further optimizations for special cases
9588 // (select (x != 0), -1, 0) -> neg & sbb
9589 // (select (x == 0), 0, -1) -> neg & sbb
9590 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9591 if (YC->isNullValue() &&
9592 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9593 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9594 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9595 DAG.getConstant(0, CmpOp0.getValueType()),
9597 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9598 DAG.getConstant(X86::COND_B, MVT::i8),
9599 SDValue(Neg.getNode(), 1));
9603 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9604 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9605 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9607 SDValue Res = // Res = 0 or -1.
9608 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9609 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9611 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9612 Res = DAG.getNOT(DL, Res, Res.getValueType());
9614 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9615 if (N2C == 0 || !N2C->isNullValue())
9616 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9621 // Look past (and (setcc_carry (cmp ...)), 1).
9622 if (Cond.getOpcode() == ISD::AND &&
9623 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9624 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9625 if (C && C->getAPIntValue() == 1)
9626 Cond = Cond.getOperand(0);
9629 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9630 // setting operand in place of the X86ISD::SETCC.
9631 unsigned CondOpcode = Cond.getOpcode();
9632 if (CondOpcode == X86ISD::SETCC ||
9633 CondOpcode == X86ISD::SETCC_CARRY) {
9634 CC = Cond.getOperand(0);
9636 SDValue Cmp = Cond.getOperand(1);
9637 unsigned Opc = Cmp.getOpcode();
9638 MVT VT = Op.getValueType().getSimpleVT();
9640 bool IllegalFPCMov = false;
9641 if (VT.isFloatingPoint() && !VT.isVector() &&
9642 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9643 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9645 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9646 Opc == X86ISD::BT) { // FIXME
9650 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9651 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9652 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9653 Cond.getOperand(0).getValueType() != MVT::i8)) {
9654 SDValue LHS = Cond.getOperand(0);
9655 SDValue RHS = Cond.getOperand(1);
9659 switch (CondOpcode) {
9660 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9661 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9662 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9663 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9664 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9665 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9666 default: llvm_unreachable("unexpected overflowing operator");
9668 if (CondOpcode == ISD::UMULO)
9669 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9672 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9674 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9676 if (CondOpcode == ISD::UMULO)
9677 Cond = X86Op.getValue(2);
9679 Cond = X86Op.getValue(1);
9681 CC = DAG.getConstant(X86Cond, MVT::i8);
9686 // Look pass the truncate if the high bits are known zero.
9687 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9688 Cond = Cond.getOperand(0);
9690 // We know the result of AND is compared against zero. Try to match
9692 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9693 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9694 if (NewSetCC.getNode()) {
9695 CC = NewSetCC.getOperand(0);
9696 Cond = NewSetCC.getOperand(1);
9703 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9704 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9707 // a < b ? -1 : 0 -> RES = ~setcc_carry
9708 // a < b ? 0 : -1 -> RES = setcc_carry
9709 // a >= b ? -1 : 0 -> RES = setcc_carry
9710 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9711 if (Cond.getOpcode() == X86ISD::SUB) {
9712 Cond = ConvertCmpIfNecessary(Cond, DAG);
9713 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9715 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9716 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9717 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9718 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9719 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9720 return DAG.getNOT(DL, Res, Res.getValueType());
9725 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9726 // widen the cmov and push the truncate through. This avoids introducing a new
9727 // branch during isel and doesn't add any extensions.
9728 if (Op.getValueType() == MVT::i8 &&
9729 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9730 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9731 if (T1.getValueType() == T2.getValueType() &&
9732 // Blacklist CopyFromReg to avoid partial register stalls.
9733 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9734 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9735 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9736 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9740 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9741 // condition is true.
9742 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9743 SDValue Ops[] = { Op2, Op1, CC, Cond };
9744 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9747 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9748 SelectionDAG &DAG) const {
9749 MVT VT = Op->getValueType(0).getSimpleVT();
9750 SDValue In = Op->getOperand(0);
9751 MVT InVT = In.getValueType().getSimpleVT();
9754 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9755 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9758 if (Subtarget->hasInt256())
9759 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9761 // Optimize vectors in AVX mode
9762 // Sign extend v8i16 to v8i32 and
9765 // Divide input vector into two parts
9766 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9767 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9768 // concat the vectors to original VT
9770 unsigned NumElems = InVT.getVectorNumElements();
9771 SDValue Undef = DAG.getUNDEF(InVT);
9773 SmallVector<int,8> ShufMask1(NumElems, -1);
9774 for (unsigned i = 0; i != NumElems/2; ++i)
9777 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9779 SmallVector<int,8> ShufMask2(NumElems, -1);
9780 for (unsigned i = 0; i != NumElems/2; ++i)
9781 ShufMask2[i] = i + NumElems/2;
9783 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9785 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9786 VT.getVectorNumElements()/2);
9788 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9789 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9791 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9794 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9795 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9796 // from the AND / OR.
9797 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9798 Opc = Op.getOpcode();
9799 if (Opc != ISD::OR && Opc != ISD::AND)
9801 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9802 Op.getOperand(0).hasOneUse() &&
9803 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9804 Op.getOperand(1).hasOneUse());
9807 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9808 // 1 and that the SETCC node has a single use.
9809 static bool isXor1OfSetCC(SDValue Op) {
9810 if (Op.getOpcode() != ISD::XOR)
9812 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9813 if (N1C && N1C->getAPIntValue() == 1) {
9814 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9815 Op.getOperand(0).hasOneUse();
9820 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9821 bool addTest = true;
9822 SDValue Chain = Op.getOperand(0);
9823 SDValue Cond = Op.getOperand(1);
9824 SDValue Dest = Op.getOperand(2);
9827 bool Inverted = false;
9829 if (Cond.getOpcode() == ISD::SETCC) {
9830 // Check for setcc([su]{add,sub,mul}o == 0).
9831 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9832 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9833 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9834 Cond.getOperand(0).getResNo() == 1 &&
9835 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9836 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9837 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9838 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9839 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9840 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9842 Cond = Cond.getOperand(0);
9844 SDValue NewCond = LowerSETCC(Cond, DAG);
9845 if (NewCond.getNode())
9850 // FIXME: LowerXALUO doesn't handle these!!
9851 else if (Cond.getOpcode() == X86ISD::ADD ||
9852 Cond.getOpcode() == X86ISD::SUB ||
9853 Cond.getOpcode() == X86ISD::SMUL ||
9854 Cond.getOpcode() == X86ISD::UMUL)
9855 Cond = LowerXALUO(Cond, DAG);
9858 // Look pass (and (setcc_carry (cmp ...)), 1).
9859 if (Cond.getOpcode() == ISD::AND &&
9860 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9861 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9862 if (C && C->getAPIntValue() == 1)
9863 Cond = Cond.getOperand(0);
9866 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9867 // setting operand in place of the X86ISD::SETCC.
9868 unsigned CondOpcode = Cond.getOpcode();
9869 if (CondOpcode == X86ISD::SETCC ||
9870 CondOpcode == X86ISD::SETCC_CARRY) {
9871 CC = Cond.getOperand(0);
9873 SDValue Cmp = Cond.getOperand(1);
9874 unsigned Opc = Cmp.getOpcode();
9875 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9876 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9880 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9884 // These can only come from an arithmetic instruction with overflow,
9885 // e.g. SADDO, UADDO.
9886 Cond = Cond.getNode()->getOperand(1);
9892 CondOpcode = Cond.getOpcode();
9893 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9894 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9895 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9896 Cond.getOperand(0).getValueType() != MVT::i8)) {
9897 SDValue LHS = Cond.getOperand(0);
9898 SDValue RHS = Cond.getOperand(1);
9902 switch (CondOpcode) {
9903 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9904 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9905 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9906 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9907 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9908 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9909 default: llvm_unreachable("unexpected overflowing operator");
9912 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9913 if (CondOpcode == ISD::UMULO)
9914 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9917 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9919 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9921 if (CondOpcode == ISD::UMULO)
9922 Cond = X86Op.getValue(2);
9924 Cond = X86Op.getValue(1);
9926 CC = DAG.getConstant(X86Cond, MVT::i8);
9930 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9931 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9932 if (CondOpc == ISD::OR) {
9933 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9934 // two branches instead of an explicit OR instruction with a
9936 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9937 isX86LogicalCmp(Cmp)) {
9938 CC = Cond.getOperand(0).getOperand(0);
9939 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9940 Chain, Dest, CC, Cmp);
9941 CC = Cond.getOperand(1).getOperand(0);
9945 } else { // ISD::AND
9946 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9947 // two branches instead of an explicit AND instruction with a
9948 // separate test. However, we only do this if this block doesn't
9949 // have a fall-through edge, because this requires an explicit
9950 // jmp when the condition is false.
9951 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9952 isX86LogicalCmp(Cmp) &&
9953 Op.getNode()->hasOneUse()) {
9954 X86::CondCode CCode =
9955 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9956 CCode = X86::GetOppositeBranchCondition(CCode);
9957 CC = DAG.getConstant(CCode, MVT::i8);
9958 SDNode *User = *Op.getNode()->use_begin();
9959 // Look for an unconditional branch following this conditional branch.
9960 // We need this because we need to reverse the successors in order
9961 // to implement FCMP_OEQ.
9962 if (User->getOpcode() == ISD::BR) {
9963 SDValue FalseBB = User->getOperand(1);
9965 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9966 assert(NewBR == User);
9970 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9971 Chain, Dest, CC, Cmp);
9972 X86::CondCode CCode =
9973 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9974 CCode = X86::GetOppositeBranchCondition(CCode);
9975 CC = DAG.getConstant(CCode, MVT::i8);
9981 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9982 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9983 // It should be transformed during dag combiner except when the condition
9984 // is set by a arithmetics with overflow node.
9985 X86::CondCode CCode =
9986 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9987 CCode = X86::GetOppositeBranchCondition(CCode);
9988 CC = DAG.getConstant(CCode, MVT::i8);
9989 Cond = Cond.getOperand(0).getOperand(1);
9991 } else if (Cond.getOpcode() == ISD::SETCC &&
9992 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9993 // For FCMP_OEQ, we can emit
9994 // two branches instead of an explicit AND instruction with a
9995 // separate test. However, we only do this if this block doesn't
9996 // have a fall-through edge, because this requires an explicit
9997 // jmp when the condition is false.
9998 if (Op.getNode()->hasOneUse()) {
9999 SDNode *User = *Op.getNode()->use_begin();
10000 // Look for an unconditional branch following this conditional branch.
10001 // We need this because we need to reverse the successors in order
10002 // to implement FCMP_OEQ.
10003 if (User->getOpcode() == ISD::BR) {
10004 SDValue FalseBB = User->getOperand(1);
10006 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10007 assert(NewBR == User);
10011 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10012 Cond.getOperand(0), Cond.getOperand(1));
10013 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10014 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10015 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10016 Chain, Dest, CC, Cmp);
10017 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10022 } else if (Cond.getOpcode() == ISD::SETCC &&
10023 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10024 // For FCMP_UNE, we can emit
10025 // two branches instead of an explicit AND instruction with a
10026 // separate test. However, we only do this if this block doesn't
10027 // have a fall-through edge, because this requires an explicit
10028 // jmp when the condition is false.
10029 if (Op.getNode()->hasOneUse()) {
10030 SDNode *User = *Op.getNode()->use_begin();
10031 // Look for an unconditional branch following this conditional branch.
10032 // We need this because we need to reverse the successors in order
10033 // to implement FCMP_UNE.
10034 if (User->getOpcode() == ISD::BR) {
10035 SDValue FalseBB = User->getOperand(1);
10037 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10038 assert(NewBR == User);
10041 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10042 Cond.getOperand(0), Cond.getOperand(1));
10043 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10044 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10045 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10046 Chain, Dest, CC, Cmp);
10047 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10057 // Look pass the truncate if the high bits are known zero.
10058 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10059 Cond = Cond.getOperand(0);
10061 // We know the result of AND is compared against zero. Try to match
10063 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10064 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10065 if (NewSetCC.getNode()) {
10066 CC = NewSetCC.getOperand(0);
10067 Cond = NewSetCC.getOperand(1);
10074 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10075 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10077 Cond = ConvertCmpIfNecessary(Cond, DAG);
10078 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10079 Chain, Dest, CC, Cond);
10082 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10083 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10084 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10085 // that the guard pages used by the OS virtual memory manager are allocated in
10086 // correct sequence.
10088 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10089 SelectionDAG &DAG) const {
10090 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10091 getTargetMachine().Options.EnableSegmentedStacks) &&
10092 "This should be used only on Windows targets or when segmented stacks "
10094 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10098 SDValue Chain = Op.getOperand(0);
10099 SDValue Size = Op.getOperand(1);
10100 // FIXME: Ensure alignment here
10102 bool Is64Bit = Subtarget->is64Bit();
10103 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10105 if (getTargetMachine().Options.EnableSegmentedStacks) {
10106 MachineFunction &MF = DAG.getMachineFunction();
10107 MachineRegisterInfo &MRI = MF.getRegInfo();
10110 // The 64 bit implementation of segmented stacks needs to clobber both r10
10111 // r11. This makes it impossible to use it along with nested parameters.
10112 const Function *F = MF.getFunction();
10114 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10116 if (I->hasNestAttr())
10117 report_fatal_error("Cannot use segmented stacks with functions that "
10118 "have nested arguments.");
10121 const TargetRegisterClass *AddrRegClass =
10122 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10123 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10124 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10125 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10126 DAG.getRegister(Vreg, SPTy));
10127 SDValue Ops1[2] = { Value, Chain };
10128 return DAG.getMergeValues(Ops1, 2, dl);
10131 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10133 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10134 Flag = Chain.getValue(1);
10135 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10137 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10138 Flag = Chain.getValue(1);
10140 const X86RegisterInfo *RegInfo =
10141 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10142 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10145 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10146 return DAG.getMergeValues(Ops1, 2, dl);
10150 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10151 MachineFunction &MF = DAG.getMachineFunction();
10152 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10154 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10157 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10158 // vastart just stores the address of the VarArgsFrameIndex slot into the
10159 // memory location argument.
10160 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10162 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10163 MachinePointerInfo(SV), false, false, 0);
10167 // gp_offset (0 - 6 * 8)
10168 // fp_offset (48 - 48 + 8 * 16)
10169 // overflow_arg_area (point to parameters coming in memory).
10171 SmallVector<SDValue, 8> MemOps;
10172 SDValue FIN = Op.getOperand(1);
10174 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10175 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10177 FIN, MachinePointerInfo(SV), false, false, 0);
10178 MemOps.push_back(Store);
10181 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10182 FIN, DAG.getIntPtrConstant(4));
10183 Store = DAG.getStore(Op.getOperand(0), DL,
10184 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10186 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10187 MemOps.push_back(Store);
10189 // Store ptr to overflow_arg_area
10190 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10191 FIN, DAG.getIntPtrConstant(4));
10192 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10194 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10195 MachinePointerInfo(SV, 8),
10197 MemOps.push_back(Store);
10199 // Store ptr to reg_save_area.
10200 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10201 FIN, DAG.getIntPtrConstant(8));
10202 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10204 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10205 MachinePointerInfo(SV, 16), false, false, 0);
10206 MemOps.push_back(Store);
10207 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10208 &MemOps[0], MemOps.size());
10211 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10212 assert(Subtarget->is64Bit() &&
10213 "LowerVAARG only handles 64-bit va_arg!");
10214 assert((Subtarget->isTargetLinux() ||
10215 Subtarget->isTargetDarwin()) &&
10216 "Unhandled target in LowerVAARG");
10217 assert(Op.getNode()->getNumOperands() == 4);
10218 SDValue Chain = Op.getOperand(0);
10219 SDValue SrcPtr = Op.getOperand(1);
10220 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10221 unsigned Align = Op.getConstantOperandVal(3);
10224 EVT ArgVT = Op.getNode()->getValueType(0);
10225 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10226 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10229 // Decide which area this value should be read from.
10230 // TODO: Implement the AMD64 ABI in its entirety. This simple
10231 // selection mechanism works only for the basic types.
10232 if (ArgVT == MVT::f80) {
10233 llvm_unreachable("va_arg for f80 not yet implemented");
10234 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10235 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10236 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10237 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10239 llvm_unreachable("Unhandled argument type in LowerVAARG");
10242 if (ArgMode == 2) {
10243 // Sanity Check: Make sure using fp_offset makes sense.
10244 assert(!getTargetMachine().Options.UseSoftFloat &&
10245 !(DAG.getMachineFunction()
10246 .getFunction()->getAttributes()
10247 .hasAttribute(AttributeSet::FunctionIndex,
10248 Attribute::NoImplicitFloat)) &&
10249 Subtarget->hasSSE1());
10252 // Insert VAARG_64 node into the DAG
10253 // VAARG_64 returns two values: Variable Argument Address, Chain
10254 SmallVector<SDValue, 11> InstOps;
10255 InstOps.push_back(Chain);
10256 InstOps.push_back(SrcPtr);
10257 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10258 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10259 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10260 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10261 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10262 VTs, &InstOps[0], InstOps.size(),
10264 MachinePointerInfo(SV),
10266 /*Volatile=*/false,
10268 /*WriteMem=*/true);
10269 Chain = VAARG.getValue(1);
10271 // Load the next argument and return it
10272 return DAG.getLoad(ArgVT, dl,
10275 MachinePointerInfo(),
10276 false, false, false, 0);
10279 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10280 SelectionDAG &DAG) {
10281 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10282 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10283 SDValue Chain = Op.getOperand(0);
10284 SDValue DstPtr = Op.getOperand(1);
10285 SDValue SrcPtr = Op.getOperand(2);
10286 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10287 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10290 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10291 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10293 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10296 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10297 // may or may not be a constant. Takes immediate version of shift as input.
10298 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10299 SDValue SrcOp, SDValue ShAmt,
10300 SelectionDAG &DAG) {
10301 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10303 if (isa<ConstantSDNode>(ShAmt)) {
10304 // Constant may be a TargetConstant. Use a regular constant.
10305 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10307 default: llvm_unreachable("Unknown target vector shift node");
10308 case X86ISD::VSHLI:
10309 case X86ISD::VSRLI:
10310 case X86ISD::VSRAI:
10311 return DAG.getNode(Opc, dl, VT, SrcOp,
10312 DAG.getConstant(ShiftAmt, MVT::i32));
10316 // Change opcode to non-immediate version
10318 default: llvm_unreachable("Unknown target vector shift node");
10319 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10320 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10321 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10324 // Need to build a vector containing shift amount
10325 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10328 ShOps[1] = DAG.getConstant(0, MVT::i32);
10329 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10330 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10332 // The return type has to be a 128-bit type with the same element
10333 // type as the input type.
10334 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10335 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10337 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10338 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10341 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10343 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10345 default: return SDValue(); // Don't custom lower most intrinsics.
10346 // Comparison intrinsics.
10347 case Intrinsic::x86_sse_comieq_ss:
10348 case Intrinsic::x86_sse_comilt_ss:
10349 case Intrinsic::x86_sse_comile_ss:
10350 case Intrinsic::x86_sse_comigt_ss:
10351 case Intrinsic::x86_sse_comige_ss:
10352 case Intrinsic::x86_sse_comineq_ss:
10353 case Intrinsic::x86_sse_ucomieq_ss:
10354 case Intrinsic::x86_sse_ucomilt_ss:
10355 case Intrinsic::x86_sse_ucomile_ss:
10356 case Intrinsic::x86_sse_ucomigt_ss:
10357 case Intrinsic::x86_sse_ucomige_ss:
10358 case Intrinsic::x86_sse_ucomineq_ss:
10359 case Intrinsic::x86_sse2_comieq_sd:
10360 case Intrinsic::x86_sse2_comilt_sd:
10361 case Intrinsic::x86_sse2_comile_sd:
10362 case Intrinsic::x86_sse2_comigt_sd:
10363 case Intrinsic::x86_sse2_comige_sd:
10364 case Intrinsic::x86_sse2_comineq_sd:
10365 case Intrinsic::x86_sse2_ucomieq_sd:
10366 case Intrinsic::x86_sse2_ucomilt_sd:
10367 case Intrinsic::x86_sse2_ucomile_sd:
10368 case Intrinsic::x86_sse2_ucomigt_sd:
10369 case Intrinsic::x86_sse2_ucomige_sd:
10370 case Intrinsic::x86_sse2_ucomineq_sd: {
10374 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10375 case Intrinsic::x86_sse_comieq_ss:
10376 case Intrinsic::x86_sse2_comieq_sd:
10377 Opc = X86ISD::COMI;
10380 case Intrinsic::x86_sse_comilt_ss:
10381 case Intrinsic::x86_sse2_comilt_sd:
10382 Opc = X86ISD::COMI;
10385 case Intrinsic::x86_sse_comile_ss:
10386 case Intrinsic::x86_sse2_comile_sd:
10387 Opc = X86ISD::COMI;
10390 case Intrinsic::x86_sse_comigt_ss:
10391 case Intrinsic::x86_sse2_comigt_sd:
10392 Opc = X86ISD::COMI;
10395 case Intrinsic::x86_sse_comige_ss:
10396 case Intrinsic::x86_sse2_comige_sd:
10397 Opc = X86ISD::COMI;
10400 case Intrinsic::x86_sse_comineq_ss:
10401 case Intrinsic::x86_sse2_comineq_sd:
10402 Opc = X86ISD::COMI;
10405 case Intrinsic::x86_sse_ucomieq_ss:
10406 case Intrinsic::x86_sse2_ucomieq_sd:
10407 Opc = X86ISD::UCOMI;
10410 case Intrinsic::x86_sse_ucomilt_ss:
10411 case Intrinsic::x86_sse2_ucomilt_sd:
10412 Opc = X86ISD::UCOMI;
10415 case Intrinsic::x86_sse_ucomile_ss:
10416 case Intrinsic::x86_sse2_ucomile_sd:
10417 Opc = X86ISD::UCOMI;
10420 case Intrinsic::x86_sse_ucomigt_ss:
10421 case Intrinsic::x86_sse2_ucomigt_sd:
10422 Opc = X86ISD::UCOMI;
10425 case Intrinsic::x86_sse_ucomige_ss:
10426 case Intrinsic::x86_sse2_ucomige_sd:
10427 Opc = X86ISD::UCOMI;
10430 case Intrinsic::x86_sse_ucomineq_ss:
10431 case Intrinsic::x86_sse2_ucomineq_sd:
10432 Opc = X86ISD::UCOMI;
10437 SDValue LHS = Op.getOperand(1);
10438 SDValue RHS = Op.getOperand(2);
10439 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10440 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10441 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10442 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10443 DAG.getConstant(X86CC, MVT::i8), Cond);
10444 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10447 // Arithmetic intrinsics.
10448 case Intrinsic::x86_sse2_pmulu_dq:
10449 case Intrinsic::x86_avx2_pmulu_dq:
10450 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10451 Op.getOperand(1), Op.getOperand(2));
10453 // SSE2/AVX2 sub with unsigned saturation intrinsics
10454 case Intrinsic::x86_sse2_psubus_b:
10455 case Intrinsic::x86_sse2_psubus_w:
10456 case Intrinsic::x86_avx2_psubus_b:
10457 case Intrinsic::x86_avx2_psubus_w:
10458 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10459 Op.getOperand(1), Op.getOperand(2));
10461 // SSE3/AVX horizontal add/sub intrinsics
10462 case Intrinsic::x86_sse3_hadd_ps:
10463 case Intrinsic::x86_sse3_hadd_pd:
10464 case Intrinsic::x86_avx_hadd_ps_256:
10465 case Intrinsic::x86_avx_hadd_pd_256:
10466 case Intrinsic::x86_sse3_hsub_ps:
10467 case Intrinsic::x86_sse3_hsub_pd:
10468 case Intrinsic::x86_avx_hsub_ps_256:
10469 case Intrinsic::x86_avx_hsub_pd_256:
10470 case Intrinsic::x86_ssse3_phadd_w_128:
10471 case Intrinsic::x86_ssse3_phadd_d_128:
10472 case Intrinsic::x86_avx2_phadd_w:
10473 case Intrinsic::x86_avx2_phadd_d:
10474 case Intrinsic::x86_ssse3_phsub_w_128:
10475 case Intrinsic::x86_ssse3_phsub_d_128:
10476 case Intrinsic::x86_avx2_phsub_w:
10477 case Intrinsic::x86_avx2_phsub_d: {
10480 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10481 case Intrinsic::x86_sse3_hadd_ps:
10482 case Intrinsic::x86_sse3_hadd_pd:
10483 case Intrinsic::x86_avx_hadd_ps_256:
10484 case Intrinsic::x86_avx_hadd_pd_256:
10485 Opcode = X86ISD::FHADD;
10487 case Intrinsic::x86_sse3_hsub_ps:
10488 case Intrinsic::x86_sse3_hsub_pd:
10489 case Intrinsic::x86_avx_hsub_ps_256:
10490 case Intrinsic::x86_avx_hsub_pd_256:
10491 Opcode = X86ISD::FHSUB;
10493 case Intrinsic::x86_ssse3_phadd_w_128:
10494 case Intrinsic::x86_ssse3_phadd_d_128:
10495 case Intrinsic::x86_avx2_phadd_w:
10496 case Intrinsic::x86_avx2_phadd_d:
10497 Opcode = X86ISD::HADD;
10499 case Intrinsic::x86_ssse3_phsub_w_128:
10500 case Intrinsic::x86_ssse3_phsub_d_128:
10501 case Intrinsic::x86_avx2_phsub_w:
10502 case Intrinsic::x86_avx2_phsub_d:
10503 Opcode = X86ISD::HSUB;
10506 return DAG.getNode(Opcode, dl, Op.getValueType(),
10507 Op.getOperand(1), Op.getOperand(2));
10510 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10511 case Intrinsic::x86_sse2_pmaxu_b:
10512 case Intrinsic::x86_sse41_pmaxuw:
10513 case Intrinsic::x86_sse41_pmaxud:
10514 case Intrinsic::x86_avx2_pmaxu_b:
10515 case Intrinsic::x86_avx2_pmaxu_w:
10516 case Intrinsic::x86_avx2_pmaxu_d:
10517 case Intrinsic::x86_sse2_pminu_b:
10518 case Intrinsic::x86_sse41_pminuw:
10519 case Intrinsic::x86_sse41_pminud:
10520 case Intrinsic::x86_avx2_pminu_b:
10521 case Intrinsic::x86_avx2_pminu_w:
10522 case Intrinsic::x86_avx2_pminu_d:
10523 case Intrinsic::x86_sse41_pmaxsb:
10524 case Intrinsic::x86_sse2_pmaxs_w:
10525 case Intrinsic::x86_sse41_pmaxsd:
10526 case Intrinsic::x86_avx2_pmaxs_b:
10527 case Intrinsic::x86_avx2_pmaxs_w:
10528 case Intrinsic::x86_avx2_pmaxs_d:
10529 case Intrinsic::x86_sse41_pminsb:
10530 case Intrinsic::x86_sse2_pmins_w:
10531 case Intrinsic::x86_sse41_pminsd:
10532 case Intrinsic::x86_avx2_pmins_b:
10533 case Intrinsic::x86_avx2_pmins_w:
10534 case Intrinsic::x86_avx2_pmins_d: {
10537 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10538 case Intrinsic::x86_sse2_pmaxu_b:
10539 case Intrinsic::x86_sse41_pmaxuw:
10540 case Intrinsic::x86_sse41_pmaxud:
10541 case Intrinsic::x86_avx2_pmaxu_b:
10542 case Intrinsic::x86_avx2_pmaxu_w:
10543 case Intrinsic::x86_avx2_pmaxu_d:
10544 Opcode = X86ISD::UMAX;
10546 case Intrinsic::x86_sse2_pminu_b:
10547 case Intrinsic::x86_sse41_pminuw:
10548 case Intrinsic::x86_sse41_pminud:
10549 case Intrinsic::x86_avx2_pminu_b:
10550 case Intrinsic::x86_avx2_pminu_w:
10551 case Intrinsic::x86_avx2_pminu_d:
10552 Opcode = X86ISD::UMIN;
10554 case Intrinsic::x86_sse41_pmaxsb:
10555 case Intrinsic::x86_sse2_pmaxs_w:
10556 case Intrinsic::x86_sse41_pmaxsd:
10557 case Intrinsic::x86_avx2_pmaxs_b:
10558 case Intrinsic::x86_avx2_pmaxs_w:
10559 case Intrinsic::x86_avx2_pmaxs_d:
10560 Opcode = X86ISD::SMAX;
10562 case Intrinsic::x86_sse41_pminsb:
10563 case Intrinsic::x86_sse2_pmins_w:
10564 case Intrinsic::x86_sse41_pminsd:
10565 case Intrinsic::x86_avx2_pmins_b:
10566 case Intrinsic::x86_avx2_pmins_w:
10567 case Intrinsic::x86_avx2_pmins_d:
10568 Opcode = X86ISD::SMIN;
10571 return DAG.getNode(Opcode, dl, Op.getValueType(),
10572 Op.getOperand(1), Op.getOperand(2));
10575 // SSE/SSE2/AVX floating point max/min intrinsics.
10576 case Intrinsic::x86_sse_max_ps:
10577 case Intrinsic::x86_sse2_max_pd:
10578 case Intrinsic::x86_avx_max_ps_256:
10579 case Intrinsic::x86_avx_max_pd_256:
10580 case Intrinsic::x86_sse_min_ps:
10581 case Intrinsic::x86_sse2_min_pd:
10582 case Intrinsic::x86_avx_min_ps_256:
10583 case Intrinsic::x86_avx_min_pd_256: {
10586 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10587 case Intrinsic::x86_sse_max_ps:
10588 case Intrinsic::x86_sse2_max_pd:
10589 case Intrinsic::x86_avx_max_ps_256:
10590 case Intrinsic::x86_avx_max_pd_256:
10591 Opcode = X86ISD::FMAX;
10593 case Intrinsic::x86_sse_min_ps:
10594 case Intrinsic::x86_sse2_min_pd:
10595 case Intrinsic::x86_avx_min_ps_256:
10596 case Intrinsic::x86_avx_min_pd_256:
10597 Opcode = X86ISD::FMIN;
10600 return DAG.getNode(Opcode, dl, Op.getValueType(),
10601 Op.getOperand(1), Op.getOperand(2));
10604 // AVX2 variable shift intrinsics
10605 case Intrinsic::x86_avx2_psllv_d:
10606 case Intrinsic::x86_avx2_psllv_q:
10607 case Intrinsic::x86_avx2_psllv_d_256:
10608 case Intrinsic::x86_avx2_psllv_q_256:
10609 case Intrinsic::x86_avx2_psrlv_d:
10610 case Intrinsic::x86_avx2_psrlv_q:
10611 case Intrinsic::x86_avx2_psrlv_d_256:
10612 case Intrinsic::x86_avx2_psrlv_q_256:
10613 case Intrinsic::x86_avx2_psrav_d:
10614 case Intrinsic::x86_avx2_psrav_d_256: {
10617 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10618 case Intrinsic::x86_avx2_psllv_d:
10619 case Intrinsic::x86_avx2_psllv_q:
10620 case Intrinsic::x86_avx2_psllv_d_256:
10621 case Intrinsic::x86_avx2_psllv_q_256:
10624 case Intrinsic::x86_avx2_psrlv_d:
10625 case Intrinsic::x86_avx2_psrlv_q:
10626 case Intrinsic::x86_avx2_psrlv_d_256:
10627 case Intrinsic::x86_avx2_psrlv_q_256:
10630 case Intrinsic::x86_avx2_psrav_d:
10631 case Intrinsic::x86_avx2_psrav_d_256:
10635 return DAG.getNode(Opcode, dl, Op.getValueType(),
10636 Op.getOperand(1), Op.getOperand(2));
10639 case Intrinsic::x86_ssse3_pshuf_b_128:
10640 case Intrinsic::x86_avx2_pshuf_b:
10641 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10642 Op.getOperand(1), Op.getOperand(2));
10644 case Intrinsic::x86_ssse3_psign_b_128:
10645 case Intrinsic::x86_ssse3_psign_w_128:
10646 case Intrinsic::x86_ssse3_psign_d_128:
10647 case Intrinsic::x86_avx2_psign_b:
10648 case Intrinsic::x86_avx2_psign_w:
10649 case Intrinsic::x86_avx2_psign_d:
10650 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10651 Op.getOperand(1), Op.getOperand(2));
10653 case Intrinsic::x86_sse41_insertps:
10654 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10655 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10657 case Intrinsic::x86_avx_vperm2f128_ps_256:
10658 case Intrinsic::x86_avx_vperm2f128_pd_256:
10659 case Intrinsic::x86_avx_vperm2f128_si_256:
10660 case Intrinsic::x86_avx2_vperm2i128:
10661 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10662 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10664 case Intrinsic::x86_avx2_permd:
10665 case Intrinsic::x86_avx2_permps:
10666 // Operands intentionally swapped. Mask is last operand to intrinsic,
10667 // but second operand for node/intruction.
10668 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10669 Op.getOperand(2), Op.getOperand(1));
10671 case Intrinsic::x86_sse_sqrt_ps:
10672 case Intrinsic::x86_sse2_sqrt_pd:
10673 case Intrinsic::x86_avx_sqrt_ps_256:
10674 case Intrinsic::x86_avx_sqrt_pd_256:
10675 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10677 // ptest and testp intrinsics. The intrinsic these come from are designed to
10678 // return an integer value, not just an instruction so lower it to the ptest
10679 // or testp pattern and a setcc for the result.
10680 case Intrinsic::x86_sse41_ptestz:
10681 case Intrinsic::x86_sse41_ptestc:
10682 case Intrinsic::x86_sse41_ptestnzc:
10683 case Intrinsic::x86_avx_ptestz_256:
10684 case Intrinsic::x86_avx_ptestc_256:
10685 case Intrinsic::x86_avx_ptestnzc_256:
10686 case Intrinsic::x86_avx_vtestz_ps:
10687 case Intrinsic::x86_avx_vtestc_ps:
10688 case Intrinsic::x86_avx_vtestnzc_ps:
10689 case Intrinsic::x86_avx_vtestz_pd:
10690 case Intrinsic::x86_avx_vtestc_pd:
10691 case Intrinsic::x86_avx_vtestnzc_pd:
10692 case Intrinsic::x86_avx_vtestz_ps_256:
10693 case Intrinsic::x86_avx_vtestc_ps_256:
10694 case Intrinsic::x86_avx_vtestnzc_ps_256:
10695 case Intrinsic::x86_avx_vtestz_pd_256:
10696 case Intrinsic::x86_avx_vtestc_pd_256:
10697 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10698 bool IsTestPacked = false;
10701 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10702 case Intrinsic::x86_avx_vtestz_ps:
10703 case Intrinsic::x86_avx_vtestz_pd:
10704 case Intrinsic::x86_avx_vtestz_ps_256:
10705 case Intrinsic::x86_avx_vtestz_pd_256:
10706 IsTestPacked = true; // Fallthrough
10707 case Intrinsic::x86_sse41_ptestz:
10708 case Intrinsic::x86_avx_ptestz_256:
10710 X86CC = X86::COND_E;
10712 case Intrinsic::x86_avx_vtestc_ps:
10713 case Intrinsic::x86_avx_vtestc_pd:
10714 case Intrinsic::x86_avx_vtestc_ps_256:
10715 case Intrinsic::x86_avx_vtestc_pd_256:
10716 IsTestPacked = true; // Fallthrough
10717 case Intrinsic::x86_sse41_ptestc:
10718 case Intrinsic::x86_avx_ptestc_256:
10720 X86CC = X86::COND_B;
10722 case Intrinsic::x86_avx_vtestnzc_ps:
10723 case Intrinsic::x86_avx_vtestnzc_pd:
10724 case Intrinsic::x86_avx_vtestnzc_ps_256:
10725 case Intrinsic::x86_avx_vtestnzc_pd_256:
10726 IsTestPacked = true; // Fallthrough
10727 case Intrinsic::x86_sse41_ptestnzc:
10728 case Intrinsic::x86_avx_ptestnzc_256:
10730 X86CC = X86::COND_A;
10734 SDValue LHS = Op.getOperand(1);
10735 SDValue RHS = Op.getOperand(2);
10736 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10737 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10738 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10739 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10740 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10743 // SSE/AVX shift intrinsics
10744 case Intrinsic::x86_sse2_psll_w:
10745 case Intrinsic::x86_sse2_psll_d:
10746 case Intrinsic::x86_sse2_psll_q:
10747 case Intrinsic::x86_avx2_psll_w:
10748 case Intrinsic::x86_avx2_psll_d:
10749 case Intrinsic::x86_avx2_psll_q:
10750 case Intrinsic::x86_sse2_psrl_w:
10751 case Intrinsic::x86_sse2_psrl_d:
10752 case Intrinsic::x86_sse2_psrl_q:
10753 case Intrinsic::x86_avx2_psrl_w:
10754 case Intrinsic::x86_avx2_psrl_d:
10755 case Intrinsic::x86_avx2_psrl_q:
10756 case Intrinsic::x86_sse2_psra_w:
10757 case Intrinsic::x86_sse2_psra_d:
10758 case Intrinsic::x86_avx2_psra_w:
10759 case Intrinsic::x86_avx2_psra_d: {
10762 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10763 case Intrinsic::x86_sse2_psll_w:
10764 case Intrinsic::x86_sse2_psll_d:
10765 case Intrinsic::x86_sse2_psll_q:
10766 case Intrinsic::x86_avx2_psll_w:
10767 case Intrinsic::x86_avx2_psll_d:
10768 case Intrinsic::x86_avx2_psll_q:
10769 Opcode = X86ISD::VSHL;
10771 case Intrinsic::x86_sse2_psrl_w:
10772 case Intrinsic::x86_sse2_psrl_d:
10773 case Intrinsic::x86_sse2_psrl_q:
10774 case Intrinsic::x86_avx2_psrl_w:
10775 case Intrinsic::x86_avx2_psrl_d:
10776 case Intrinsic::x86_avx2_psrl_q:
10777 Opcode = X86ISD::VSRL;
10779 case Intrinsic::x86_sse2_psra_w:
10780 case Intrinsic::x86_sse2_psra_d:
10781 case Intrinsic::x86_avx2_psra_w:
10782 case Intrinsic::x86_avx2_psra_d:
10783 Opcode = X86ISD::VSRA;
10786 return DAG.getNode(Opcode, dl, Op.getValueType(),
10787 Op.getOperand(1), Op.getOperand(2));
10790 // SSE/AVX immediate shift intrinsics
10791 case Intrinsic::x86_sse2_pslli_w:
10792 case Intrinsic::x86_sse2_pslli_d:
10793 case Intrinsic::x86_sse2_pslli_q:
10794 case Intrinsic::x86_avx2_pslli_w:
10795 case Intrinsic::x86_avx2_pslli_d:
10796 case Intrinsic::x86_avx2_pslli_q:
10797 case Intrinsic::x86_sse2_psrli_w:
10798 case Intrinsic::x86_sse2_psrli_d:
10799 case Intrinsic::x86_sse2_psrli_q:
10800 case Intrinsic::x86_avx2_psrli_w:
10801 case Intrinsic::x86_avx2_psrli_d:
10802 case Intrinsic::x86_avx2_psrli_q:
10803 case Intrinsic::x86_sse2_psrai_w:
10804 case Intrinsic::x86_sse2_psrai_d:
10805 case Intrinsic::x86_avx2_psrai_w:
10806 case Intrinsic::x86_avx2_psrai_d: {
10809 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10810 case Intrinsic::x86_sse2_pslli_w:
10811 case Intrinsic::x86_sse2_pslli_d:
10812 case Intrinsic::x86_sse2_pslli_q:
10813 case Intrinsic::x86_avx2_pslli_w:
10814 case Intrinsic::x86_avx2_pslli_d:
10815 case Intrinsic::x86_avx2_pslli_q:
10816 Opcode = X86ISD::VSHLI;
10818 case Intrinsic::x86_sse2_psrli_w:
10819 case Intrinsic::x86_sse2_psrli_d:
10820 case Intrinsic::x86_sse2_psrli_q:
10821 case Intrinsic::x86_avx2_psrli_w:
10822 case Intrinsic::x86_avx2_psrli_d:
10823 case Intrinsic::x86_avx2_psrli_q:
10824 Opcode = X86ISD::VSRLI;
10826 case Intrinsic::x86_sse2_psrai_w:
10827 case Intrinsic::x86_sse2_psrai_d:
10828 case Intrinsic::x86_avx2_psrai_w:
10829 case Intrinsic::x86_avx2_psrai_d:
10830 Opcode = X86ISD::VSRAI;
10833 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10834 Op.getOperand(1), Op.getOperand(2), DAG);
10837 case Intrinsic::x86_sse42_pcmpistria128:
10838 case Intrinsic::x86_sse42_pcmpestria128:
10839 case Intrinsic::x86_sse42_pcmpistric128:
10840 case Intrinsic::x86_sse42_pcmpestric128:
10841 case Intrinsic::x86_sse42_pcmpistrio128:
10842 case Intrinsic::x86_sse42_pcmpestrio128:
10843 case Intrinsic::x86_sse42_pcmpistris128:
10844 case Intrinsic::x86_sse42_pcmpestris128:
10845 case Intrinsic::x86_sse42_pcmpistriz128:
10846 case Intrinsic::x86_sse42_pcmpestriz128: {
10850 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10851 case Intrinsic::x86_sse42_pcmpistria128:
10852 Opcode = X86ISD::PCMPISTRI;
10853 X86CC = X86::COND_A;
10855 case Intrinsic::x86_sse42_pcmpestria128:
10856 Opcode = X86ISD::PCMPESTRI;
10857 X86CC = X86::COND_A;
10859 case Intrinsic::x86_sse42_pcmpistric128:
10860 Opcode = X86ISD::PCMPISTRI;
10861 X86CC = X86::COND_B;
10863 case Intrinsic::x86_sse42_pcmpestric128:
10864 Opcode = X86ISD::PCMPESTRI;
10865 X86CC = X86::COND_B;
10867 case Intrinsic::x86_sse42_pcmpistrio128:
10868 Opcode = X86ISD::PCMPISTRI;
10869 X86CC = X86::COND_O;
10871 case Intrinsic::x86_sse42_pcmpestrio128:
10872 Opcode = X86ISD::PCMPESTRI;
10873 X86CC = X86::COND_O;
10875 case Intrinsic::x86_sse42_pcmpistris128:
10876 Opcode = X86ISD::PCMPISTRI;
10877 X86CC = X86::COND_S;
10879 case Intrinsic::x86_sse42_pcmpestris128:
10880 Opcode = X86ISD::PCMPESTRI;
10881 X86CC = X86::COND_S;
10883 case Intrinsic::x86_sse42_pcmpistriz128:
10884 Opcode = X86ISD::PCMPISTRI;
10885 X86CC = X86::COND_E;
10887 case Intrinsic::x86_sse42_pcmpestriz128:
10888 Opcode = X86ISD::PCMPESTRI;
10889 X86CC = X86::COND_E;
10892 SmallVector<SDValue, 5> NewOps;
10893 NewOps.append(Op->op_begin()+1, Op->op_end());
10894 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10895 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10896 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10897 DAG.getConstant(X86CC, MVT::i8),
10898 SDValue(PCMP.getNode(), 1));
10899 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10902 case Intrinsic::x86_sse42_pcmpistri128:
10903 case Intrinsic::x86_sse42_pcmpestri128: {
10905 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10906 Opcode = X86ISD::PCMPISTRI;
10908 Opcode = X86ISD::PCMPESTRI;
10910 SmallVector<SDValue, 5> NewOps;
10911 NewOps.append(Op->op_begin()+1, Op->op_end());
10912 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10913 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10915 case Intrinsic::x86_fma_vfmadd_ps:
10916 case Intrinsic::x86_fma_vfmadd_pd:
10917 case Intrinsic::x86_fma_vfmsub_ps:
10918 case Intrinsic::x86_fma_vfmsub_pd:
10919 case Intrinsic::x86_fma_vfnmadd_ps:
10920 case Intrinsic::x86_fma_vfnmadd_pd:
10921 case Intrinsic::x86_fma_vfnmsub_ps:
10922 case Intrinsic::x86_fma_vfnmsub_pd:
10923 case Intrinsic::x86_fma_vfmaddsub_ps:
10924 case Intrinsic::x86_fma_vfmaddsub_pd:
10925 case Intrinsic::x86_fma_vfmsubadd_ps:
10926 case Intrinsic::x86_fma_vfmsubadd_pd:
10927 case Intrinsic::x86_fma_vfmadd_ps_256:
10928 case Intrinsic::x86_fma_vfmadd_pd_256:
10929 case Intrinsic::x86_fma_vfmsub_ps_256:
10930 case Intrinsic::x86_fma_vfmsub_pd_256:
10931 case Intrinsic::x86_fma_vfnmadd_ps_256:
10932 case Intrinsic::x86_fma_vfnmadd_pd_256:
10933 case Intrinsic::x86_fma_vfnmsub_ps_256:
10934 case Intrinsic::x86_fma_vfnmsub_pd_256:
10935 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10936 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10937 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10938 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10941 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10942 case Intrinsic::x86_fma_vfmadd_ps:
10943 case Intrinsic::x86_fma_vfmadd_pd:
10944 case Intrinsic::x86_fma_vfmadd_ps_256:
10945 case Intrinsic::x86_fma_vfmadd_pd_256:
10946 Opc = X86ISD::FMADD;
10948 case Intrinsic::x86_fma_vfmsub_ps:
10949 case Intrinsic::x86_fma_vfmsub_pd:
10950 case Intrinsic::x86_fma_vfmsub_ps_256:
10951 case Intrinsic::x86_fma_vfmsub_pd_256:
10952 Opc = X86ISD::FMSUB;
10954 case Intrinsic::x86_fma_vfnmadd_ps:
10955 case Intrinsic::x86_fma_vfnmadd_pd:
10956 case Intrinsic::x86_fma_vfnmadd_ps_256:
10957 case Intrinsic::x86_fma_vfnmadd_pd_256:
10958 Opc = X86ISD::FNMADD;
10960 case Intrinsic::x86_fma_vfnmsub_ps:
10961 case Intrinsic::x86_fma_vfnmsub_pd:
10962 case Intrinsic::x86_fma_vfnmsub_ps_256:
10963 case Intrinsic::x86_fma_vfnmsub_pd_256:
10964 Opc = X86ISD::FNMSUB;
10966 case Intrinsic::x86_fma_vfmaddsub_ps:
10967 case Intrinsic::x86_fma_vfmaddsub_pd:
10968 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10969 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10970 Opc = X86ISD::FMADDSUB;
10972 case Intrinsic::x86_fma_vfmsubadd_ps:
10973 case Intrinsic::x86_fma_vfmsubadd_pd:
10974 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10975 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10976 Opc = X86ISD::FMSUBADD;
10980 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10981 Op.getOperand(2), Op.getOperand(3));
10986 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10988 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10990 default: return SDValue(); // Don't custom lower most intrinsics.
10992 // RDRAND/RDSEED intrinsics.
10993 case Intrinsic::x86_rdrand_16:
10994 case Intrinsic::x86_rdrand_32:
10995 case Intrinsic::x86_rdrand_64:
10996 case Intrinsic::x86_rdseed_16:
10997 case Intrinsic::x86_rdseed_32:
10998 case Intrinsic::x86_rdseed_64: {
10999 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11000 IntNo == Intrinsic::x86_rdseed_32 ||
11001 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11003 // Emit the node with the right value type.
11004 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11005 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11007 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11008 // Otherwise return the value from Rand, which is always 0, casted to i32.
11009 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11010 DAG.getConstant(1, Op->getValueType(1)),
11011 DAG.getConstant(X86::COND_B, MVT::i32),
11012 SDValue(Result.getNode(), 1) };
11013 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11014 DAG.getVTList(Op->getValueType(1), MVT::Glue),
11015 Ops, array_lengthof(Ops));
11017 // Return { result, isValid, chain }.
11018 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11019 SDValue(Result.getNode(), 2));
11022 // XTEST intrinsics.
11023 case Intrinsic::x86_xtest: {
11024 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11025 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11026 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11027 DAG.getConstant(X86::COND_NE, MVT::i8),
11029 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11030 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11031 Ret, SDValue(InTrans.getNode(), 1));
11036 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11037 SelectionDAG &DAG) const {
11038 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11039 MFI->setReturnAddressIsTaken(true);
11041 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11043 EVT PtrVT = getPointerTy();
11046 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11047 const X86RegisterInfo *RegInfo =
11048 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11049 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11050 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11051 DAG.getNode(ISD::ADD, dl, PtrVT,
11052 FrameAddr, Offset),
11053 MachinePointerInfo(), false, false, false, 0);
11056 // Just load the return address.
11057 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11058 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11059 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11062 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11063 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11064 MFI->setFrameAddressIsTaken(true);
11066 EVT VT = Op.getValueType();
11067 SDLoc dl(Op); // FIXME probably not meaningful
11068 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11069 const X86RegisterInfo *RegInfo =
11070 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11071 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11072 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11073 (FrameReg == X86::EBP && VT == MVT::i32)) &&
11074 "Invalid Frame Register!");
11075 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11077 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11078 MachinePointerInfo(),
11079 false, false, false, 0);
11083 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11084 SelectionDAG &DAG) const {
11085 const X86RegisterInfo *RegInfo =
11086 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11087 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11090 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11091 SDValue Chain = Op.getOperand(0);
11092 SDValue Offset = Op.getOperand(1);
11093 SDValue Handler = Op.getOperand(2);
11096 EVT PtrVT = getPointerTy();
11097 const X86RegisterInfo *RegInfo =
11098 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11099 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11100 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11101 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11102 "Invalid Frame Register!");
11103 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11104 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11106 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11107 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11108 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11109 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11111 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11113 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11114 DAG.getRegister(StoreAddrReg, PtrVT));
11117 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11118 SelectionDAG &DAG) const {
11120 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11121 DAG.getVTList(MVT::i32, MVT::Other),
11122 Op.getOperand(0), Op.getOperand(1));
11125 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11126 SelectionDAG &DAG) const {
11128 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11129 Op.getOperand(0), Op.getOperand(1));
11132 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11133 return Op.getOperand(0);
11136 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11137 SelectionDAG &DAG) const {
11138 SDValue Root = Op.getOperand(0);
11139 SDValue Trmp = Op.getOperand(1); // trampoline
11140 SDValue FPtr = Op.getOperand(2); // nested function
11141 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11144 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11145 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11147 if (Subtarget->is64Bit()) {
11148 SDValue OutChains[6];
11150 // Large code-model.
11151 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11152 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11154 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11155 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11157 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11159 // Load the pointer to the nested function into R11.
11160 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11161 SDValue Addr = Trmp;
11162 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11163 Addr, MachinePointerInfo(TrmpAddr),
11166 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11167 DAG.getConstant(2, MVT::i64));
11168 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11169 MachinePointerInfo(TrmpAddr, 2),
11172 // Load the 'nest' parameter value into R10.
11173 // R10 is specified in X86CallingConv.td
11174 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11175 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11176 DAG.getConstant(10, MVT::i64));
11177 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11178 Addr, MachinePointerInfo(TrmpAddr, 10),
11181 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11182 DAG.getConstant(12, MVT::i64));
11183 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11184 MachinePointerInfo(TrmpAddr, 12),
11187 // Jump to the nested function.
11188 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11189 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11190 DAG.getConstant(20, MVT::i64));
11191 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11192 Addr, MachinePointerInfo(TrmpAddr, 20),
11195 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11196 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11197 DAG.getConstant(22, MVT::i64));
11198 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11199 MachinePointerInfo(TrmpAddr, 22),
11202 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11204 const Function *Func =
11205 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11206 CallingConv::ID CC = Func->getCallingConv();
11211 llvm_unreachable("Unsupported calling convention");
11212 case CallingConv::C:
11213 case CallingConv::X86_StdCall: {
11214 // Pass 'nest' parameter in ECX.
11215 // Must be kept in sync with X86CallingConv.td
11216 NestReg = X86::ECX;
11218 // Check that ECX wasn't needed by an 'inreg' parameter.
11219 FunctionType *FTy = Func->getFunctionType();
11220 const AttributeSet &Attrs = Func->getAttributes();
11222 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11223 unsigned InRegCount = 0;
11226 for (FunctionType::param_iterator I = FTy->param_begin(),
11227 E = FTy->param_end(); I != E; ++I, ++Idx)
11228 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11229 // FIXME: should only count parameters that are lowered to integers.
11230 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11232 if (InRegCount > 2) {
11233 report_fatal_error("Nest register in use - reduce number of inreg"
11239 case CallingConv::X86_FastCall:
11240 case CallingConv::X86_ThisCall:
11241 case CallingConv::Fast:
11242 // Pass 'nest' parameter in EAX.
11243 // Must be kept in sync with X86CallingConv.td
11244 NestReg = X86::EAX;
11248 SDValue OutChains[4];
11249 SDValue Addr, Disp;
11251 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11252 DAG.getConstant(10, MVT::i32));
11253 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11255 // This is storing the opcode for MOV32ri.
11256 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11257 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11258 OutChains[0] = DAG.getStore(Root, dl,
11259 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11260 Trmp, MachinePointerInfo(TrmpAddr),
11263 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11264 DAG.getConstant(1, MVT::i32));
11265 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11266 MachinePointerInfo(TrmpAddr, 1),
11269 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11270 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11271 DAG.getConstant(5, MVT::i32));
11272 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11273 MachinePointerInfo(TrmpAddr, 5),
11276 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11277 DAG.getConstant(6, MVT::i32));
11278 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11279 MachinePointerInfo(TrmpAddr, 6),
11282 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11286 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11287 SelectionDAG &DAG) const {
11289 The rounding mode is in bits 11:10 of FPSR, and has the following
11291 00 Round to nearest
11296 FLT_ROUNDS, on the other hand, expects the following:
11303 To perform the conversion, we do:
11304 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11307 MachineFunction &MF = DAG.getMachineFunction();
11308 const TargetMachine &TM = MF.getTarget();
11309 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11310 unsigned StackAlignment = TFI.getStackAlignment();
11311 EVT VT = Op.getValueType();
11314 // Save FP Control Word to stack slot
11315 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11316 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11318 MachineMemOperand *MMO =
11319 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11320 MachineMemOperand::MOStore, 2, 2);
11322 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11323 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11324 DAG.getVTList(MVT::Other),
11325 Ops, array_lengthof(Ops), MVT::i16,
11328 // Load FP Control Word from stack slot
11329 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11330 MachinePointerInfo(), false, false, false, 0);
11332 // Transform as necessary
11334 DAG.getNode(ISD::SRL, DL, MVT::i16,
11335 DAG.getNode(ISD::AND, DL, MVT::i16,
11336 CWD, DAG.getConstant(0x800, MVT::i16)),
11337 DAG.getConstant(11, MVT::i8));
11339 DAG.getNode(ISD::SRL, DL, MVT::i16,
11340 DAG.getNode(ISD::AND, DL, MVT::i16,
11341 CWD, DAG.getConstant(0x400, MVT::i16)),
11342 DAG.getConstant(9, MVT::i8));
11345 DAG.getNode(ISD::AND, DL, MVT::i16,
11346 DAG.getNode(ISD::ADD, DL, MVT::i16,
11347 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11348 DAG.getConstant(1, MVT::i16)),
11349 DAG.getConstant(3, MVT::i16));
11351 return DAG.getNode((VT.getSizeInBits() < 16 ?
11352 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11355 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11356 EVT VT = Op.getValueType();
11358 unsigned NumBits = VT.getSizeInBits();
11361 Op = Op.getOperand(0);
11362 if (VT == MVT::i8) {
11363 // Zero extend to i32 since there is not an i8 bsr.
11365 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11368 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11369 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11370 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11372 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11375 DAG.getConstant(NumBits+NumBits-1, OpVT),
11376 DAG.getConstant(X86::COND_E, MVT::i8),
11379 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11381 // Finally xor with NumBits-1.
11382 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11385 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11389 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11390 EVT VT = Op.getValueType();
11392 unsigned NumBits = VT.getSizeInBits();
11395 Op = Op.getOperand(0);
11396 if (VT == MVT::i8) {
11397 // Zero extend to i32 since there is not an i8 bsr.
11399 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11402 // Issue a bsr (scan bits in reverse).
11403 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11404 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11406 // And xor with NumBits-1.
11407 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11410 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11414 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11415 EVT VT = Op.getValueType();
11416 unsigned NumBits = VT.getSizeInBits();
11418 Op = Op.getOperand(0);
11420 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11421 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11422 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11424 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11427 DAG.getConstant(NumBits, VT),
11428 DAG.getConstant(X86::COND_E, MVT::i8),
11431 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11434 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11435 // ones, and then concatenate the result back.
11436 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11437 EVT VT = Op.getValueType();
11439 assert(VT.is256BitVector() && VT.isInteger() &&
11440 "Unsupported value type for operation");
11442 unsigned NumElems = VT.getVectorNumElements();
11445 // Extract the LHS vectors
11446 SDValue LHS = Op.getOperand(0);
11447 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11448 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11450 // Extract the RHS vectors
11451 SDValue RHS = Op.getOperand(1);
11452 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11453 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11455 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11456 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11458 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11459 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11460 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11463 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11464 assert(Op.getValueType().is256BitVector() &&
11465 Op.getValueType().isInteger() &&
11466 "Only handle AVX 256-bit vector integer operation");
11467 return Lower256IntArith(Op, DAG);
11470 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11471 assert(Op.getValueType().is256BitVector() &&
11472 Op.getValueType().isInteger() &&
11473 "Only handle AVX 256-bit vector integer operation");
11474 return Lower256IntArith(Op, DAG);
11477 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11478 SelectionDAG &DAG) {
11480 EVT VT = Op.getValueType();
11482 // Decompose 256-bit ops into smaller 128-bit ops.
11483 if (VT.is256BitVector() && !Subtarget->hasInt256())
11484 return Lower256IntArith(Op, DAG);
11486 SDValue A = Op.getOperand(0);
11487 SDValue B = Op.getOperand(1);
11489 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11490 if (VT == MVT::v4i32) {
11491 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11492 "Should not custom lower when pmuldq is available!");
11494 // Extract the odd parts.
11495 const int UnpackMask[] = { 1, -1, 3, -1 };
11496 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11497 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11499 // Multiply the even parts.
11500 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11501 // Now multiply odd parts.
11502 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11504 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11505 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11507 // Merge the two vectors back together with a shuffle. This expands into 2
11509 const int ShufMask[] = { 0, 4, 2, 6 };
11510 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11513 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11514 "Only know how to lower V2I64/V4I64 multiply");
11516 // Ahi = psrlqi(a, 32);
11517 // Bhi = psrlqi(b, 32);
11519 // AloBlo = pmuludq(a, b);
11520 // AloBhi = pmuludq(a, Bhi);
11521 // AhiBlo = pmuludq(Ahi, b);
11523 // AloBhi = psllqi(AloBhi, 32);
11524 // AhiBlo = psllqi(AhiBlo, 32);
11525 // return AloBlo + AloBhi + AhiBlo;
11527 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11529 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11530 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11532 // Bit cast to 32-bit vectors for MULUDQ
11533 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11534 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11535 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11536 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11537 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11539 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11540 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11541 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11543 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11544 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11546 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11547 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11550 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11551 EVT VT = Op.getValueType();
11552 EVT EltTy = VT.getVectorElementType();
11553 unsigned NumElts = VT.getVectorNumElements();
11554 SDValue N0 = Op.getOperand(0);
11557 // Lower sdiv X, pow2-const.
11558 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11562 APInt SplatValue, SplatUndef;
11563 unsigned SplatBitSize;
11565 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11567 EltTy.getSizeInBits() < SplatBitSize)
11570 if ((SplatValue != 0) &&
11571 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11572 unsigned lg2 = SplatValue.countTrailingZeros();
11573 // Splat the sign bit.
11574 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11575 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11576 // Add (N0 < 0) ? abs2 - 1 : 0;
11577 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11578 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11579 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11580 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11581 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11583 // If we're dividing by a positive value, we're done. Otherwise, we must
11584 // negate the result.
11585 if (SplatValue.isNonNegative())
11588 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11589 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11590 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11595 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11596 const X86Subtarget *Subtarget) {
11597 EVT VT = Op.getValueType();
11599 SDValue R = Op.getOperand(0);
11600 SDValue Amt = Op.getOperand(1);
11602 // Optimize shl/srl/sra with constant shift amount.
11603 if (isSplatVector(Amt.getNode())) {
11604 SDValue SclrAmt = Amt->getOperand(0);
11605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11606 uint64_t ShiftAmt = C->getZExtValue();
11608 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11609 (Subtarget->hasInt256() &&
11610 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11611 if (Op.getOpcode() == ISD::SHL)
11612 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11613 DAG.getConstant(ShiftAmt, MVT::i32));
11614 if (Op.getOpcode() == ISD::SRL)
11615 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11616 DAG.getConstant(ShiftAmt, MVT::i32));
11617 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11618 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11619 DAG.getConstant(ShiftAmt, MVT::i32));
11622 if (VT == MVT::v16i8) {
11623 if (Op.getOpcode() == ISD::SHL) {
11624 // Make a large shift.
11625 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11626 DAG.getConstant(ShiftAmt, MVT::i32));
11627 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11628 // Zero out the rightmost bits.
11629 SmallVector<SDValue, 16> V(16,
11630 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11632 return DAG.getNode(ISD::AND, dl, VT, SHL,
11633 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11635 if (Op.getOpcode() == ISD::SRL) {
11636 // Make a large shift.
11637 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11638 DAG.getConstant(ShiftAmt, MVT::i32));
11639 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11640 // Zero out the leftmost bits.
11641 SmallVector<SDValue, 16> V(16,
11642 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11644 return DAG.getNode(ISD::AND, dl, VT, SRL,
11645 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11647 if (Op.getOpcode() == ISD::SRA) {
11648 if (ShiftAmt == 7) {
11649 // R s>> 7 === R s< 0
11650 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11651 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11654 // R s>> a === ((R u>> a) ^ m) - m
11655 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11656 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11658 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11659 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11660 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11663 llvm_unreachable("Unknown shift opcode.");
11666 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11667 if (Op.getOpcode() == ISD::SHL) {
11668 // Make a large shift.
11669 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11670 DAG.getConstant(ShiftAmt, MVT::i32));
11671 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11672 // Zero out the rightmost bits.
11673 SmallVector<SDValue, 32> V(32,
11674 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11676 return DAG.getNode(ISD::AND, dl, VT, SHL,
11677 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11679 if (Op.getOpcode() == ISD::SRL) {
11680 // Make a large shift.
11681 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11682 DAG.getConstant(ShiftAmt, MVT::i32));
11683 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11684 // Zero out the leftmost bits.
11685 SmallVector<SDValue, 32> V(32,
11686 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11688 return DAG.getNode(ISD::AND, dl, VT, SRL,
11689 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11691 if (Op.getOpcode() == ISD::SRA) {
11692 if (ShiftAmt == 7) {
11693 // R s>> 7 === R s< 0
11694 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11695 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11698 // R s>> a === ((R u>> a) ^ m) - m
11699 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11700 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11702 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11703 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11704 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11707 llvm_unreachable("Unknown shift opcode.");
11712 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11713 if (!Subtarget->is64Bit() &&
11714 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11715 Amt.getOpcode() == ISD::BITCAST &&
11716 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11717 Amt = Amt.getOperand(0);
11718 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11719 VT.getVectorNumElements();
11720 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11721 uint64_t ShiftAmt = 0;
11722 for (unsigned i = 0; i != Ratio; ++i) {
11723 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11727 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11729 // Check remaining shift amounts.
11730 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11731 uint64_t ShAmt = 0;
11732 for (unsigned j = 0; j != Ratio; ++j) {
11733 ConstantSDNode *C =
11734 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11738 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11740 if (ShAmt != ShiftAmt)
11743 switch (Op.getOpcode()) {
11745 llvm_unreachable("Unknown shift opcode!");
11747 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11748 DAG.getConstant(ShiftAmt, MVT::i32));
11750 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11751 DAG.getConstant(ShiftAmt, MVT::i32));
11753 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11754 DAG.getConstant(ShiftAmt, MVT::i32));
11761 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11762 const X86Subtarget* Subtarget) {
11763 EVT VT = Op.getValueType();
11765 SDValue R = Op.getOperand(0);
11766 SDValue Amt = Op.getOperand(1);
11768 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11769 VT == MVT::v4i32 || VT == MVT::v8i16 ||
11770 (Subtarget->hasInt256() &&
11771 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11772 VT == MVT::v8i32 || VT == MVT::v16i16))) {
11774 EVT EltVT = VT.getVectorElementType();
11776 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11777 unsigned NumElts = VT.getVectorNumElements();
11779 for (i = 0; i != NumElts; ++i) {
11780 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11784 for (j = i; j != NumElts; ++j) {
11785 SDValue Arg = Amt.getOperand(j);
11786 if (Arg.getOpcode() == ISD::UNDEF) continue;
11787 if (Arg != Amt.getOperand(i))
11790 if (i != NumElts && j == NumElts)
11791 BaseShAmt = Amt.getOperand(i);
11793 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11794 Amt = Amt.getOperand(0);
11795 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11796 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11797 SDValue InVec = Amt.getOperand(0);
11798 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11799 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11801 for (; i != NumElts; ++i) {
11802 SDValue Arg = InVec.getOperand(i);
11803 if (Arg.getOpcode() == ISD::UNDEF) continue;
11807 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11808 if (ConstantSDNode *C =
11809 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11810 unsigned SplatIdx =
11811 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11812 if (C->getZExtValue() == SplatIdx)
11813 BaseShAmt = InVec.getOperand(1);
11816 if (BaseShAmt.getNode() == 0)
11817 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11818 DAG.getIntPtrConstant(0));
11822 if (BaseShAmt.getNode()) {
11823 if (EltVT.bitsGT(MVT::i32))
11824 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11825 else if (EltVT.bitsLT(MVT::i32))
11826 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11828 switch (Op.getOpcode()) {
11830 llvm_unreachable("Unknown shift opcode!");
11832 switch (VT.getSimpleVT().SimpleTy) {
11833 default: return SDValue();
11840 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11843 switch (VT.getSimpleVT().SimpleTy) {
11844 default: return SDValue();
11849 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11852 switch (VT.getSimpleVT().SimpleTy) {
11853 default: return SDValue();
11860 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11866 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11867 if (!Subtarget->is64Bit() &&
11868 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11869 Amt.getOpcode() == ISD::BITCAST &&
11870 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11871 Amt = Amt.getOperand(0);
11872 unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11873 VT.getVectorNumElements();
11874 std::vector<SDValue> Vals(Ratio);
11875 for (unsigned i = 0; i != Ratio; ++i)
11876 Vals[i] = Amt.getOperand(i);
11877 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11878 for (unsigned j = 0; j != Ratio; ++j)
11879 if (Vals[j] != Amt.getOperand(i + j))
11882 switch (Op.getOpcode()) {
11884 llvm_unreachable("Unknown shift opcode!");
11886 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11888 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11890 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11897 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11899 EVT VT = Op.getValueType();
11901 SDValue R = Op.getOperand(0);
11902 SDValue Amt = Op.getOperand(1);
11905 if (!Subtarget->hasSSE2())
11908 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11912 V = LowerScalarVariableShift(Op, DAG, Subtarget);
11916 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11917 if (Subtarget->hasInt256()) {
11918 if (Op.getOpcode() == ISD::SRL &&
11919 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11920 VT == MVT::v4i64 || VT == MVT::v8i32))
11922 if (Op.getOpcode() == ISD::SHL &&
11923 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11924 VT == MVT::v4i64 || VT == MVT::v8i32))
11926 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11930 // Lower SHL with variable shift amount.
11931 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11932 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11934 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11935 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11936 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11937 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11939 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11940 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11943 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11944 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11946 // Turn 'a' into a mask suitable for VSELECT
11947 SDValue VSelM = DAG.getConstant(0x80, VT);
11948 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11949 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11951 SDValue CM1 = DAG.getConstant(0x0f, VT);
11952 SDValue CM2 = DAG.getConstant(0x3f, VT);
11954 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11955 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11956 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11957 DAG.getConstant(4, MVT::i32), DAG);
11958 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11959 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11962 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11963 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11964 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11966 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11967 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11968 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11969 DAG.getConstant(2, MVT::i32), DAG);
11970 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11971 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11974 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11975 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11976 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11978 // return VSELECT(r, r+r, a);
11979 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11980 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11984 // Decompose 256-bit shifts into smaller 128-bit shifts.
11985 if (VT.is256BitVector()) {
11986 unsigned NumElems = VT.getVectorNumElements();
11987 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11988 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11990 // Extract the two vectors
11991 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11992 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11994 // Recreate the shift amount vectors
11995 SDValue Amt1, Amt2;
11996 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11997 // Constant shift amount
11998 SmallVector<SDValue, 4> Amt1Csts;
11999 SmallVector<SDValue, 4> Amt2Csts;
12000 for (unsigned i = 0; i != NumElems/2; ++i)
12001 Amt1Csts.push_back(Amt->getOperand(i));
12002 for (unsigned i = NumElems/2; i != NumElems; ++i)
12003 Amt2Csts.push_back(Amt->getOperand(i));
12005 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12006 &Amt1Csts[0], NumElems/2);
12007 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12008 &Amt2Csts[0], NumElems/2);
12010 // Variable shift amount
12011 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12012 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12015 // Issue new vector shifts for the smaller types
12016 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12017 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12019 // Concatenate the result back
12020 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12026 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12027 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12028 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12029 // looks for this combo and may remove the "setcc" instruction if the "setcc"
12030 // has only one use.
12031 SDNode *N = Op.getNode();
12032 SDValue LHS = N->getOperand(0);
12033 SDValue RHS = N->getOperand(1);
12034 unsigned BaseOp = 0;
12037 switch (Op.getOpcode()) {
12038 default: llvm_unreachable("Unknown ovf instruction!");
12040 // A subtract of one will be selected as a INC. Note that INC doesn't
12041 // set CF, so we can't do this for UADDO.
12042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12044 BaseOp = X86ISD::INC;
12045 Cond = X86::COND_O;
12048 BaseOp = X86ISD::ADD;
12049 Cond = X86::COND_O;
12052 BaseOp = X86ISD::ADD;
12053 Cond = X86::COND_B;
12056 // A subtract of one will be selected as a DEC. Note that DEC doesn't
12057 // set CF, so we can't do this for USUBO.
12058 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12060 BaseOp = X86ISD::DEC;
12061 Cond = X86::COND_O;
12064 BaseOp = X86ISD::SUB;
12065 Cond = X86::COND_O;
12068 BaseOp = X86ISD::SUB;
12069 Cond = X86::COND_B;
12072 BaseOp = X86ISD::SMUL;
12073 Cond = X86::COND_O;
12075 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12076 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12078 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12081 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12082 DAG.getConstant(X86::COND_O, MVT::i32),
12083 SDValue(Sum.getNode(), 2));
12085 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12089 // Also sets EFLAGS.
12090 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12091 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12094 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12095 DAG.getConstant(Cond, MVT::i32),
12096 SDValue(Sum.getNode(), 1));
12098 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12101 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12102 SelectionDAG &DAG) const {
12104 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12105 EVT VT = Op.getValueType();
12107 if (!Subtarget->hasSSE2() || !VT.isVector())
12110 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12111 ExtraVT.getScalarType().getSizeInBits();
12112 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12114 switch (VT.getSimpleVT().SimpleTy) {
12115 default: return SDValue();
12118 if (!Subtarget->hasFp256())
12120 if (!Subtarget->hasInt256()) {
12121 // needs to be split
12122 unsigned NumElems = VT.getVectorNumElements();
12124 // Extract the LHS vectors
12125 SDValue LHS = Op.getOperand(0);
12126 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12127 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12129 MVT EltVT = VT.getVectorElementType().getSimpleVT();
12130 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12132 EVT ExtraEltVT = ExtraVT.getVectorElementType();
12133 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12134 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12136 SDValue Extra = DAG.getValueType(ExtraVT);
12138 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12139 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12141 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12146 // (sext (vzext x)) -> (vsext x)
12147 SDValue Op0 = Op.getOperand(0);
12148 SDValue Op00 = Op0.getOperand(0);
12150 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12151 if (Op0.getOpcode() == ISD::BITCAST &&
12152 Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12153 Tmp1 = LowerVectorIntExtend(Op00, DAG);
12154 if (Tmp1.getNode()) {
12155 SDValue Tmp1Op0 = Tmp1.getOperand(0);
12156 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12157 "This optimization is invalid without a VZEXT.");
12158 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12161 // If the above didn't work, then just use Shift-Left + Shift-Right.
12162 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12163 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12168 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12169 SelectionDAG &DAG) {
12171 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12172 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12173 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12174 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12176 // The only fence that needs an instruction is a sequentially-consistent
12177 // cross-thread fence.
12178 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12179 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12180 // no-sse2). There isn't any reason to disable it if the target processor
12182 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12183 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12185 SDValue Chain = Op.getOperand(0);
12186 SDValue Zero = DAG.getConstant(0, MVT::i32);
12188 DAG.getRegister(X86::ESP, MVT::i32), // Base
12189 DAG.getTargetConstant(1, MVT::i8), // Scale
12190 DAG.getRegister(0, MVT::i32), // Index
12191 DAG.getTargetConstant(0, MVT::i32), // Disp
12192 DAG.getRegister(0, MVT::i32), // Segment.
12196 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12197 return SDValue(Res, 0);
12200 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12201 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12204 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12205 SelectionDAG &DAG) {
12206 EVT T = Op.getValueType();
12210 switch(T.getSimpleVT().SimpleTy) {
12211 default: llvm_unreachable("Invalid value type!");
12212 case MVT::i8: Reg = X86::AL; size = 1; break;
12213 case MVT::i16: Reg = X86::AX; size = 2; break;
12214 case MVT::i32: Reg = X86::EAX; size = 4; break;
12216 assert(Subtarget->is64Bit() && "Node not type legal!");
12217 Reg = X86::RAX; size = 8;
12220 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12221 Op.getOperand(2), SDValue());
12222 SDValue Ops[] = { cpIn.getValue(0),
12225 DAG.getTargetConstant(size, MVT::i8),
12226 cpIn.getValue(1) };
12227 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12228 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12229 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12230 Ops, array_lengthof(Ops), T, MMO);
12232 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12236 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12237 SelectionDAG &DAG) {
12238 assert(Subtarget->is64Bit() && "Result not type legalized?");
12239 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12240 SDValue TheChain = Op.getOperand(0);
12242 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12243 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12244 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12246 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12247 DAG.getConstant(32, MVT::i8));
12249 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12252 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12255 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12256 EVT SrcVT = Op.getOperand(0).getValueType();
12257 EVT DstVT = Op.getValueType();
12258 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12259 Subtarget->hasMMX() && "Unexpected custom BITCAST");
12260 assert((DstVT == MVT::i64 ||
12261 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12262 "Unexpected custom BITCAST");
12263 // i64 <=> MMX conversions are Legal.
12264 if (SrcVT==MVT::i64 && DstVT.isVector())
12266 if (DstVT==MVT::i64 && SrcVT.isVector())
12268 // MMX <=> MMX conversions are Legal.
12269 if (SrcVT.isVector() && DstVT.isVector())
12271 // All other conversions need to be expanded.
12275 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12276 SDNode *Node = Op.getNode();
12278 EVT T = Node->getValueType(0);
12279 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12280 DAG.getConstant(0, T), Node->getOperand(2));
12281 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12282 cast<AtomicSDNode>(Node)->getMemoryVT(),
12283 Node->getOperand(0),
12284 Node->getOperand(1), negOp,
12285 cast<AtomicSDNode>(Node)->getSrcValue(),
12286 cast<AtomicSDNode>(Node)->getAlignment(),
12287 cast<AtomicSDNode>(Node)->getOrdering(),
12288 cast<AtomicSDNode>(Node)->getSynchScope());
12291 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12292 SDNode *Node = Op.getNode();
12294 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12296 // Convert seq_cst store -> xchg
12297 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12298 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12299 // (The only way to get a 16-byte store is cmpxchg16b)
12300 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12301 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12302 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12303 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12304 cast<AtomicSDNode>(Node)->getMemoryVT(),
12305 Node->getOperand(0),
12306 Node->getOperand(1), Node->getOperand(2),
12307 cast<AtomicSDNode>(Node)->getMemOperand(),
12308 cast<AtomicSDNode>(Node)->getOrdering(),
12309 cast<AtomicSDNode>(Node)->getSynchScope());
12310 return Swap.getValue(1);
12312 // Other atomic stores have a simple pattern.
12316 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12317 EVT VT = Op.getNode()->getValueType(0);
12319 // Let legalize expand this if it isn't a legal type yet.
12320 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12323 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12326 bool ExtraOp = false;
12327 switch (Op.getOpcode()) {
12328 default: llvm_unreachable("Invalid code");
12329 case ISD::ADDC: Opc = X86ISD::ADD; break;
12330 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12331 case ISD::SUBC: Opc = X86ISD::SUB; break;
12332 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12336 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12338 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12339 Op.getOperand(1), Op.getOperand(2));
12342 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12343 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12345 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12346 // which returns the values as { float, float } (in XMM0) or
12347 // { double, double } (which is returned in XMM0, XMM1).
12349 SDValue Arg = Op.getOperand(0);
12350 EVT ArgVT = Arg.getValueType();
12351 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12354 ArgListEntry Entry;
12358 Entry.isSExt = false;
12359 Entry.isZExt = false;
12360 Args.push_back(Entry);
12362 bool isF64 = ArgVT == MVT::f64;
12363 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12364 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12365 // the results are returned via SRet in memory.
12366 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
12367 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12369 Type *RetTy = isF64
12370 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12371 : (Type*)VectorType::get(ArgTy, 4);
12373 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12374 false, false, false, false, 0,
12375 CallingConv::C, /*isTaillCall=*/false,
12376 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12377 Callee, Args, DAG, dl);
12378 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12381 // Returned in xmm0 and xmm1.
12382 return CallResult.first;
12384 // Returned in bits 0:31 and 32:64 xmm0.
12385 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12386 CallResult.first, DAG.getIntPtrConstant(0));
12387 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12388 CallResult.first, DAG.getIntPtrConstant(1));
12389 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12390 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12393 /// LowerOperation - Provide custom lowering hooks for some operations.
12395 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12396 switch (Op.getOpcode()) {
12397 default: llvm_unreachable("Should not custom lower this!");
12398 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12399 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12400 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12401 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12402 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12403 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12404 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12405 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12406 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12407 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12408 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12409 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12410 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12411 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12412 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12413 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12414 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12415 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12416 case ISD::SHL_PARTS:
12417 case ISD::SRA_PARTS:
12418 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12419 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12420 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12421 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12422 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12423 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12424 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12425 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12426 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12427 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12428 case ISD::FABS: return LowerFABS(Op, DAG);
12429 case ISD::FNEG: return LowerFNEG(Op, DAG);
12430 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12431 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12432 case ISD::SETCC: return LowerSETCC(Op, DAG);
12433 case ISD::SELECT: return LowerSELECT(Op, DAG);
12434 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12435 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12436 case ISD::VASTART: return LowerVASTART(Op, DAG);
12437 case ISD::VAARG: return LowerVAARG(Op, DAG);
12438 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12439 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12440 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12441 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12442 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12443 case ISD::FRAME_TO_ARGS_OFFSET:
12444 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12445 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12446 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12447 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12448 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12449 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12450 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12451 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12452 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12453 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12454 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12455 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12458 case ISD::SHL: return LowerShift(Op, DAG);
12464 case ISD::UMULO: return LowerXALUO(Op, DAG);
12465 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12466 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12470 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12471 case ISD::ADD: return LowerADD(Op, DAG);
12472 case ISD::SUB: return LowerSUB(Op, DAG);
12473 case ISD::SDIV: return LowerSDIV(Op, DAG);
12474 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
12478 static void ReplaceATOMIC_LOAD(SDNode *Node,
12479 SmallVectorImpl<SDValue> &Results,
12480 SelectionDAG &DAG) {
12482 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12484 // Convert wide load -> cmpxchg8b/cmpxchg16b
12485 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12486 // (The only way to get a 16-byte load is cmpxchg16b)
12487 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12488 SDValue Zero = DAG.getConstant(0, VT);
12489 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12490 Node->getOperand(0),
12491 Node->getOperand(1), Zero, Zero,
12492 cast<AtomicSDNode>(Node)->getMemOperand(),
12493 cast<AtomicSDNode>(Node)->getOrdering(),
12494 cast<AtomicSDNode>(Node)->getSynchScope());
12495 Results.push_back(Swap.getValue(0));
12496 Results.push_back(Swap.getValue(1));
12500 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12501 SelectionDAG &DAG, unsigned NewOp) {
12503 assert (Node->getValueType(0) == MVT::i64 &&
12504 "Only know how to expand i64 atomics");
12506 SDValue Chain = Node->getOperand(0);
12507 SDValue In1 = Node->getOperand(1);
12508 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12509 Node->getOperand(2), DAG.getIntPtrConstant(0));
12510 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12511 Node->getOperand(2), DAG.getIntPtrConstant(1));
12512 SDValue Ops[] = { Chain, In1, In2L, In2H };
12513 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12515 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12516 cast<MemSDNode>(Node)->getMemOperand());
12517 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12518 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12519 Results.push_back(Result.getValue(2));
12522 /// ReplaceNodeResults - Replace a node with an illegal result type
12523 /// with a new node built out of custom code.
12524 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12525 SmallVectorImpl<SDValue>&Results,
12526 SelectionDAG &DAG) const {
12528 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12529 switch (N->getOpcode()) {
12531 llvm_unreachable("Do not know how to custom type legalize this operation!");
12532 case ISD::SIGN_EXTEND_INREG:
12537 // We don't want to expand or promote these.
12539 case ISD::FP_TO_SINT:
12540 case ISD::FP_TO_UINT: {
12541 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12543 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12546 std::pair<SDValue,SDValue> Vals =
12547 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12548 SDValue FIST = Vals.first, StackSlot = Vals.second;
12549 if (FIST.getNode() != 0) {
12550 EVT VT = N->getValueType(0);
12551 // Return a load from the stack slot.
12552 if (StackSlot.getNode() != 0)
12553 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12554 MachinePointerInfo(),
12555 false, false, false, 0));
12557 Results.push_back(FIST);
12561 case ISD::UINT_TO_FP: {
12562 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12563 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12564 N->getValueType(0) != MVT::v2f32)
12566 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12568 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12570 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12571 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12572 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12573 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12574 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12575 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12578 case ISD::FP_ROUND: {
12579 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12581 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12582 Results.push_back(V);
12585 case ISD::READCYCLECOUNTER: {
12586 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12587 SDValue TheChain = N->getOperand(0);
12588 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12589 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12591 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12593 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12594 SDValue Ops[] = { eax, edx };
12595 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12596 array_lengthof(Ops)));
12597 Results.push_back(edx.getValue(1));
12600 case ISD::ATOMIC_CMP_SWAP: {
12601 EVT T = N->getValueType(0);
12602 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12603 bool Regs64bit = T == MVT::i128;
12604 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12605 SDValue cpInL, cpInH;
12606 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12607 DAG.getConstant(0, HalfT));
12608 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12609 DAG.getConstant(1, HalfT));
12610 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12611 Regs64bit ? X86::RAX : X86::EAX,
12613 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12614 Regs64bit ? X86::RDX : X86::EDX,
12615 cpInH, cpInL.getValue(1));
12616 SDValue swapInL, swapInH;
12617 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12618 DAG.getConstant(0, HalfT));
12619 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12620 DAG.getConstant(1, HalfT));
12621 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12622 Regs64bit ? X86::RBX : X86::EBX,
12623 swapInL, cpInH.getValue(1));
12624 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12625 Regs64bit ? X86::RCX : X86::ECX,
12626 swapInH, swapInL.getValue(1));
12627 SDValue Ops[] = { swapInH.getValue(0),
12629 swapInH.getValue(1) };
12630 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12631 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12632 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12633 X86ISD::LCMPXCHG8_DAG;
12634 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12635 Ops, array_lengthof(Ops), T, MMO);
12636 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12637 Regs64bit ? X86::RAX : X86::EAX,
12638 HalfT, Result.getValue(1));
12639 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12640 Regs64bit ? X86::RDX : X86::EDX,
12641 HalfT, cpOutL.getValue(2));
12642 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12643 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12644 Results.push_back(cpOutH.getValue(1));
12647 case ISD::ATOMIC_LOAD_ADD:
12648 case ISD::ATOMIC_LOAD_AND:
12649 case ISD::ATOMIC_LOAD_NAND:
12650 case ISD::ATOMIC_LOAD_OR:
12651 case ISD::ATOMIC_LOAD_SUB:
12652 case ISD::ATOMIC_LOAD_XOR:
12653 case ISD::ATOMIC_LOAD_MAX:
12654 case ISD::ATOMIC_LOAD_MIN:
12655 case ISD::ATOMIC_LOAD_UMAX:
12656 case ISD::ATOMIC_LOAD_UMIN:
12657 case ISD::ATOMIC_SWAP: {
12659 switch (N->getOpcode()) {
12660 default: llvm_unreachable("Unexpected opcode");
12661 case ISD::ATOMIC_LOAD_ADD:
12662 Opc = X86ISD::ATOMADD64_DAG;
12664 case ISD::ATOMIC_LOAD_AND:
12665 Opc = X86ISD::ATOMAND64_DAG;
12667 case ISD::ATOMIC_LOAD_NAND:
12668 Opc = X86ISD::ATOMNAND64_DAG;
12670 case ISD::ATOMIC_LOAD_OR:
12671 Opc = X86ISD::ATOMOR64_DAG;
12673 case ISD::ATOMIC_LOAD_SUB:
12674 Opc = X86ISD::ATOMSUB64_DAG;
12676 case ISD::ATOMIC_LOAD_XOR:
12677 Opc = X86ISD::ATOMXOR64_DAG;
12679 case ISD::ATOMIC_LOAD_MAX:
12680 Opc = X86ISD::ATOMMAX64_DAG;
12682 case ISD::ATOMIC_LOAD_MIN:
12683 Opc = X86ISD::ATOMMIN64_DAG;
12685 case ISD::ATOMIC_LOAD_UMAX:
12686 Opc = X86ISD::ATOMUMAX64_DAG;
12688 case ISD::ATOMIC_LOAD_UMIN:
12689 Opc = X86ISD::ATOMUMIN64_DAG;
12691 case ISD::ATOMIC_SWAP:
12692 Opc = X86ISD::ATOMSWAP64_DAG;
12695 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12698 case ISD::ATOMIC_LOAD:
12699 ReplaceATOMIC_LOAD(N, Results, DAG);
12703 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12705 default: return NULL;
12706 case X86ISD::BSF: return "X86ISD::BSF";
12707 case X86ISD::BSR: return "X86ISD::BSR";
12708 case X86ISD::SHLD: return "X86ISD::SHLD";
12709 case X86ISD::SHRD: return "X86ISD::SHRD";
12710 case X86ISD::FAND: return "X86ISD::FAND";
12711 case X86ISD::FOR: return "X86ISD::FOR";
12712 case X86ISD::FXOR: return "X86ISD::FXOR";
12713 case X86ISD::FSRL: return "X86ISD::FSRL";
12714 case X86ISD::FILD: return "X86ISD::FILD";
12715 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12716 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12717 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12718 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12719 case X86ISD::FLD: return "X86ISD::FLD";
12720 case X86ISD::FST: return "X86ISD::FST";
12721 case X86ISD::CALL: return "X86ISD::CALL";
12722 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12723 case X86ISD::BT: return "X86ISD::BT";
12724 case X86ISD::CMP: return "X86ISD::CMP";
12725 case X86ISD::COMI: return "X86ISD::COMI";
12726 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12727 case X86ISD::SETCC: return "X86ISD::SETCC";
12728 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12729 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12730 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12731 case X86ISD::CMOV: return "X86ISD::CMOV";
12732 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12733 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12734 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12735 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12736 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12737 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12738 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12739 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12740 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12741 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12742 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12743 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12744 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12745 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12746 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12747 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12748 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12749 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12750 case X86ISD::HADD: return "X86ISD::HADD";
12751 case X86ISD::HSUB: return "X86ISD::HSUB";
12752 case X86ISD::FHADD: return "X86ISD::FHADD";
12753 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12754 case X86ISD::UMAX: return "X86ISD::UMAX";
12755 case X86ISD::UMIN: return "X86ISD::UMIN";
12756 case X86ISD::SMAX: return "X86ISD::SMAX";
12757 case X86ISD::SMIN: return "X86ISD::SMIN";
12758 case X86ISD::FMAX: return "X86ISD::FMAX";
12759 case X86ISD::FMIN: return "X86ISD::FMIN";
12760 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12761 case X86ISD::FMINC: return "X86ISD::FMINC";
12762 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12763 case X86ISD::FRCP: return "X86ISD::FRCP";
12764 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12765 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12766 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12767 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12768 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12769 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12770 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12771 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12772 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12773 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12774 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12775 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12776 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12777 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12778 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12779 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12780 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12781 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12782 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12783 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12784 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12785 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12786 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12787 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12788 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12789 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12790 case X86ISD::VSHL: return "X86ISD::VSHL";
12791 case X86ISD::VSRL: return "X86ISD::VSRL";
12792 case X86ISD::VSRA: return "X86ISD::VSRA";
12793 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12794 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12795 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12796 case X86ISD::CMPP: return "X86ISD::CMPP";
12797 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12798 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12799 case X86ISD::ADD: return "X86ISD::ADD";
12800 case X86ISD::SUB: return "X86ISD::SUB";
12801 case X86ISD::ADC: return "X86ISD::ADC";
12802 case X86ISD::SBB: return "X86ISD::SBB";
12803 case X86ISD::SMUL: return "X86ISD::SMUL";
12804 case X86ISD::UMUL: return "X86ISD::UMUL";
12805 case X86ISD::INC: return "X86ISD::INC";
12806 case X86ISD::DEC: return "X86ISD::DEC";
12807 case X86ISD::OR: return "X86ISD::OR";
12808 case X86ISD::XOR: return "X86ISD::XOR";
12809 case X86ISD::AND: return "X86ISD::AND";
12810 case X86ISD::BLSI: return "X86ISD::BLSI";
12811 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12812 case X86ISD::BLSR: return "X86ISD::BLSR";
12813 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12814 case X86ISD::PTEST: return "X86ISD::PTEST";
12815 case X86ISD::TESTP: return "X86ISD::TESTP";
12816 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
12817 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12818 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12819 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12820 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12821 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12822 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12823 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12824 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12825 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12826 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12827 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12828 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12829 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12830 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12831 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12832 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12833 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12834 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12835 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12836 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12837 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12838 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12839 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12840 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12841 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12842 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12843 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12844 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12845 case X86ISD::SAHF: return "X86ISD::SAHF";
12846 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12847 case X86ISD::RDSEED: return "X86ISD::RDSEED";
12848 case X86ISD::FMADD: return "X86ISD::FMADD";
12849 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12850 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12851 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12852 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12853 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12854 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12855 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12856 case X86ISD::XTEST: return "X86ISD::XTEST";
12860 // isLegalAddressingMode - Return true if the addressing mode represented
12861 // by AM is legal for this target, for a load/store of the specified type.
12862 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12864 // X86 supports extremely general addressing modes.
12865 CodeModel::Model M = getTargetMachine().getCodeModel();
12866 Reloc::Model R = getTargetMachine().getRelocationModel();
12868 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12869 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12874 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12876 // If a reference to this global requires an extra load, we can't fold it.
12877 if (isGlobalStubReference(GVFlags))
12880 // If BaseGV requires a register for the PIC base, we cannot also have a
12881 // BaseReg specified.
12882 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12885 // If lower 4G is not available, then we must use rip-relative addressing.
12886 if ((M != CodeModel::Small || R != Reloc::Static) &&
12887 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12891 switch (AM.Scale) {
12897 // These scales always work.
12902 // These scales are formed with basereg+scalereg. Only accept if there is
12907 default: // Other stuff never works.
12914 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12915 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12917 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12918 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12919 return NumBits1 > NumBits2;
12922 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12923 return isInt<32>(Imm);
12926 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12927 // Can also use sub to handle negated immediates.
12928 return isInt<32>(Imm);
12931 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12932 if (!VT1.isInteger() || !VT2.isInteger())
12934 unsigned NumBits1 = VT1.getSizeInBits();
12935 unsigned NumBits2 = VT2.getSizeInBits();
12936 return NumBits1 > NumBits2;
12939 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12940 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12941 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12944 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12945 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12946 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12949 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12950 EVT VT1 = Val.getValueType();
12951 if (isZExtFree(VT1, VT2))
12954 if (Val.getOpcode() != ISD::LOAD)
12957 if (!VT1.isSimple() || !VT1.isInteger() ||
12958 !VT2.isSimple() || !VT2.isInteger())
12961 switch (VT1.getSimpleVT().SimpleTy) {
12966 // X86 has 8, 16, and 32-bit zero-extending loads.
12973 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12974 // i16 instructions are longer (0x66 prefix) and potentially slower.
12975 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12978 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12979 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12980 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12981 /// are assumed to be legal.
12983 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12985 // Very little shuffling can be done for 64-bit vectors right now.
12986 if (VT.getSizeInBits() == 64)
12989 // FIXME: pshufb, blends, shifts.
12990 return (VT.getVectorNumElements() == 2 ||
12991 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12992 isMOVLMask(M, VT) ||
12993 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12994 isPSHUFDMask(M, VT) ||
12995 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12996 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12997 isPALIGNRMask(M, VT, Subtarget) ||
12998 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12999 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13000 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13001 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13005 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13007 unsigned NumElts = VT.getVectorNumElements();
13008 // FIXME: This collection of masks seems suspect.
13011 if (NumElts == 4 && VT.is128BitVector()) {
13012 return (isMOVLMask(Mask, VT) ||
13013 isCommutedMOVLMask(Mask, VT, true) ||
13014 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13015 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13020 //===----------------------------------------------------------------------===//
13021 // X86 Scheduler Hooks
13022 //===----------------------------------------------------------------------===//
13024 /// Utility function to emit xbegin specifying the start of an RTM region.
13025 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13026 const TargetInstrInfo *TII) {
13027 DebugLoc DL = MI->getDebugLoc();
13029 const BasicBlock *BB = MBB->getBasicBlock();
13030 MachineFunction::iterator I = MBB;
13033 // For the v = xbegin(), we generate
13044 MachineBasicBlock *thisMBB = MBB;
13045 MachineFunction *MF = MBB->getParent();
13046 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13047 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13048 MF->insert(I, mainMBB);
13049 MF->insert(I, sinkMBB);
13051 // Transfer the remainder of BB and its successor edges to sinkMBB.
13052 sinkMBB->splice(sinkMBB->begin(), MBB,
13053 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13054 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13058 // # fallthrough to mainMBB
13059 // # abortion to sinkMBB
13060 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13061 thisMBB->addSuccessor(mainMBB);
13062 thisMBB->addSuccessor(sinkMBB);
13066 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13067 mainMBB->addSuccessor(sinkMBB);
13070 // EAX is live into the sinkMBB
13071 sinkMBB->addLiveIn(X86::EAX);
13072 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13073 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13076 MI->eraseFromParent();
13080 // Get CMPXCHG opcode for the specified data type.
13081 static unsigned getCmpXChgOpcode(EVT VT) {
13082 switch (VT.getSimpleVT().SimpleTy) {
13083 case MVT::i8: return X86::LCMPXCHG8;
13084 case MVT::i16: return X86::LCMPXCHG16;
13085 case MVT::i32: return X86::LCMPXCHG32;
13086 case MVT::i64: return X86::LCMPXCHG64;
13090 llvm_unreachable("Invalid operand size!");
13093 // Get LOAD opcode for the specified data type.
13094 static unsigned getLoadOpcode(EVT VT) {
13095 switch (VT.getSimpleVT().SimpleTy) {
13096 case MVT::i8: return X86::MOV8rm;
13097 case MVT::i16: return X86::MOV16rm;
13098 case MVT::i32: return X86::MOV32rm;
13099 case MVT::i64: return X86::MOV64rm;
13103 llvm_unreachable("Invalid operand size!");
13106 // Get opcode of the non-atomic one from the specified atomic instruction.
13107 static unsigned getNonAtomicOpcode(unsigned Opc) {
13109 case X86::ATOMAND8: return X86::AND8rr;
13110 case X86::ATOMAND16: return X86::AND16rr;
13111 case X86::ATOMAND32: return X86::AND32rr;
13112 case X86::ATOMAND64: return X86::AND64rr;
13113 case X86::ATOMOR8: return X86::OR8rr;
13114 case X86::ATOMOR16: return X86::OR16rr;
13115 case X86::ATOMOR32: return X86::OR32rr;
13116 case X86::ATOMOR64: return X86::OR64rr;
13117 case X86::ATOMXOR8: return X86::XOR8rr;
13118 case X86::ATOMXOR16: return X86::XOR16rr;
13119 case X86::ATOMXOR32: return X86::XOR32rr;
13120 case X86::ATOMXOR64: return X86::XOR64rr;
13122 llvm_unreachable("Unhandled atomic-load-op opcode!");
13125 // Get opcode of the non-atomic one from the specified atomic instruction with
13127 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13128 unsigned &ExtraOpc) {
13130 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
13131 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
13132 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
13133 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
13134 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
13135 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13136 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13137 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13138 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
13139 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13140 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13141 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13142 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
13143 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13144 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13145 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13146 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
13147 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13148 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13149 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13151 llvm_unreachable("Unhandled atomic-load-op opcode!");
13154 // Get opcode of the non-atomic one from the specified atomic instruction for
13155 // 64-bit data type on 32-bit target.
13156 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13158 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
13159 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
13160 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
13161 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
13162 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
13163 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13164 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
13165 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
13166 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
13167 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
13169 llvm_unreachable("Unhandled atomic-load-op opcode!");
13172 // Get opcode of the non-atomic one from the specified atomic instruction for
13173 // 64-bit data type on 32-bit target with extra opcode.
13174 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13176 unsigned &ExtraOpc) {
13178 case X86::ATOMNAND6432:
13179 ExtraOpc = X86::NOT32r;
13180 HiOpc = X86::AND32rr;
13181 return X86::AND32rr;
13183 llvm_unreachable("Unhandled atomic-load-op opcode!");
13186 // Get pseudo CMOV opcode from the specified data type.
13187 static unsigned getPseudoCMOVOpc(EVT VT) {
13188 switch (VT.getSimpleVT().SimpleTy) {
13189 case MVT::i8: return X86::CMOV_GR8;
13190 case MVT::i16: return X86::CMOV_GR16;
13191 case MVT::i32: return X86::CMOV_GR32;
13195 llvm_unreachable("Unknown CMOV opcode!");
13198 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13199 // They will be translated into a spin-loop or compare-exchange loop from
13202 // dst = atomic-fetch-op MI.addr, MI.val
13208 // t1 = LOAD MI.addr
13210 // t4 = phi(t1, t3 / loop)
13211 // t2 = OP MI.val, t4
13213 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13219 MachineBasicBlock *
13220 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13221 MachineBasicBlock *MBB) const {
13222 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13223 DebugLoc DL = MI->getDebugLoc();
13225 MachineFunction *MF = MBB->getParent();
13226 MachineRegisterInfo &MRI = MF->getRegInfo();
13228 const BasicBlock *BB = MBB->getBasicBlock();
13229 MachineFunction::iterator I = MBB;
13232 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13233 "Unexpected number of operands");
13235 assert(MI->hasOneMemOperand() &&
13236 "Expected atomic-load-op to have one memoperand");
13238 // Memory Reference
13239 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13240 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13242 unsigned DstReg, SrcReg;
13243 unsigned MemOpndSlot;
13245 unsigned CurOp = 0;
13247 DstReg = MI->getOperand(CurOp++).getReg();
13248 MemOpndSlot = CurOp;
13249 CurOp += X86::AddrNumOperands;
13250 SrcReg = MI->getOperand(CurOp++).getReg();
13252 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13253 MVT::SimpleValueType VT = *RC->vt_begin();
13254 unsigned t1 = MRI.createVirtualRegister(RC);
13255 unsigned t2 = MRI.createVirtualRegister(RC);
13256 unsigned t3 = MRI.createVirtualRegister(RC);
13257 unsigned t4 = MRI.createVirtualRegister(RC);
13258 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13260 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13261 unsigned LOADOpc = getLoadOpcode(VT);
13263 // For the atomic load-arith operator, we generate
13266 // t1 = LOAD [MI.addr]
13268 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
13269 // t1 = OP MI.val, EAX
13271 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13277 MachineBasicBlock *thisMBB = MBB;
13278 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13279 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13280 MF->insert(I, mainMBB);
13281 MF->insert(I, sinkMBB);
13283 MachineInstrBuilder MIB;
13285 // Transfer the remainder of BB and its successor edges to sinkMBB.
13286 sinkMBB->splice(sinkMBB->begin(), MBB,
13287 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13288 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13291 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13292 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13293 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13295 NewMO.setIsKill(false);
13296 MIB.addOperand(NewMO);
13298 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13299 unsigned flags = (*MMOI)->getFlags();
13300 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13301 MachineMemOperand *MMO =
13302 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13303 (*MMOI)->getSize(),
13304 (*MMOI)->getBaseAlignment(),
13305 (*MMOI)->getTBAAInfo(),
13306 (*MMOI)->getRanges());
13307 MIB.addMemOperand(MMO);
13310 thisMBB->addSuccessor(mainMBB);
13313 MachineBasicBlock *origMainMBB = mainMBB;
13316 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13317 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13319 unsigned Opc = MI->getOpcode();
13322 llvm_unreachable("Unhandled atomic-load-op opcode!");
13323 case X86::ATOMAND8:
13324 case X86::ATOMAND16:
13325 case X86::ATOMAND32:
13326 case X86::ATOMAND64:
13328 case X86::ATOMOR16:
13329 case X86::ATOMOR32:
13330 case X86::ATOMOR64:
13331 case X86::ATOMXOR8:
13332 case X86::ATOMXOR16:
13333 case X86::ATOMXOR32:
13334 case X86::ATOMXOR64: {
13335 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13336 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13340 case X86::ATOMNAND8:
13341 case X86::ATOMNAND16:
13342 case X86::ATOMNAND32:
13343 case X86::ATOMNAND64: {
13344 unsigned Tmp = MRI.createVirtualRegister(RC);
13346 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13347 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13349 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13352 case X86::ATOMMAX8:
13353 case X86::ATOMMAX16:
13354 case X86::ATOMMAX32:
13355 case X86::ATOMMAX64:
13356 case X86::ATOMMIN8:
13357 case X86::ATOMMIN16:
13358 case X86::ATOMMIN32:
13359 case X86::ATOMMIN64:
13360 case X86::ATOMUMAX8:
13361 case X86::ATOMUMAX16:
13362 case X86::ATOMUMAX32:
13363 case X86::ATOMUMAX64:
13364 case X86::ATOMUMIN8:
13365 case X86::ATOMUMIN16:
13366 case X86::ATOMUMIN32:
13367 case X86::ATOMUMIN64: {
13369 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13371 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13375 if (Subtarget->hasCMov()) {
13376 if (VT != MVT::i8) {
13378 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13382 // Promote i8 to i32 to use CMOV32
13383 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13384 const TargetRegisterClass *RC32 =
13385 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13386 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13387 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13388 unsigned Tmp = MRI.createVirtualRegister(RC32);
13390 unsigned Undef = MRI.createVirtualRegister(RC32);
13391 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13393 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13396 .addImm(X86::sub_8bit);
13397 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13400 .addImm(X86::sub_8bit);
13402 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13406 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13407 .addReg(Tmp, 0, X86::sub_8bit);
13410 // Use pseudo select and lower them.
13411 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13412 "Invalid atomic-load-op transformation!");
13413 unsigned SelOpc = getPseudoCMOVOpc(VT);
13414 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13415 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13416 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13417 .addReg(SrcReg).addReg(t4)
13419 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13420 // Replace the original PHI node as mainMBB is changed after CMOV
13422 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13423 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13424 Phi->eraseFromParent();
13430 // Copy PhyReg back from virtual register.
13431 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13434 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13435 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13436 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13438 NewMO.setIsKill(false);
13439 MIB.addOperand(NewMO);
13442 MIB.setMemRefs(MMOBegin, MMOEnd);
13444 // Copy PhyReg back to virtual register.
13445 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13448 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13450 mainMBB->addSuccessor(origMainMBB);
13451 mainMBB->addSuccessor(sinkMBB);
13454 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13455 TII->get(TargetOpcode::COPY), DstReg)
13458 MI->eraseFromParent();
13462 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13463 // instructions. They will be translated into a spin-loop or compare-exchange
13467 // dst = atomic-fetch-op MI.addr, MI.val
13473 // t1L = LOAD [MI.addr + 0]
13474 // t1H = LOAD [MI.addr + 4]
13476 // t4L = phi(t1L, t3L / loop)
13477 // t4H = phi(t1H, t3H / loop)
13478 // t2L = OP MI.val.lo, t4L
13479 // t2H = OP MI.val.hi, t4H
13484 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13492 MachineBasicBlock *
13493 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13494 MachineBasicBlock *MBB) const {
13495 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13496 DebugLoc DL = MI->getDebugLoc();
13498 MachineFunction *MF = MBB->getParent();
13499 MachineRegisterInfo &MRI = MF->getRegInfo();
13501 const BasicBlock *BB = MBB->getBasicBlock();
13502 MachineFunction::iterator I = MBB;
13505 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13506 "Unexpected number of operands");
13508 assert(MI->hasOneMemOperand() &&
13509 "Expected atomic-load-op32 to have one memoperand");
13511 // Memory Reference
13512 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13513 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13515 unsigned DstLoReg, DstHiReg;
13516 unsigned SrcLoReg, SrcHiReg;
13517 unsigned MemOpndSlot;
13519 unsigned CurOp = 0;
13521 DstLoReg = MI->getOperand(CurOp++).getReg();
13522 DstHiReg = MI->getOperand(CurOp++).getReg();
13523 MemOpndSlot = CurOp;
13524 CurOp += X86::AddrNumOperands;
13525 SrcLoReg = MI->getOperand(CurOp++).getReg();
13526 SrcHiReg = MI->getOperand(CurOp++).getReg();
13528 const TargetRegisterClass *RC = &X86::GR32RegClass;
13529 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13531 unsigned t1L = MRI.createVirtualRegister(RC);
13532 unsigned t1H = MRI.createVirtualRegister(RC);
13533 unsigned t2L = MRI.createVirtualRegister(RC);
13534 unsigned t2H = MRI.createVirtualRegister(RC);
13535 unsigned t3L = MRI.createVirtualRegister(RC);
13536 unsigned t3H = MRI.createVirtualRegister(RC);
13537 unsigned t4L = MRI.createVirtualRegister(RC);
13538 unsigned t4H = MRI.createVirtualRegister(RC);
13540 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13541 unsigned LOADOpc = X86::MOV32rm;
13543 // For the atomic load-arith operator, we generate
13546 // t1L = LOAD [MI.addr + 0]
13547 // t1H = LOAD [MI.addr + 4]
13549 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
13550 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
13551 // t2L = OP MI.val.lo, t4L
13552 // t2H = OP MI.val.hi, t4H
13555 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13563 MachineBasicBlock *thisMBB = MBB;
13564 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13565 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13566 MF->insert(I, mainMBB);
13567 MF->insert(I, sinkMBB);
13569 MachineInstrBuilder MIB;
13571 // Transfer the remainder of BB and its successor edges to sinkMBB.
13572 sinkMBB->splice(sinkMBB->begin(), MBB,
13573 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13574 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13578 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13579 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13580 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13582 NewMO.setIsKill(false);
13583 MIB.addOperand(NewMO);
13585 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13586 unsigned flags = (*MMOI)->getFlags();
13587 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13588 MachineMemOperand *MMO =
13589 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13590 (*MMOI)->getSize(),
13591 (*MMOI)->getBaseAlignment(),
13592 (*MMOI)->getTBAAInfo(),
13593 (*MMOI)->getRanges());
13594 MIB.addMemOperand(MMO);
13596 MachineInstr *LowMI = MIB;
13599 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13600 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13601 if (i == X86::AddrDisp) {
13602 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13604 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13606 NewMO.setIsKill(false);
13607 MIB.addOperand(NewMO);
13610 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13612 thisMBB->addSuccessor(mainMBB);
13615 MachineBasicBlock *origMainMBB = mainMBB;
13618 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13619 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13620 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13621 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13623 unsigned Opc = MI->getOpcode();
13626 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13627 case X86::ATOMAND6432:
13628 case X86::ATOMOR6432:
13629 case X86::ATOMXOR6432:
13630 case X86::ATOMADD6432:
13631 case X86::ATOMSUB6432: {
13633 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13634 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13636 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13640 case X86::ATOMNAND6432: {
13641 unsigned HiOpc, NOTOpc;
13642 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13643 unsigned TmpL = MRI.createVirtualRegister(RC);
13644 unsigned TmpH = MRI.createVirtualRegister(RC);
13645 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13647 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13649 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13650 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13653 case X86::ATOMMAX6432:
13654 case X86::ATOMMIN6432:
13655 case X86::ATOMUMAX6432:
13656 case X86::ATOMUMIN6432: {
13658 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13659 unsigned cL = MRI.createVirtualRegister(RC8);
13660 unsigned cH = MRI.createVirtualRegister(RC8);
13661 unsigned cL32 = MRI.createVirtualRegister(RC);
13662 unsigned cH32 = MRI.createVirtualRegister(RC);
13663 unsigned cc = MRI.createVirtualRegister(RC);
13664 // cl := cmp src_lo, lo
13665 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13666 .addReg(SrcLoReg).addReg(t4L);
13667 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13668 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13669 // ch := cmp src_hi, hi
13670 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13671 .addReg(SrcHiReg).addReg(t4H);
13672 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13673 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13674 // cc := if (src_hi == hi) ? cl : ch;
13675 if (Subtarget->hasCMov()) {
13676 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13677 .addReg(cH32).addReg(cL32);
13679 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13680 .addReg(cH32).addReg(cL32)
13681 .addImm(X86::COND_E);
13682 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13684 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13685 if (Subtarget->hasCMov()) {
13686 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13687 .addReg(SrcLoReg).addReg(t4L);
13688 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13689 .addReg(SrcHiReg).addReg(t4H);
13691 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13692 .addReg(SrcLoReg).addReg(t4L)
13693 .addImm(X86::COND_NE);
13694 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13695 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13696 // 2nd CMOV lowering.
13697 mainMBB->addLiveIn(X86::EFLAGS);
13698 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13699 .addReg(SrcHiReg).addReg(t4H)
13700 .addImm(X86::COND_NE);
13701 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13702 // Replace the original PHI node as mainMBB is changed after CMOV
13704 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13705 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13706 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13707 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13708 PhiL->eraseFromParent();
13709 PhiH->eraseFromParent();
13713 case X86::ATOMSWAP6432: {
13715 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13716 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13717 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13722 // Copy EDX:EAX back from HiReg:LoReg
13723 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13724 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13725 // Copy ECX:EBX from t1H:t1L
13726 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13727 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13729 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13730 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13731 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13733 NewMO.setIsKill(false);
13734 MIB.addOperand(NewMO);
13736 MIB.setMemRefs(MMOBegin, MMOEnd);
13738 // Copy EDX:EAX back to t3H:t3L
13739 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13740 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13742 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13744 mainMBB->addSuccessor(origMainMBB);
13745 mainMBB->addSuccessor(sinkMBB);
13748 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13749 TII->get(TargetOpcode::COPY), DstLoReg)
13751 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13752 TII->get(TargetOpcode::COPY), DstHiReg)
13755 MI->eraseFromParent();
13759 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13760 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13761 // in the .td file.
13762 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13763 const TargetInstrInfo *TII) {
13765 switch (MI->getOpcode()) {
13766 default: llvm_unreachable("illegal opcode!");
13767 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13768 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13769 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13770 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13771 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13772 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13773 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13774 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13777 DebugLoc dl = MI->getDebugLoc();
13778 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13780 unsigned NumArgs = MI->getNumOperands();
13781 for (unsigned i = 1; i < NumArgs; ++i) {
13782 MachineOperand &Op = MI->getOperand(i);
13783 if (!(Op.isReg() && Op.isImplicit()))
13784 MIB.addOperand(Op);
13786 if (MI->hasOneMemOperand())
13787 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13789 BuildMI(*BB, MI, dl,
13790 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13791 .addReg(X86::XMM0);
13793 MI->eraseFromParent();
13797 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13798 // defs in an instruction pattern
13799 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13800 const TargetInstrInfo *TII) {
13802 switch (MI->getOpcode()) {
13803 default: llvm_unreachable("illegal opcode!");
13804 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13805 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13806 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13807 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13808 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13809 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13810 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13811 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13814 DebugLoc dl = MI->getDebugLoc();
13815 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13817 unsigned NumArgs = MI->getNumOperands(); // remove the results
13818 for (unsigned i = 1; i < NumArgs; ++i) {
13819 MachineOperand &Op = MI->getOperand(i);
13820 if (!(Op.isReg() && Op.isImplicit()))
13821 MIB.addOperand(Op);
13823 if (MI->hasOneMemOperand())
13824 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13826 BuildMI(*BB, MI, dl,
13827 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13830 MI->eraseFromParent();
13834 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13835 const TargetInstrInfo *TII,
13836 const X86Subtarget* Subtarget) {
13837 DebugLoc dl = MI->getDebugLoc();
13839 // Address into RAX/EAX, other two args into ECX, EDX.
13840 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13841 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13842 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13843 for (int i = 0; i < X86::AddrNumOperands; ++i)
13844 MIB.addOperand(MI->getOperand(i));
13846 unsigned ValOps = X86::AddrNumOperands;
13847 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13848 .addReg(MI->getOperand(ValOps).getReg());
13849 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13850 .addReg(MI->getOperand(ValOps+1).getReg());
13852 // The instruction doesn't actually take any operands though.
13853 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13855 MI->eraseFromParent(); // The pseudo is gone now.
13859 MachineBasicBlock *
13860 X86TargetLowering::EmitVAARG64WithCustomInserter(
13862 MachineBasicBlock *MBB) const {
13863 // Emit va_arg instruction on X86-64.
13865 // Operands to this pseudo-instruction:
13866 // 0 ) Output : destination address (reg)
13867 // 1-5) Input : va_list address (addr, i64mem)
13868 // 6 ) ArgSize : Size (in bytes) of vararg type
13869 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13870 // 8 ) Align : Alignment of type
13871 // 9 ) EFLAGS (implicit-def)
13873 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13874 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13876 unsigned DestReg = MI->getOperand(0).getReg();
13877 MachineOperand &Base = MI->getOperand(1);
13878 MachineOperand &Scale = MI->getOperand(2);
13879 MachineOperand &Index = MI->getOperand(3);
13880 MachineOperand &Disp = MI->getOperand(4);
13881 MachineOperand &Segment = MI->getOperand(5);
13882 unsigned ArgSize = MI->getOperand(6).getImm();
13883 unsigned ArgMode = MI->getOperand(7).getImm();
13884 unsigned Align = MI->getOperand(8).getImm();
13886 // Memory Reference
13887 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13888 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13889 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13891 // Machine Information
13892 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13893 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13894 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13895 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13896 DebugLoc DL = MI->getDebugLoc();
13898 // struct va_list {
13901 // i64 overflow_area (address)
13902 // i64 reg_save_area (address)
13904 // sizeof(va_list) = 24
13905 // alignment(va_list) = 8
13907 unsigned TotalNumIntRegs = 6;
13908 unsigned TotalNumXMMRegs = 8;
13909 bool UseGPOffset = (ArgMode == 1);
13910 bool UseFPOffset = (ArgMode == 2);
13911 unsigned MaxOffset = TotalNumIntRegs * 8 +
13912 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13914 /* Align ArgSize to a multiple of 8 */
13915 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13916 bool NeedsAlign = (Align > 8);
13918 MachineBasicBlock *thisMBB = MBB;
13919 MachineBasicBlock *overflowMBB;
13920 MachineBasicBlock *offsetMBB;
13921 MachineBasicBlock *endMBB;
13923 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13924 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13925 unsigned OffsetReg = 0;
13927 if (!UseGPOffset && !UseFPOffset) {
13928 // If we only pull from the overflow region, we don't create a branch.
13929 // We don't need to alter control flow.
13930 OffsetDestReg = 0; // unused
13931 OverflowDestReg = DestReg;
13934 overflowMBB = thisMBB;
13937 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13938 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13939 // If not, pull from overflow_area. (branch to overflowMBB)
13944 // offsetMBB overflowMBB
13949 // Registers for the PHI in endMBB
13950 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13951 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13953 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13954 MachineFunction *MF = MBB->getParent();
13955 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13956 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13957 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13959 MachineFunction::iterator MBBIter = MBB;
13962 // Insert the new basic blocks
13963 MF->insert(MBBIter, offsetMBB);
13964 MF->insert(MBBIter, overflowMBB);
13965 MF->insert(MBBIter, endMBB);
13967 // Transfer the remainder of MBB and its successor edges to endMBB.
13968 endMBB->splice(endMBB->begin(), thisMBB,
13969 llvm::next(MachineBasicBlock::iterator(MI)),
13971 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13973 // Make offsetMBB and overflowMBB successors of thisMBB
13974 thisMBB->addSuccessor(offsetMBB);
13975 thisMBB->addSuccessor(overflowMBB);
13977 // endMBB is a successor of both offsetMBB and overflowMBB
13978 offsetMBB->addSuccessor(endMBB);
13979 overflowMBB->addSuccessor(endMBB);
13981 // Load the offset value into a register
13982 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13983 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13987 .addDisp(Disp, UseFPOffset ? 4 : 0)
13988 .addOperand(Segment)
13989 .setMemRefs(MMOBegin, MMOEnd);
13991 // Check if there is enough room left to pull this argument.
13992 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13994 .addImm(MaxOffset + 8 - ArgSizeA8);
13996 // Branch to "overflowMBB" if offset >= max
13997 // Fall through to "offsetMBB" otherwise
13998 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13999 .addMBB(overflowMBB);
14002 // In offsetMBB, emit code to use the reg_save_area.
14004 assert(OffsetReg != 0);
14006 // Read the reg_save_area address.
14007 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14008 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14013 .addOperand(Segment)
14014 .setMemRefs(MMOBegin, MMOEnd);
14016 // Zero-extend the offset
14017 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14018 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14021 .addImm(X86::sub_32bit);
14023 // Add the offset to the reg_save_area to get the final address.
14024 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14025 .addReg(OffsetReg64)
14026 .addReg(RegSaveReg);
14028 // Compute the offset for the next argument
14029 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14030 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14032 .addImm(UseFPOffset ? 16 : 8);
14034 // Store it back into the va_list.
14035 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14039 .addDisp(Disp, UseFPOffset ? 4 : 0)
14040 .addOperand(Segment)
14041 .addReg(NextOffsetReg)
14042 .setMemRefs(MMOBegin, MMOEnd);
14045 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14050 // Emit code to use overflow area
14053 // Load the overflow_area address into a register.
14054 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14055 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14060 .addOperand(Segment)
14061 .setMemRefs(MMOBegin, MMOEnd);
14063 // If we need to align it, do so. Otherwise, just copy the address
14064 // to OverflowDestReg.
14066 // Align the overflow address
14067 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14068 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14070 // aligned_addr = (addr + (align-1)) & ~(align-1)
14071 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14072 .addReg(OverflowAddrReg)
14075 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14077 .addImm(~(uint64_t)(Align-1));
14079 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14080 .addReg(OverflowAddrReg);
14083 // Compute the next overflow address after this argument.
14084 // (the overflow address should be kept 8-byte aligned)
14085 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14086 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14087 .addReg(OverflowDestReg)
14088 .addImm(ArgSizeA8);
14090 // Store the new overflow address.
14091 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14096 .addOperand(Segment)
14097 .addReg(NextAddrReg)
14098 .setMemRefs(MMOBegin, MMOEnd);
14100 // If we branched, emit the PHI to the front of endMBB.
14102 BuildMI(*endMBB, endMBB->begin(), DL,
14103 TII->get(X86::PHI), DestReg)
14104 .addReg(OffsetDestReg).addMBB(offsetMBB)
14105 .addReg(OverflowDestReg).addMBB(overflowMBB);
14108 // Erase the pseudo instruction
14109 MI->eraseFromParent();
14114 MachineBasicBlock *
14115 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14117 MachineBasicBlock *MBB) const {
14118 // Emit code to save XMM registers to the stack. The ABI says that the
14119 // number of registers to save is given in %al, so it's theoretically
14120 // possible to do an indirect jump trick to avoid saving all of them,
14121 // however this code takes a simpler approach and just executes all
14122 // of the stores if %al is non-zero. It's less code, and it's probably
14123 // easier on the hardware branch predictor, and stores aren't all that
14124 // expensive anyway.
14126 // Create the new basic blocks. One block contains all the XMM stores,
14127 // and one block is the final destination regardless of whether any
14128 // stores were performed.
14129 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14130 MachineFunction *F = MBB->getParent();
14131 MachineFunction::iterator MBBIter = MBB;
14133 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14134 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14135 F->insert(MBBIter, XMMSaveMBB);
14136 F->insert(MBBIter, EndMBB);
14138 // Transfer the remainder of MBB and its successor edges to EndMBB.
14139 EndMBB->splice(EndMBB->begin(), MBB,
14140 llvm::next(MachineBasicBlock::iterator(MI)),
14142 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14144 // The original block will now fall through to the XMM save block.
14145 MBB->addSuccessor(XMMSaveMBB);
14146 // The XMMSaveMBB will fall through to the end block.
14147 XMMSaveMBB->addSuccessor(EndMBB);
14149 // Now add the instructions.
14150 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14151 DebugLoc DL = MI->getDebugLoc();
14153 unsigned CountReg = MI->getOperand(0).getReg();
14154 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14155 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14157 if (!Subtarget->isTargetWin64()) {
14158 // If %al is 0, branch around the XMM save block.
14159 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14160 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14161 MBB->addSuccessor(EndMBB);
14164 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14165 // In the XMM save block, save all the XMM argument registers.
14166 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14167 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14168 MachineMemOperand *MMO =
14169 F->getMachineMemOperand(
14170 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14171 MachineMemOperand::MOStore,
14172 /*Size=*/16, /*Align=*/16);
14173 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14174 .addFrameIndex(RegSaveFrameIndex)
14175 .addImm(/*Scale=*/1)
14176 .addReg(/*IndexReg=*/0)
14177 .addImm(/*Disp=*/Offset)
14178 .addReg(/*Segment=*/0)
14179 .addReg(MI->getOperand(i).getReg())
14180 .addMemOperand(MMO);
14183 MI->eraseFromParent(); // The pseudo instruction is gone now.
14188 // The EFLAGS operand of SelectItr might be missing a kill marker
14189 // because there were multiple uses of EFLAGS, and ISel didn't know
14190 // which to mark. Figure out whether SelectItr should have had a
14191 // kill marker, and set it if it should. Returns the correct kill
14193 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14194 MachineBasicBlock* BB,
14195 const TargetRegisterInfo* TRI) {
14196 // Scan forward through BB for a use/def of EFLAGS.
14197 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14198 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14199 const MachineInstr& mi = *miI;
14200 if (mi.readsRegister(X86::EFLAGS))
14202 if (mi.definesRegister(X86::EFLAGS))
14203 break; // Should have kill-flag - update below.
14206 // If we hit the end of the block, check whether EFLAGS is live into a
14208 if (miI == BB->end()) {
14209 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14210 sEnd = BB->succ_end();
14211 sItr != sEnd; ++sItr) {
14212 MachineBasicBlock* succ = *sItr;
14213 if (succ->isLiveIn(X86::EFLAGS))
14218 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14219 // out. SelectMI should have a kill flag on EFLAGS.
14220 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14224 MachineBasicBlock *
14225 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14226 MachineBasicBlock *BB) const {
14227 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14228 DebugLoc DL = MI->getDebugLoc();
14230 // To "insert" a SELECT_CC instruction, we actually have to insert the
14231 // diamond control-flow pattern. The incoming instruction knows the
14232 // destination vreg to set, the condition code register to branch on, the
14233 // true/false values to select between, and a branch opcode to use.
14234 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14235 MachineFunction::iterator It = BB;
14241 // cmpTY ccX, r1, r2
14243 // fallthrough --> copy0MBB
14244 MachineBasicBlock *thisMBB = BB;
14245 MachineFunction *F = BB->getParent();
14246 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14247 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14248 F->insert(It, copy0MBB);
14249 F->insert(It, sinkMBB);
14251 // If the EFLAGS register isn't dead in the terminator, then claim that it's
14252 // live into the sink and copy blocks.
14253 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14254 if (!MI->killsRegister(X86::EFLAGS) &&
14255 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14256 copy0MBB->addLiveIn(X86::EFLAGS);
14257 sinkMBB->addLiveIn(X86::EFLAGS);
14260 // Transfer the remainder of BB and its successor edges to sinkMBB.
14261 sinkMBB->splice(sinkMBB->begin(), BB,
14262 llvm::next(MachineBasicBlock::iterator(MI)),
14264 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14266 // Add the true and fallthrough blocks as its successors.
14267 BB->addSuccessor(copy0MBB);
14268 BB->addSuccessor(sinkMBB);
14270 // Create the conditional branch instruction.
14272 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14273 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14276 // %FalseValue = ...
14277 // # fallthrough to sinkMBB
14278 copy0MBB->addSuccessor(sinkMBB);
14281 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14283 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14284 TII->get(X86::PHI), MI->getOperand(0).getReg())
14285 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14286 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14288 MI->eraseFromParent(); // The pseudo instruction is gone now.
14292 MachineBasicBlock *
14293 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14294 bool Is64Bit) const {
14295 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14296 DebugLoc DL = MI->getDebugLoc();
14297 MachineFunction *MF = BB->getParent();
14298 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14300 assert(getTargetMachine().Options.EnableSegmentedStacks);
14302 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14303 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14306 // ... [Till the alloca]
14307 // If stacklet is not large enough, jump to mallocMBB
14310 // Allocate by subtracting from RSP
14311 // Jump to continueMBB
14314 // Allocate by call to runtime
14318 // [rest of original BB]
14321 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14322 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14323 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14325 MachineRegisterInfo &MRI = MF->getRegInfo();
14326 const TargetRegisterClass *AddrRegClass =
14327 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14329 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14330 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14331 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14332 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14333 sizeVReg = MI->getOperand(1).getReg(),
14334 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14336 MachineFunction::iterator MBBIter = BB;
14339 MF->insert(MBBIter, bumpMBB);
14340 MF->insert(MBBIter, mallocMBB);
14341 MF->insert(MBBIter, continueMBB);
14343 continueMBB->splice(continueMBB->begin(), BB, llvm::next
14344 (MachineBasicBlock::iterator(MI)), BB->end());
14345 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14347 // Add code to the main basic block to check if the stack limit has been hit,
14348 // and if so, jump to mallocMBB otherwise to bumpMBB.
14349 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14350 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14351 .addReg(tmpSPVReg).addReg(sizeVReg);
14352 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14353 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14354 .addReg(SPLimitVReg);
14355 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14357 // bumpMBB simply decreases the stack pointer, since we know the current
14358 // stacklet has enough space.
14359 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14360 .addReg(SPLimitVReg);
14361 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14362 .addReg(SPLimitVReg);
14363 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14365 // Calls into a routine in libgcc to allocate more space from the heap.
14366 const uint32_t *RegMask =
14367 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14369 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14371 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14372 .addExternalSymbol("__morestack_allocate_stack_space")
14373 .addRegMask(RegMask)
14374 .addReg(X86::RDI, RegState::Implicit)
14375 .addReg(X86::RAX, RegState::ImplicitDefine);
14377 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14379 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14380 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14381 .addExternalSymbol("__morestack_allocate_stack_space")
14382 .addRegMask(RegMask)
14383 .addReg(X86::EAX, RegState::ImplicitDefine);
14387 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14390 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14391 .addReg(Is64Bit ? X86::RAX : X86::EAX);
14392 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14394 // Set up the CFG correctly.
14395 BB->addSuccessor(bumpMBB);
14396 BB->addSuccessor(mallocMBB);
14397 mallocMBB->addSuccessor(continueMBB);
14398 bumpMBB->addSuccessor(continueMBB);
14400 // Take care of the PHI nodes.
14401 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14402 MI->getOperand(0).getReg())
14403 .addReg(mallocPtrVReg).addMBB(mallocMBB)
14404 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14406 // Delete the original pseudo instruction.
14407 MI->eraseFromParent();
14410 return continueMBB;
14413 MachineBasicBlock *
14414 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14415 MachineBasicBlock *BB) const {
14416 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14417 DebugLoc DL = MI->getDebugLoc();
14419 assert(!Subtarget->isTargetEnvMacho());
14421 // The lowering is pretty easy: we're just emitting the call to _alloca. The
14422 // non-trivial part is impdef of ESP.
14424 if (Subtarget->isTargetWin64()) {
14425 if (Subtarget->isTargetCygMing()) {
14426 // ___chkstk(Mingw64):
14427 // Clobbers R10, R11, RAX and EFLAGS.
14429 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14430 .addExternalSymbol("___chkstk")
14431 .addReg(X86::RAX, RegState::Implicit)
14432 .addReg(X86::RSP, RegState::Implicit)
14433 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14434 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14435 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14437 // __chkstk(MSVCRT): does not update stack pointer.
14438 // Clobbers R10, R11 and EFLAGS.
14439 // FIXME: RAX(allocated size) might be reused and not killed.
14440 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14441 .addExternalSymbol("__chkstk")
14442 .addReg(X86::RAX, RegState::Implicit)
14443 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14444 // RAX has the offset to subtracted from RSP.
14445 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14450 const char *StackProbeSymbol =
14451 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14453 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14454 .addExternalSymbol(StackProbeSymbol)
14455 .addReg(X86::EAX, RegState::Implicit)
14456 .addReg(X86::ESP, RegState::Implicit)
14457 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14458 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14459 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14462 MI->eraseFromParent(); // The pseudo instruction is gone now.
14466 MachineBasicBlock *
14467 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14468 MachineBasicBlock *BB) const {
14469 // This is pretty easy. We're taking the value that we received from
14470 // our load from the relocation, sticking it in either RDI (x86-64)
14471 // or EAX and doing an indirect call. The return value will then
14472 // be in the normal return register.
14473 const X86InstrInfo *TII
14474 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14475 DebugLoc DL = MI->getDebugLoc();
14476 MachineFunction *F = BB->getParent();
14478 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14479 assert(MI->getOperand(3).isGlobal() && "This should be a global");
14481 // Get a register mask for the lowered call.
14482 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14483 // proper register mask.
14484 const uint32_t *RegMask =
14485 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14486 if (Subtarget->is64Bit()) {
14487 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14488 TII->get(X86::MOV64rm), X86::RDI)
14490 .addImm(0).addReg(0)
14491 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14492 MI->getOperand(3).getTargetFlags())
14494 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14495 addDirectMem(MIB, X86::RDI);
14496 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14497 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14498 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14499 TII->get(X86::MOV32rm), X86::EAX)
14501 .addImm(0).addReg(0)
14502 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14503 MI->getOperand(3).getTargetFlags())
14505 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14506 addDirectMem(MIB, X86::EAX);
14507 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14509 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14510 TII->get(X86::MOV32rm), X86::EAX)
14511 .addReg(TII->getGlobalBaseReg(F))
14512 .addImm(0).addReg(0)
14513 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14514 MI->getOperand(3).getTargetFlags())
14516 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14517 addDirectMem(MIB, X86::EAX);
14518 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14521 MI->eraseFromParent(); // The pseudo instruction is gone now.
14525 MachineBasicBlock *
14526 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14527 MachineBasicBlock *MBB) const {
14528 DebugLoc DL = MI->getDebugLoc();
14529 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14531 MachineFunction *MF = MBB->getParent();
14532 MachineRegisterInfo &MRI = MF->getRegInfo();
14534 const BasicBlock *BB = MBB->getBasicBlock();
14535 MachineFunction::iterator I = MBB;
14538 // Memory Reference
14539 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14540 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14543 unsigned MemOpndSlot = 0;
14545 unsigned CurOp = 0;
14547 DstReg = MI->getOperand(CurOp++).getReg();
14548 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14549 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14550 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14551 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14553 MemOpndSlot = CurOp;
14555 MVT PVT = getPointerTy();
14556 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14557 "Invalid Pointer Size!");
14559 // For v = setjmp(buf), we generate
14562 // buf[LabelOffset] = restoreMBB
14563 // SjLjSetup restoreMBB
14569 // v = phi(main, restore)
14574 MachineBasicBlock *thisMBB = MBB;
14575 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14576 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14577 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14578 MF->insert(I, mainMBB);
14579 MF->insert(I, sinkMBB);
14580 MF->push_back(restoreMBB);
14582 MachineInstrBuilder MIB;
14584 // Transfer the remainder of BB and its successor edges to sinkMBB.
14585 sinkMBB->splice(sinkMBB->begin(), MBB,
14586 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14587 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14590 unsigned PtrStoreOpc = 0;
14591 unsigned LabelReg = 0;
14592 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14593 Reloc::Model RM = getTargetMachine().getRelocationModel();
14594 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14595 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14597 // Prepare IP either in reg or imm.
14598 if (!UseImmLabel) {
14599 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14600 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14601 LabelReg = MRI.createVirtualRegister(PtrRC);
14602 if (Subtarget->is64Bit()) {
14603 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14607 .addMBB(restoreMBB)
14610 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14611 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14612 .addReg(XII->getGlobalBaseReg(MF))
14615 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14619 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14621 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14622 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14623 if (i == X86::AddrDisp)
14624 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14626 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14629 MIB.addReg(LabelReg);
14631 MIB.addMBB(restoreMBB);
14632 MIB.setMemRefs(MMOBegin, MMOEnd);
14634 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14635 .addMBB(restoreMBB);
14637 const X86RegisterInfo *RegInfo =
14638 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14639 MIB.addRegMask(RegInfo->getNoPreservedMask());
14640 thisMBB->addSuccessor(mainMBB);
14641 thisMBB->addSuccessor(restoreMBB);
14645 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14646 mainMBB->addSuccessor(sinkMBB);
14649 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14650 TII->get(X86::PHI), DstReg)
14651 .addReg(mainDstReg).addMBB(mainMBB)
14652 .addReg(restoreDstReg).addMBB(restoreMBB);
14655 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14656 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14657 restoreMBB->addSuccessor(sinkMBB);
14659 MI->eraseFromParent();
14663 MachineBasicBlock *
14664 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14665 MachineBasicBlock *MBB) const {
14666 DebugLoc DL = MI->getDebugLoc();
14667 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14669 MachineFunction *MF = MBB->getParent();
14670 MachineRegisterInfo &MRI = MF->getRegInfo();
14672 // Memory Reference
14673 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14674 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14676 MVT PVT = getPointerTy();
14677 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14678 "Invalid Pointer Size!");
14680 const TargetRegisterClass *RC =
14681 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14682 unsigned Tmp = MRI.createVirtualRegister(RC);
14683 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14684 const X86RegisterInfo *RegInfo =
14685 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14686 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14687 unsigned SP = RegInfo->getStackRegister();
14689 MachineInstrBuilder MIB;
14691 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14692 const int64_t SPOffset = 2 * PVT.getStoreSize();
14694 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14695 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14698 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14699 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14700 MIB.addOperand(MI->getOperand(i));
14701 MIB.setMemRefs(MMOBegin, MMOEnd);
14703 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14704 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14705 if (i == X86::AddrDisp)
14706 MIB.addDisp(MI->getOperand(i), LabelOffset);
14708 MIB.addOperand(MI->getOperand(i));
14710 MIB.setMemRefs(MMOBegin, MMOEnd);
14712 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14713 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14714 if (i == X86::AddrDisp)
14715 MIB.addDisp(MI->getOperand(i), SPOffset);
14717 MIB.addOperand(MI->getOperand(i));
14719 MIB.setMemRefs(MMOBegin, MMOEnd);
14721 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14723 MI->eraseFromParent();
14727 MachineBasicBlock *
14728 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14729 MachineBasicBlock *BB) const {
14730 switch (MI->getOpcode()) {
14731 default: llvm_unreachable("Unexpected instr type to insert");
14732 case X86::TAILJMPd64:
14733 case X86::TAILJMPr64:
14734 case X86::TAILJMPm64:
14735 llvm_unreachable("TAILJMP64 would not be touched here.");
14736 case X86::TCRETURNdi64:
14737 case X86::TCRETURNri64:
14738 case X86::TCRETURNmi64:
14740 case X86::WIN_ALLOCA:
14741 return EmitLoweredWinAlloca(MI, BB);
14742 case X86::SEG_ALLOCA_32:
14743 return EmitLoweredSegAlloca(MI, BB, false);
14744 case X86::SEG_ALLOCA_64:
14745 return EmitLoweredSegAlloca(MI, BB, true);
14746 case X86::TLSCall_32:
14747 case X86::TLSCall_64:
14748 return EmitLoweredTLSCall(MI, BB);
14749 case X86::CMOV_GR8:
14750 case X86::CMOV_FR32:
14751 case X86::CMOV_FR64:
14752 case X86::CMOV_V4F32:
14753 case X86::CMOV_V2F64:
14754 case X86::CMOV_V2I64:
14755 case X86::CMOV_V8F32:
14756 case X86::CMOV_V4F64:
14757 case X86::CMOV_V4I64:
14758 case X86::CMOV_GR16:
14759 case X86::CMOV_GR32:
14760 case X86::CMOV_RFP32:
14761 case X86::CMOV_RFP64:
14762 case X86::CMOV_RFP80:
14763 return EmitLoweredSelect(MI, BB);
14765 case X86::FP32_TO_INT16_IN_MEM:
14766 case X86::FP32_TO_INT32_IN_MEM:
14767 case X86::FP32_TO_INT64_IN_MEM:
14768 case X86::FP64_TO_INT16_IN_MEM:
14769 case X86::FP64_TO_INT32_IN_MEM:
14770 case X86::FP64_TO_INT64_IN_MEM:
14771 case X86::FP80_TO_INT16_IN_MEM:
14772 case X86::FP80_TO_INT32_IN_MEM:
14773 case X86::FP80_TO_INT64_IN_MEM: {
14774 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14775 DebugLoc DL = MI->getDebugLoc();
14777 // Change the floating point control register to use "round towards zero"
14778 // mode when truncating to an integer value.
14779 MachineFunction *F = BB->getParent();
14780 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14781 addFrameReference(BuildMI(*BB, MI, DL,
14782 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14784 // Load the old value of the high byte of the control word...
14786 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14787 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14790 // Set the high part to be round to zero...
14791 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14794 // Reload the modified control word now...
14795 addFrameReference(BuildMI(*BB, MI, DL,
14796 TII->get(X86::FLDCW16m)), CWFrameIdx);
14798 // Restore the memory image of control word to original value
14799 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14802 // Get the X86 opcode to use.
14804 switch (MI->getOpcode()) {
14805 default: llvm_unreachable("illegal opcode!");
14806 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14807 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14808 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14809 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14810 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14811 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14812 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14813 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14814 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14818 MachineOperand &Op = MI->getOperand(0);
14820 AM.BaseType = X86AddressMode::RegBase;
14821 AM.Base.Reg = Op.getReg();
14823 AM.BaseType = X86AddressMode::FrameIndexBase;
14824 AM.Base.FrameIndex = Op.getIndex();
14826 Op = MI->getOperand(1);
14828 AM.Scale = Op.getImm();
14829 Op = MI->getOperand(2);
14831 AM.IndexReg = Op.getImm();
14832 Op = MI->getOperand(3);
14833 if (Op.isGlobal()) {
14834 AM.GV = Op.getGlobal();
14836 AM.Disp = Op.getImm();
14838 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14839 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14841 // Reload the original control word now.
14842 addFrameReference(BuildMI(*BB, MI, DL,
14843 TII->get(X86::FLDCW16m)), CWFrameIdx);
14845 MI->eraseFromParent(); // The pseudo instruction is gone now.
14848 // String/text processing lowering.
14849 case X86::PCMPISTRM128REG:
14850 case X86::VPCMPISTRM128REG:
14851 case X86::PCMPISTRM128MEM:
14852 case X86::VPCMPISTRM128MEM:
14853 case X86::PCMPESTRM128REG:
14854 case X86::VPCMPESTRM128REG:
14855 case X86::PCMPESTRM128MEM:
14856 case X86::VPCMPESTRM128MEM:
14857 assert(Subtarget->hasSSE42() &&
14858 "Target must have SSE4.2 or AVX features enabled");
14859 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14861 // String/text processing lowering.
14862 case X86::PCMPISTRIREG:
14863 case X86::VPCMPISTRIREG:
14864 case X86::PCMPISTRIMEM:
14865 case X86::VPCMPISTRIMEM:
14866 case X86::PCMPESTRIREG:
14867 case X86::VPCMPESTRIREG:
14868 case X86::PCMPESTRIMEM:
14869 case X86::VPCMPESTRIMEM:
14870 assert(Subtarget->hasSSE42() &&
14871 "Target must have SSE4.2 or AVX features enabled");
14872 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14874 // Thread synchronization.
14876 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14880 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14882 // Atomic Lowering.
14883 case X86::ATOMAND8:
14884 case X86::ATOMAND16:
14885 case X86::ATOMAND32:
14886 case X86::ATOMAND64:
14889 case X86::ATOMOR16:
14890 case X86::ATOMOR32:
14891 case X86::ATOMOR64:
14893 case X86::ATOMXOR16:
14894 case X86::ATOMXOR8:
14895 case X86::ATOMXOR32:
14896 case X86::ATOMXOR64:
14898 case X86::ATOMNAND8:
14899 case X86::ATOMNAND16:
14900 case X86::ATOMNAND32:
14901 case X86::ATOMNAND64:
14903 case X86::ATOMMAX8:
14904 case X86::ATOMMAX16:
14905 case X86::ATOMMAX32:
14906 case X86::ATOMMAX64:
14908 case X86::ATOMMIN8:
14909 case X86::ATOMMIN16:
14910 case X86::ATOMMIN32:
14911 case X86::ATOMMIN64:
14913 case X86::ATOMUMAX8:
14914 case X86::ATOMUMAX16:
14915 case X86::ATOMUMAX32:
14916 case X86::ATOMUMAX64:
14918 case X86::ATOMUMIN8:
14919 case X86::ATOMUMIN16:
14920 case X86::ATOMUMIN32:
14921 case X86::ATOMUMIN64:
14922 return EmitAtomicLoadArith(MI, BB);
14924 // This group does 64-bit operations on a 32-bit host.
14925 case X86::ATOMAND6432:
14926 case X86::ATOMOR6432:
14927 case X86::ATOMXOR6432:
14928 case X86::ATOMNAND6432:
14929 case X86::ATOMADD6432:
14930 case X86::ATOMSUB6432:
14931 case X86::ATOMMAX6432:
14932 case X86::ATOMMIN6432:
14933 case X86::ATOMUMAX6432:
14934 case X86::ATOMUMIN6432:
14935 case X86::ATOMSWAP6432:
14936 return EmitAtomicLoadArith6432(MI, BB);
14938 case X86::VASTART_SAVE_XMM_REGS:
14939 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14941 case X86::VAARG_64:
14942 return EmitVAARG64WithCustomInserter(MI, BB);
14944 case X86::EH_SjLj_SetJmp32:
14945 case X86::EH_SjLj_SetJmp64:
14946 return emitEHSjLjSetJmp(MI, BB);
14948 case X86::EH_SjLj_LongJmp32:
14949 case X86::EH_SjLj_LongJmp64:
14950 return emitEHSjLjLongJmp(MI, BB);
14954 //===----------------------------------------------------------------------===//
14955 // X86 Optimization Hooks
14956 //===----------------------------------------------------------------------===//
14958 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14961 const SelectionDAG &DAG,
14962 unsigned Depth) const {
14963 unsigned BitWidth = KnownZero.getBitWidth();
14964 unsigned Opc = Op.getOpcode();
14965 assert((Opc >= ISD::BUILTIN_OP_END ||
14966 Opc == ISD::INTRINSIC_WO_CHAIN ||
14967 Opc == ISD::INTRINSIC_W_CHAIN ||
14968 Opc == ISD::INTRINSIC_VOID) &&
14969 "Should use MaskedValueIsZero if you don't know whether Op"
14970 " is a target node!");
14972 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14986 // These nodes' second result is a boolean.
14987 if (Op.getResNo() == 0)
14990 case X86ISD::SETCC:
14991 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14993 case ISD::INTRINSIC_WO_CHAIN: {
14994 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14995 unsigned NumLoBits = 0;
14998 case Intrinsic::x86_sse_movmsk_ps:
14999 case Intrinsic::x86_avx_movmsk_ps_256:
15000 case Intrinsic::x86_sse2_movmsk_pd:
15001 case Intrinsic::x86_avx_movmsk_pd_256:
15002 case Intrinsic::x86_mmx_pmovmskb:
15003 case Intrinsic::x86_sse2_pmovmskb_128:
15004 case Intrinsic::x86_avx2_pmovmskb: {
15005 // High bits of movmskp{s|d}, pmovmskb are known zero.
15007 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15008 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
15009 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
15010 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
15011 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
15012 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
15013 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
15014 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
15016 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15025 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15026 unsigned Depth) const {
15027 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15028 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15029 return Op.getValueType().getScalarType().getSizeInBits();
15035 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15036 /// node is a GlobalAddress + offset.
15037 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15038 const GlobalValue* &GA,
15039 int64_t &Offset) const {
15040 if (N->getOpcode() == X86ISD::Wrapper) {
15041 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15042 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15043 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15047 return TargetLowering::isGAPlusOffset(N, GA, Offset);
15050 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15051 /// same as extracting the high 128-bit part of 256-bit vector and then
15052 /// inserting the result into the low part of a new 256-bit vector
15053 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15054 EVT VT = SVOp->getValueType(0);
15055 unsigned NumElems = VT.getVectorNumElements();
15057 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15058 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15059 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15060 SVOp->getMaskElt(j) >= 0)
15066 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15067 /// same as extracting the low 128-bit part of 256-bit vector and then
15068 /// inserting the result into the high part of a new 256-bit vector
15069 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15070 EVT VT = SVOp->getValueType(0);
15071 unsigned NumElems = VT.getVectorNumElements();
15073 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15074 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15075 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15076 SVOp->getMaskElt(j) >= 0)
15082 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15083 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15084 TargetLowering::DAGCombinerInfo &DCI,
15085 const X86Subtarget* Subtarget) {
15087 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15088 SDValue V1 = SVOp->getOperand(0);
15089 SDValue V2 = SVOp->getOperand(1);
15090 EVT VT = SVOp->getValueType(0);
15091 unsigned NumElems = VT.getVectorNumElements();
15093 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15094 V2.getOpcode() == ISD::CONCAT_VECTORS) {
15098 // V UNDEF BUILD_VECTOR UNDEF
15100 // CONCAT_VECTOR CONCAT_VECTOR
15103 // RESULT: V + zero extended
15105 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15106 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15107 V1.getOperand(1).getOpcode() != ISD::UNDEF)
15110 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15113 // To match the shuffle mask, the first half of the mask should
15114 // be exactly the first vector, and all the rest a splat with the
15115 // first element of the second one.
15116 for (unsigned i = 0; i != NumElems/2; ++i)
15117 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15118 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15121 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15122 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15123 if (Ld->hasNUsesOfValue(1, 0)) {
15124 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15125 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15127 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15128 array_lengthof(Ops),
15130 Ld->getPointerInfo(),
15131 Ld->getAlignment(),
15132 false/*isVolatile*/, true/*ReadMem*/,
15133 false/*WriteMem*/);
15135 // Make sure the newly-created LOAD is in the same position as Ld in
15136 // terms of dependency. We create a TokenFactor for Ld and ResNode,
15137 // and update uses of Ld's output chain to use the TokenFactor.
15138 if (Ld->hasAnyUseOfValue(1)) {
15139 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15140 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15141 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15142 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15143 SDValue(ResNode.getNode(), 1));
15146 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15150 // Emit a zeroed vector and insert the desired subvector on its
15152 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15153 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15154 return DCI.CombineTo(N, InsV);
15157 //===--------------------------------------------------------------------===//
15158 // Combine some shuffles into subvector extracts and inserts:
15161 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15162 if (isShuffleHigh128VectorInsertLow(SVOp)) {
15163 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15164 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15165 return DCI.CombineTo(N, InsV);
15168 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15169 if (isShuffleLow128VectorInsertHigh(SVOp)) {
15170 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15171 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15172 return DCI.CombineTo(N, InsV);
15178 /// PerformShuffleCombine - Performs several different shuffle combines.
15179 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15180 TargetLowering::DAGCombinerInfo &DCI,
15181 const X86Subtarget *Subtarget) {
15183 EVT VT = N->getValueType(0);
15185 // Don't create instructions with illegal types after legalize types has run.
15186 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15187 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15190 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15191 if (Subtarget->hasFp256() && VT.is256BitVector() &&
15192 N->getOpcode() == ISD::VECTOR_SHUFFLE)
15193 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15195 // Only handle 128 wide vector from here on.
15196 if (!VT.is128BitVector())
15199 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15200 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15201 // consecutive, non-overlapping, and in the right order.
15202 SmallVector<SDValue, 16> Elts;
15203 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15204 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15206 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15209 /// PerformTruncateCombine - Converts truncate operation to
15210 /// a sequence of vector shuffle operations.
15211 /// It is possible when we truncate 256-bit vector to 128-bit vector
15212 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15213 TargetLowering::DAGCombinerInfo &DCI,
15214 const X86Subtarget *Subtarget) {
15218 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15219 /// specific shuffle of a load can be folded into a single element load.
15220 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15221 /// shuffles have been customed lowered so we need to handle those here.
15222 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15223 TargetLowering::DAGCombinerInfo &DCI) {
15224 if (DCI.isBeforeLegalizeOps())
15227 SDValue InVec = N->getOperand(0);
15228 SDValue EltNo = N->getOperand(1);
15230 if (!isa<ConstantSDNode>(EltNo))
15233 EVT VT = InVec.getValueType();
15235 bool HasShuffleIntoBitcast = false;
15236 if (InVec.getOpcode() == ISD::BITCAST) {
15237 // Don't duplicate a load with other uses.
15238 if (!InVec.hasOneUse())
15240 EVT BCVT = InVec.getOperand(0).getValueType();
15241 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15243 InVec = InVec.getOperand(0);
15244 HasShuffleIntoBitcast = true;
15247 if (!isTargetShuffle(InVec.getOpcode()))
15250 // Don't duplicate a load with other uses.
15251 if (!InVec.hasOneUse())
15254 SmallVector<int, 16> ShuffleMask;
15256 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15260 // Select the input vector, guarding against out of range extract vector.
15261 unsigned NumElems = VT.getVectorNumElements();
15262 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15263 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15264 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15265 : InVec.getOperand(1);
15267 // If inputs to shuffle are the same for both ops, then allow 2 uses
15268 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15270 if (LdNode.getOpcode() == ISD::BITCAST) {
15271 // Don't duplicate a load with other uses.
15272 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15275 AllowedUses = 1; // only allow 1 load use if we have a bitcast
15276 LdNode = LdNode.getOperand(0);
15279 if (!ISD::isNormalLoad(LdNode.getNode()))
15282 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15284 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15287 if (HasShuffleIntoBitcast) {
15288 // If there's a bitcast before the shuffle, check if the load type and
15289 // alignment is valid.
15290 unsigned Align = LN0->getAlignment();
15291 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15292 unsigned NewAlign = TLI.getDataLayout()->
15293 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15295 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15299 // All checks match so transform back to vector_shuffle so that DAG combiner
15300 // can finish the job
15303 // Create shuffle node taking into account the case that its a unary shuffle
15304 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15305 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15306 InVec.getOperand(0), Shuffle,
15308 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15309 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15313 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15314 /// generation and convert it from being a bunch of shuffles and extracts
15315 /// to a simple store and scalar loads to extract the elements.
15316 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15317 TargetLowering::DAGCombinerInfo &DCI) {
15318 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15319 if (NewOp.getNode())
15322 SDValue InputVector = N->getOperand(0);
15323 // Detect whether we are trying to convert from mmx to i32 and the bitcast
15324 // from mmx to v2i32 has a single usage.
15325 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15326 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15327 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15328 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15329 N->getValueType(0),
15330 InputVector.getNode()->getOperand(0));
15332 // Only operate on vectors of 4 elements, where the alternative shuffling
15333 // gets to be more expensive.
15334 if (InputVector.getValueType() != MVT::v4i32)
15337 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15338 // single use which is a sign-extend or zero-extend, and all elements are
15340 SmallVector<SDNode *, 4> Uses;
15341 unsigned ExtractedElements = 0;
15342 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15343 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15344 if (UI.getUse().getResNo() != InputVector.getResNo())
15347 SDNode *Extract = *UI;
15348 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15351 if (Extract->getValueType(0) != MVT::i32)
15353 if (!Extract->hasOneUse())
15355 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15356 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15358 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15361 // Record which element was extracted.
15362 ExtractedElements |=
15363 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15365 Uses.push_back(Extract);
15368 // If not all the elements were used, this may not be worthwhile.
15369 if (ExtractedElements != 15)
15372 // Ok, we've now decided to do the transformation.
15373 SDLoc dl(InputVector);
15375 // Store the value to a temporary stack slot.
15376 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15377 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15378 MachinePointerInfo(), false, false, 0);
15380 // Replace each use (extract) with a load of the appropriate element.
15381 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15382 UE = Uses.end(); UI != UE; ++UI) {
15383 SDNode *Extract = *UI;
15385 // cOMpute the element's address.
15386 SDValue Idx = Extract->getOperand(1);
15388 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15389 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15390 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15391 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15393 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15394 StackPtr, OffsetVal);
15396 // Load the scalar.
15397 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15398 ScalarAddr, MachinePointerInfo(),
15399 false, false, false, 0);
15401 // Replace the exact with the load.
15402 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15405 // The replacement was made in place; don't return anything.
15409 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15410 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15411 SDValue RHS, SelectionDAG &DAG,
15412 const X86Subtarget *Subtarget) {
15413 if (!VT.isVector())
15416 switch (VT.getSimpleVT().SimpleTy) {
15421 if (!Subtarget->hasAVX2())
15426 if (!Subtarget->hasSSE2())
15430 // SSE2 has only a small subset of the operations.
15431 bool hasUnsigned = Subtarget->hasSSE41() ||
15432 (Subtarget->hasSSE2() && VT == MVT::v16i8);
15433 bool hasSigned = Subtarget->hasSSE41() ||
15434 (Subtarget->hasSSE2() && VT == MVT::v8i16);
15436 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15438 // Check for x CC y ? x : y.
15439 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15440 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15445 return hasUnsigned ? X86ISD::UMIN : 0;
15448 return hasUnsigned ? X86ISD::UMAX : 0;
15451 return hasSigned ? X86ISD::SMIN : 0;
15454 return hasSigned ? X86ISD::SMAX : 0;
15456 // Check for x CC y ? y : x -- a min/max with reversed arms.
15457 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15458 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15463 return hasUnsigned ? X86ISD::UMAX : 0;
15466 return hasUnsigned ? X86ISD::UMIN : 0;
15469 return hasSigned ? X86ISD::SMAX : 0;
15472 return hasSigned ? X86ISD::SMIN : 0;
15479 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15481 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15482 TargetLowering::DAGCombinerInfo &DCI,
15483 const X86Subtarget *Subtarget) {
15485 SDValue Cond = N->getOperand(0);
15486 // Get the LHS/RHS of the select.
15487 SDValue LHS = N->getOperand(1);
15488 SDValue RHS = N->getOperand(2);
15489 EVT VT = LHS.getValueType();
15491 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15492 // instructions match the semantics of the common C idiom x<y?x:y but not
15493 // x<=y?x:y, because of how they handle negative zero (which can be
15494 // ignored in unsafe-math mode).
15495 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15496 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15497 (Subtarget->hasSSE2() ||
15498 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15499 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15501 unsigned Opcode = 0;
15502 // Check for x CC y ? x : y.
15503 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15504 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15508 // Converting this to a min would handle NaNs incorrectly, and swapping
15509 // the operands would cause it to handle comparisons between positive
15510 // and negative zero incorrectly.
15511 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15512 if (!DAG.getTarget().Options.UnsafeFPMath &&
15513 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15515 std::swap(LHS, RHS);
15517 Opcode = X86ISD::FMIN;
15520 // Converting this to a min would handle comparisons between positive
15521 // and negative zero incorrectly.
15522 if (!DAG.getTarget().Options.UnsafeFPMath &&
15523 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15525 Opcode = X86ISD::FMIN;
15528 // Converting this to a min would handle both negative zeros and NaNs
15529 // incorrectly, but we can swap the operands to fix both.
15530 std::swap(LHS, RHS);
15534 Opcode = X86ISD::FMIN;
15538 // Converting this to a max would handle comparisons between positive
15539 // and negative zero incorrectly.
15540 if (!DAG.getTarget().Options.UnsafeFPMath &&
15541 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15543 Opcode = X86ISD::FMAX;
15546 // Converting this to a max would handle NaNs incorrectly, and swapping
15547 // the operands would cause it to handle comparisons between positive
15548 // and negative zero incorrectly.
15549 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15550 if (!DAG.getTarget().Options.UnsafeFPMath &&
15551 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15553 std::swap(LHS, RHS);
15555 Opcode = X86ISD::FMAX;
15558 // Converting this to a max would handle both negative zeros and NaNs
15559 // incorrectly, but we can swap the operands to fix both.
15560 std::swap(LHS, RHS);
15564 Opcode = X86ISD::FMAX;
15567 // Check for x CC y ? y : x -- a min/max with reversed arms.
15568 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15569 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15573 // Converting this to a min would handle comparisons between positive
15574 // and negative zero incorrectly, and swapping the operands would
15575 // cause it to handle NaNs incorrectly.
15576 if (!DAG.getTarget().Options.UnsafeFPMath &&
15577 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15578 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15580 std::swap(LHS, RHS);
15582 Opcode = X86ISD::FMIN;
15585 // Converting this to a min would handle NaNs incorrectly.
15586 if (!DAG.getTarget().Options.UnsafeFPMath &&
15587 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15589 Opcode = X86ISD::FMIN;
15592 // Converting this to a min would handle both negative zeros and NaNs
15593 // incorrectly, but we can swap the operands to fix both.
15594 std::swap(LHS, RHS);
15598 Opcode = X86ISD::FMIN;
15602 // Converting this to a max would handle NaNs incorrectly.
15603 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15605 Opcode = X86ISD::FMAX;
15608 // Converting this to a max would handle comparisons between positive
15609 // and negative zero incorrectly, and swapping the operands would
15610 // cause it to handle NaNs incorrectly.
15611 if (!DAG.getTarget().Options.UnsafeFPMath &&
15612 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15613 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15615 std::swap(LHS, RHS);
15617 Opcode = X86ISD::FMAX;
15620 // Converting this to a max would handle both negative zeros and NaNs
15621 // incorrectly, but we can swap the operands to fix both.
15622 std::swap(LHS, RHS);
15626 Opcode = X86ISD::FMAX;
15632 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15635 // If this is a select between two integer constants, try to do some
15637 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15638 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15639 // Don't do this for crazy integer types.
15640 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15641 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15642 // so that TrueC (the true value) is larger than FalseC.
15643 bool NeedsCondInvert = false;
15645 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15646 // Efficiently invertible.
15647 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15648 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15649 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15650 NeedsCondInvert = true;
15651 std::swap(TrueC, FalseC);
15654 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15655 if (FalseC->getAPIntValue() == 0 &&
15656 TrueC->getAPIntValue().isPowerOf2()) {
15657 if (NeedsCondInvert) // Invert the condition if needed.
15658 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15659 DAG.getConstant(1, Cond.getValueType()));
15661 // Zero extend the condition if needed.
15662 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15664 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15665 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15666 DAG.getConstant(ShAmt, MVT::i8));
15669 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15670 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15671 if (NeedsCondInvert) // Invert the condition if needed.
15672 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15673 DAG.getConstant(1, Cond.getValueType()));
15675 // Zero extend the condition if needed.
15676 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15677 FalseC->getValueType(0), Cond);
15678 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15679 SDValue(FalseC, 0));
15682 // Optimize cases that will turn into an LEA instruction. This requires
15683 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15684 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15685 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15686 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15688 bool isFastMultiplier = false;
15690 switch ((unsigned char)Diff) {
15692 case 1: // result = add base, cond
15693 case 2: // result = lea base( , cond*2)
15694 case 3: // result = lea base(cond, cond*2)
15695 case 4: // result = lea base( , cond*4)
15696 case 5: // result = lea base(cond, cond*4)
15697 case 8: // result = lea base( , cond*8)
15698 case 9: // result = lea base(cond, cond*8)
15699 isFastMultiplier = true;
15704 if (isFastMultiplier) {
15705 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15706 if (NeedsCondInvert) // Invert the condition if needed.
15707 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15708 DAG.getConstant(1, Cond.getValueType()));
15710 // Zero extend the condition if needed.
15711 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15713 // Scale the condition by the difference.
15715 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15716 DAG.getConstant(Diff, Cond.getValueType()));
15718 // Add the base if non-zero.
15719 if (FalseC->getAPIntValue() != 0)
15720 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15721 SDValue(FalseC, 0));
15728 // Canonicalize max and min:
15729 // (x > y) ? x : y -> (x >= y) ? x : y
15730 // (x < y) ? x : y -> (x <= y) ? x : y
15731 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15732 // the need for an extra compare
15733 // against zero. e.g.
15734 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15736 // testl %edi, %edi
15738 // cmovgl %edi, %eax
15742 // cmovsl %eax, %edi
15743 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15744 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15745 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15746 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15751 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15752 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
15753 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15754 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15759 // Match VSELECTs into subs with unsigned saturation.
15760 if (!DCI.isBeforeLegalize() &&
15761 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15762 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15763 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15764 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15765 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15767 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15768 // left side invert the predicate to simplify logic below.
15770 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15772 CC = ISD::getSetCCInverse(CC, true);
15773 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15777 if (Other.getNode() && Other->getNumOperands() == 2 &&
15778 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15779 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15780 SDValue CondRHS = Cond->getOperand(1);
15782 // Look for a general sub with unsigned saturation first.
15783 // x >= y ? x-y : 0 --> subus x, y
15784 // x > y ? x-y : 0 --> subus x, y
15785 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15786 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15787 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15789 // If the RHS is a constant we have to reverse the const canonicalization.
15790 // x > C-1 ? x+-C : 0 --> subus x, C
15791 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15792 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15793 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15794 if (CondRHS.getConstantOperandVal(0) == -A-1)
15795 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15796 DAG.getConstant(-A, VT));
15799 // Another special case: If C was a sign bit, the sub has been
15800 // canonicalized into a xor.
15801 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15802 // it's safe to decanonicalize the xor?
15803 // x s< 0 ? x^C : 0 --> subus x, C
15804 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15805 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15806 isSplatVector(OpRHS.getNode())) {
15807 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15809 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15814 // Try to match a min/max vector operation.
15815 if (!DCI.isBeforeLegalize() &&
15816 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15817 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15818 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15820 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15821 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15822 Cond.getOpcode() == ISD::SETCC) {
15824 assert(Cond.getValueType().isVector() &&
15825 "vector select expects a vector selector!");
15827 EVT IntVT = Cond.getValueType();
15828 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15829 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15831 if (!TValIsAllOnes && !FValIsAllZeros) {
15832 // Try invert the condition if true value is not all 1s and false value
15834 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15835 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15837 if (TValIsAllZeros || FValIsAllOnes) {
15838 SDValue CC = Cond.getOperand(2);
15839 ISD::CondCode NewCC =
15840 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15841 Cond.getOperand(0).getValueType().isInteger());
15842 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15843 std::swap(LHS, RHS);
15844 TValIsAllOnes = FValIsAllOnes;
15845 FValIsAllZeros = TValIsAllZeros;
15849 if (TValIsAllOnes || FValIsAllZeros) {
15852 if (TValIsAllOnes && FValIsAllZeros)
15854 else if (TValIsAllOnes)
15855 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15856 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15857 else if (FValIsAllZeros)
15858 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15859 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15861 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15865 // If we know that this node is legal then we know that it is going to be
15866 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15867 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15868 // to simplify previous instructions.
15869 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15870 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15871 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15872 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15874 // Don't optimize vector selects that map to mask-registers.
15878 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15879 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15881 APInt KnownZero, KnownOne;
15882 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15883 DCI.isBeforeLegalizeOps());
15884 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15885 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15886 DCI.CommitTargetLoweringOpt(TLO);
15892 // Check whether a boolean test is testing a boolean value generated by
15893 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15896 // Simplify the following patterns:
15897 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15898 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15899 // to (Op EFLAGS Cond)
15901 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15902 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15903 // to (Op EFLAGS !Cond)
15905 // where Op could be BRCOND or CMOV.
15907 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15908 // Quit if not CMP and SUB with its value result used.
15909 if (Cmp.getOpcode() != X86ISD::CMP &&
15910 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15913 // Quit if not used as a boolean value.
15914 if (CC != X86::COND_E && CC != X86::COND_NE)
15917 // Check CMP operands. One of them should be 0 or 1 and the other should be
15918 // an SetCC or extended from it.
15919 SDValue Op1 = Cmp.getOperand(0);
15920 SDValue Op2 = Cmp.getOperand(1);
15923 const ConstantSDNode* C = 0;
15924 bool needOppositeCond = (CC == X86::COND_E);
15925 bool checkAgainstTrue = false; // Is it a comparison against 1?
15927 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15929 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15931 else // Quit if all operands are not constants.
15934 if (C->getZExtValue() == 1) {
15935 needOppositeCond = !needOppositeCond;
15936 checkAgainstTrue = true;
15937 } else if (C->getZExtValue() != 0)
15938 // Quit if the constant is neither 0 or 1.
15941 bool truncatedToBoolWithAnd = false;
15942 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15943 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15944 SetCC.getOpcode() == ISD::TRUNCATE ||
15945 SetCC.getOpcode() == ISD::AND) {
15946 if (SetCC.getOpcode() == ISD::AND) {
15948 ConstantSDNode *CS;
15949 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15950 CS->getZExtValue() == 1)
15952 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15953 CS->getZExtValue() == 1)
15957 SetCC = SetCC.getOperand(OpIdx);
15958 truncatedToBoolWithAnd = true;
15960 SetCC = SetCC.getOperand(0);
15963 switch (SetCC.getOpcode()) {
15964 case X86ISD::SETCC_CARRY:
15965 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15966 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15967 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15968 // truncated to i1 using 'and'.
15969 if (checkAgainstTrue && !truncatedToBoolWithAnd)
15971 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15972 "Invalid use of SETCC_CARRY!");
15974 case X86ISD::SETCC:
15975 // Set the condition code or opposite one if necessary.
15976 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15977 if (needOppositeCond)
15978 CC = X86::GetOppositeBranchCondition(CC);
15979 return SetCC.getOperand(1);
15980 case X86ISD::CMOV: {
15981 // Check whether false/true value has canonical one, i.e. 0 or 1.
15982 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15983 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15984 // Quit if true value is not a constant.
15987 // Quit if false value is not a constant.
15989 SDValue Op = SetCC.getOperand(0);
15990 // Skip 'zext' or 'trunc' node.
15991 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15992 Op.getOpcode() == ISD::TRUNCATE)
15993 Op = Op.getOperand(0);
15994 // A special case for rdrand/rdseed, where 0 is set if false cond is
15996 if ((Op.getOpcode() != X86ISD::RDRAND &&
15997 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16000 // Quit if false value is not the constant 0 or 1.
16001 bool FValIsFalse = true;
16002 if (FVal && FVal->getZExtValue() != 0) {
16003 if (FVal->getZExtValue() != 1)
16005 // If FVal is 1, opposite cond is needed.
16006 needOppositeCond = !needOppositeCond;
16007 FValIsFalse = false;
16009 // Quit if TVal is not the constant opposite of FVal.
16010 if (FValIsFalse && TVal->getZExtValue() != 1)
16012 if (!FValIsFalse && TVal->getZExtValue() != 0)
16014 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16015 if (needOppositeCond)
16016 CC = X86::GetOppositeBranchCondition(CC);
16017 return SetCC.getOperand(3);
16024 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16025 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16026 TargetLowering::DAGCombinerInfo &DCI,
16027 const X86Subtarget *Subtarget) {
16030 // If the flag operand isn't dead, don't touch this CMOV.
16031 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16034 SDValue FalseOp = N->getOperand(0);
16035 SDValue TrueOp = N->getOperand(1);
16036 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16037 SDValue Cond = N->getOperand(3);
16039 if (CC == X86::COND_E || CC == X86::COND_NE) {
16040 switch (Cond.getOpcode()) {
16044 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16045 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16046 return (CC == X86::COND_E) ? FalseOp : TrueOp;
16052 Flags = checkBoolTestSetCCCombine(Cond, CC);
16053 if (Flags.getNode() &&
16054 // Extra check as FCMOV only supports a subset of X86 cond.
16055 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16056 SDValue Ops[] = { FalseOp, TrueOp,
16057 DAG.getConstant(CC, MVT::i8), Flags };
16058 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16059 Ops, array_lengthof(Ops));
16062 // If this is a select between two integer constants, try to do some
16063 // optimizations. Note that the operands are ordered the opposite of SELECT
16065 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16066 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16067 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16068 // larger than FalseC (the false value).
16069 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16070 CC = X86::GetOppositeBranchCondition(CC);
16071 std::swap(TrueC, FalseC);
16072 std::swap(TrueOp, FalseOp);
16075 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
16076 // This is efficient for any integer data type (including i8/i16) and
16078 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16079 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16080 DAG.getConstant(CC, MVT::i8), Cond);
16082 // Zero extend the condition if needed.
16083 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16085 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16086 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16087 DAG.getConstant(ShAmt, MVT::i8));
16088 if (N->getNumValues() == 2) // Dead flag value?
16089 return DCI.CombineTo(N, Cond, SDValue());
16093 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
16094 // for any integer data type, including i8/i16.
16095 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16096 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16097 DAG.getConstant(CC, MVT::i8), Cond);
16099 // Zero extend the condition if needed.
16100 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16101 FalseC->getValueType(0), Cond);
16102 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16103 SDValue(FalseC, 0));
16105 if (N->getNumValues() == 2) // Dead flag value?
16106 return DCI.CombineTo(N, Cond, SDValue());
16110 // Optimize cases that will turn into an LEA instruction. This requires
16111 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16112 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16113 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16114 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16116 bool isFastMultiplier = false;
16118 switch ((unsigned char)Diff) {
16120 case 1: // result = add base, cond
16121 case 2: // result = lea base( , cond*2)
16122 case 3: // result = lea base(cond, cond*2)
16123 case 4: // result = lea base( , cond*4)
16124 case 5: // result = lea base(cond, cond*4)
16125 case 8: // result = lea base( , cond*8)
16126 case 9: // result = lea base(cond, cond*8)
16127 isFastMultiplier = true;
16132 if (isFastMultiplier) {
16133 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16134 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16135 DAG.getConstant(CC, MVT::i8), Cond);
16136 // Zero extend the condition if needed.
16137 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16139 // Scale the condition by the difference.
16141 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16142 DAG.getConstant(Diff, Cond.getValueType()));
16144 // Add the base if non-zero.
16145 if (FalseC->getAPIntValue() != 0)
16146 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16147 SDValue(FalseC, 0));
16148 if (N->getNumValues() == 2) // Dead flag value?
16149 return DCI.CombineTo(N, Cond, SDValue());
16156 // Handle these cases:
16157 // (select (x != c), e, c) -> select (x != c), e, x),
16158 // (select (x == c), c, e) -> select (x == c), x, e)
16159 // where the c is an integer constant, and the "select" is the combination
16160 // of CMOV and CMP.
16162 // The rationale for this change is that the conditional-move from a constant
16163 // needs two instructions, however, conditional-move from a register needs
16164 // only one instruction.
16166 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16167 // some instruction-combining opportunities. This opt needs to be
16168 // postponed as late as possible.
16170 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16171 // the DCI.xxxx conditions are provided to postpone the optimization as
16172 // late as possible.
16174 ConstantSDNode *CmpAgainst = 0;
16175 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16176 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16177 !isa<ConstantSDNode>(Cond.getOperand(0))) {
16179 if (CC == X86::COND_NE &&
16180 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16181 CC = X86::GetOppositeBranchCondition(CC);
16182 std::swap(TrueOp, FalseOp);
16185 if (CC == X86::COND_E &&
16186 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16187 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16188 DAG.getConstant(CC, MVT::i8), Cond };
16189 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16190 array_lengthof(Ops));
16198 /// PerformMulCombine - Optimize a single multiply with constant into two
16199 /// in order to implement it with two cheaper instructions, e.g.
16200 /// LEA + SHL, LEA + LEA.
16201 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16202 TargetLowering::DAGCombinerInfo &DCI) {
16203 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16206 EVT VT = N->getValueType(0);
16207 if (VT != MVT::i64)
16210 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16213 uint64_t MulAmt = C->getZExtValue();
16214 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16217 uint64_t MulAmt1 = 0;
16218 uint64_t MulAmt2 = 0;
16219 if ((MulAmt % 9) == 0) {
16221 MulAmt2 = MulAmt / 9;
16222 } else if ((MulAmt % 5) == 0) {
16224 MulAmt2 = MulAmt / 5;
16225 } else if ((MulAmt % 3) == 0) {
16227 MulAmt2 = MulAmt / 3;
16230 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16233 if (isPowerOf2_64(MulAmt2) &&
16234 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16235 // If second multiplifer is pow2, issue it first. We want the multiply by
16236 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16238 std::swap(MulAmt1, MulAmt2);
16241 if (isPowerOf2_64(MulAmt1))
16242 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16243 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16245 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16246 DAG.getConstant(MulAmt1, VT));
16248 if (isPowerOf2_64(MulAmt2))
16249 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16250 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16252 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16253 DAG.getConstant(MulAmt2, VT));
16255 // Do not add new nodes to DAG combiner worklist.
16256 DCI.CombineTo(N, NewMul, false);
16261 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16262 SDValue N0 = N->getOperand(0);
16263 SDValue N1 = N->getOperand(1);
16264 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16265 EVT VT = N0.getValueType();
16267 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16268 // since the result of setcc_c is all zero's or all ones.
16269 if (VT.isInteger() && !VT.isVector() &&
16270 N1C && N0.getOpcode() == ISD::AND &&
16271 N0.getOperand(1).getOpcode() == ISD::Constant) {
16272 SDValue N00 = N0.getOperand(0);
16273 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16274 ((N00.getOpcode() == ISD::ANY_EXTEND ||
16275 N00.getOpcode() == ISD::ZERO_EXTEND) &&
16276 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16277 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16278 APInt ShAmt = N1C->getAPIntValue();
16279 Mask = Mask.shl(ShAmt);
16281 return DAG.getNode(ISD::AND, SDLoc(N), VT,
16282 N00, DAG.getConstant(Mask, VT));
16286 // Hardware support for vector shifts is sparse which makes us scalarize the
16287 // vector operations in many cases. Also, on sandybridge ADD is faster than
16289 // (shl V, 1) -> add V,V
16290 if (isSplatVector(N1.getNode())) {
16291 assert(N0.getValueType().isVector() && "Invalid vector shift type");
16292 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16293 // We shift all of the values by one. In many cases we do not have
16294 // hardware support for this operation. This is better expressed as an ADD
16296 if (N1C && (1 == N1C->getZExtValue())) {
16297 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16304 /// PerformShiftCombine - Combine shifts.
16305 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16306 TargetLowering::DAGCombinerInfo &DCI,
16307 const X86Subtarget *Subtarget) {
16308 if (N->getOpcode() == ISD::SHL) {
16309 SDValue V = PerformSHLCombine(N, DAG);
16310 if (V.getNode()) return V;
16316 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
16317 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16318 // and friends. Likewise for OR -> CMPNEQSS.
16319 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16320 TargetLowering::DAGCombinerInfo &DCI,
16321 const X86Subtarget *Subtarget) {
16324 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16325 // we're requiring SSE2 for both.
16326 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16327 SDValue N0 = N->getOperand(0);
16328 SDValue N1 = N->getOperand(1);
16329 SDValue CMP0 = N0->getOperand(1);
16330 SDValue CMP1 = N1->getOperand(1);
16333 // The SETCCs should both refer to the same CMP.
16334 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16337 SDValue CMP00 = CMP0->getOperand(0);
16338 SDValue CMP01 = CMP0->getOperand(1);
16339 EVT VT = CMP00.getValueType();
16341 if (VT == MVT::f32 || VT == MVT::f64) {
16342 bool ExpectingFlags = false;
16343 // Check for any users that want flags:
16344 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16345 !ExpectingFlags && UI != UE; ++UI)
16346 switch (UI->getOpcode()) {
16351 ExpectingFlags = true;
16353 case ISD::CopyToReg:
16354 case ISD::SIGN_EXTEND:
16355 case ISD::ZERO_EXTEND:
16356 case ISD::ANY_EXTEND:
16360 if (!ExpectingFlags) {
16361 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16362 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16364 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16365 X86::CondCode tmp = cc0;
16370 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
16371 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16372 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16373 X86ISD::NodeType NTOperator = is64BitFP ?
16374 X86ISD::FSETCCsd : X86ISD::FSETCCss;
16375 // FIXME: need symbolic constants for these magic numbers.
16376 // See X86ATTInstPrinter.cpp:printSSECC().
16377 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16378 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16379 DAG.getConstant(x86cc, MVT::i8));
16380 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16382 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16383 DAG.getConstant(1, MVT::i32));
16384 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16385 return OneBitOfTruth;
16393 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16394 /// so it can be folded inside ANDNP.
16395 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16396 EVT VT = N->getValueType(0);
16398 // Match direct AllOnes for 128 and 256-bit vectors
16399 if (ISD::isBuildVectorAllOnes(N))
16402 // Look through a bit convert.
16403 if (N->getOpcode() == ISD::BITCAST)
16404 N = N->getOperand(0).getNode();
16406 // Sometimes the operand may come from a insert_subvector building a 256-bit
16408 if (VT.is256BitVector() &&
16409 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16410 SDValue V1 = N->getOperand(0);
16411 SDValue V2 = N->getOperand(1);
16413 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16414 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16415 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16416 ISD::isBuildVectorAllOnes(V2.getNode()))
16423 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16424 // register. In most cases we actually compare or select YMM-sized registers
16425 // and mixing the two types creates horrible code. This method optimizes
16426 // some of the transition sequences.
16427 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16428 TargetLowering::DAGCombinerInfo &DCI,
16429 const X86Subtarget *Subtarget) {
16430 EVT VT = N->getValueType(0);
16431 if (!VT.is256BitVector())
16434 assert((N->getOpcode() == ISD::ANY_EXTEND ||
16435 N->getOpcode() == ISD::ZERO_EXTEND ||
16436 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16438 SDValue Narrow = N->getOperand(0);
16439 EVT NarrowVT = Narrow->getValueType(0);
16440 if (!NarrowVT.is128BitVector())
16443 if (Narrow->getOpcode() != ISD::XOR &&
16444 Narrow->getOpcode() != ISD::AND &&
16445 Narrow->getOpcode() != ISD::OR)
16448 SDValue N0 = Narrow->getOperand(0);
16449 SDValue N1 = Narrow->getOperand(1);
16452 // The Left side has to be a trunc.
16453 if (N0.getOpcode() != ISD::TRUNCATE)
16456 // The type of the truncated inputs.
16457 EVT WideVT = N0->getOperand(0)->getValueType(0);
16461 // The right side has to be a 'trunc' or a constant vector.
16462 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16463 bool RHSConst = (isSplatVector(N1.getNode()) &&
16464 isa<ConstantSDNode>(N1->getOperand(0)));
16465 if (!RHSTrunc && !RHSConst)
16468 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16470 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16473 // Set N0 and N1 to hold the inputs to the new wide operation.
16474 N0 = N0->getOperand(0);
16476 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16477 N1->getOperand(0));
16478 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16479 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16480 } else if (RHSTrunc) {
16481 N1 = N1->getOperand(0);
16484 // Generate the wide operation.
16485 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16486 unsigned Opcode = N->getOpcode();
16488 case ISD::ANY_EXTEND:
16490 case ISD::ZERO_EXTEND: {
16491 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16492 APInt Mask = APInt::getAllOnesValue(InBits);
16493 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16494 return DAG.getNode(ISD::AND, DL, VT,
16495 Op, DAG.getConstant(Mask, VT));
16497 case ISD::SIGN_EXTEND:
16498 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16499 Op, DAG.getValueType(NarrowVT));
16501 llvm_unreachable("Unexpected opcode");
16505 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16506 TargetLowering::DAGCombinerInfo &DCI,
16507 const X86Subtarget *Subtarget) {
16508 EVT VT = N->getValueType(0);
16509 if (DCI.isBeforeLegalizeOps())
16512 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16516 // Create BLSI, and BLSR instructions
16517 // BLSI is X & (-X)
16518 // BLSR is X & (X-1)
16519 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16520 SDValue N0 = N->getOperand(0);
16521 SDValue N1 = N->getOperand(1);
16524 // Check LHS for neg
16525 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16526 isZero(N0.getOperand(0)))
16527 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16529 // Check RHS for neg
16530 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16531 isZero(N1.getOperand(0)))
16532 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16534 // Check LHS for X-1
16535 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16536 isAllOnes(N0.getOperand(1)))
16537 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16539 // Check RHS for X-1
16540 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16541 isAllOnes(N1.getOperand(1)))
16542 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16547 // Want to form ANDNP nodes:
16548 // 1) In the hopes of then easily combining them with OR and AND nodes
16549 // to form PBLEND/PSIGN.
16550 // 2) To match ANDN packed intrinsics
16551 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16554 SDValue N0 = N->getOperand(0);
16555 SDValue N1 = N->getOperand(1);
16558 // Check LHS for vnot
16559 if (N0.getOpcode() == ISD::XOR &&
16560 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16561 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16562 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16564 // Check RHS for vnot
16565 if (N1.getOpcode() == ISD::XOR &&
16566 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16567 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16568 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16573 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16574 TargetLowering::DAGCombinerInfo &DCI,
16575 const X86Subtarget *Subtarget) {
16576 EVT VT = N->getValueType(0);
16577 if (DCI.isBeforeLegalizeOps())
16580 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16584 SDValue N0 = N->getOperand(0);
16585 SDValue N1 = N->getOperand(1);
16587 // look for psign/blend
16588 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16589 if (!Subtarget->hasSSSE3() ||
16590 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16593 // Canonicalize pandn to RHS
16594 if (N0.getOpcode() == X86ISD::ANDNP)
16596 // or (and (m, y), (pandn m, x))
16597 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16598 SDValue Mask = N1.getOperand(0);
16599 SDValue X = N1.getOperand(1);
16601 if (N0.getOperand(0) == Mask)
16602 Y = N0.getOperand(1);
16603 if (N0.getOperand(1) == Mask)
16604 Y = N0.getOperand(0);
16606 // Check to see if the mask appeared in both the AND and ANDNP and
16610 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16611 // Look through mask bitcast.
16612 if (Mask.getOpcode() == ISD::BITCAST)
16613 Mask = Mask.getOperand(0);
16614 if (X.getOpcode() == ISD::BITCAST)
16615 X = X.getOperand(0);
16616 if (Y.getOpcode() == ISD::BITCAST)
16617 Y = Y.getOperand(0);
16619 EVT MaskVT = Mask.getValueType();
16621 // Validate that the Mask operand is a vector sra node.
16622 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16623 // there is no psrai.b
16624 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16625 unsigned SraAmt = ~0;
16626 if (Mask.getOpcode() == ISD::SRA) {
16627 SDValue Amt = Mask.getOperand(1);
16628 if (isSplatVector(Amt.getNode())) {
16629 SDValue SclrAmt = Amt->getOperand(0);
16630 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16631 SraAmt = C->getZExtValue();
16633 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16634 SDValue SraC = Mask.getOperand(1);
16635 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16637 if ((SraAmt + 1) != EltBits)
16642 // Now we know we at least have a plendvb with the mask val. See if
16643 // we can form a psignb/w/d.
16644 // psign = x.type == y.type == mask.type && y = sub(0, x);
16645 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16646 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16647 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16648 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16649 "Unsupported VT for PSIGN");
16650 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16651 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16653 // PBLENDVB only available on SSE 4.1
16654 if (!Subtarget->hasSSE41())
16657 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16659 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16660 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16661 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16662 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16663 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16667 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16670 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16671 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16673 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16675 if (!N0.hasOneUse() || !N1.hasOneUse())
16678 SDValue ShAmt0 = N0.getOperand(1);
16679 if (ShAmt0.getValueType() != MVT::i8)
16681 SDValue ShAmt1 = N1.getOperand(1);
16682 if (ShAmt1.getValueType() != MVT::i8)
16684 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16685 ShAmt0 = ShAmt0.getOperand(0);
16686 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16687 ShAmt1 = ShAmt1.getOperand(0);
16690 unsigned Opc = X86ISD::SHLD;
16691 SDValue Op0 = N0.getOperand(0);
16692 SDValue Op1 = N1.getOperand(0);
16693 if (ShAmt0.getOpcode() == ISD::SUB) {
16694 Opc = X86ISD::SHRD;
16695 std::swap(Op0, Op1);
16696 std::swap(ShAmt0, ShAmt1);
16699 unsigned Bits = VT.getSizeInBits();
16700 if (ShAmt1.getOpcode() == ISD::SUB) {
16701 SDValue Sum = ShAmt1.getOperand(0);
16702 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16703 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16704 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16705 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16706 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16707 return DAG.getNode(Opc, DL, VT,
16709 DAG.getNode(ISD::TRUNCATE, DL,
16712 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16713 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16715 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16716 return DAG.getNode(Opc, DL, VT,
16717 N0.getOperand(0), N1.getOperand(0),
16718 DAG.getNode(ISD::TRUNCATE, DL,
16725 // Generate NEG and CMOV for integer abs.
16726 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16727 EVT VT = N->getValueType(0);
16729 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16730 // 8-bit integer abs to NEG and CMOV.
16731 if (VT.isInteger() && VT.getSizeInBits() == 8)
16734 SDValue N0 = N->getOperand(0);
16735 SDValue N1 = N->getOperand(1);
16738 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16739 // and change it to SUB and CMOV.
16740 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16741 N0.getOpcode() == ISD::ADD &&
16742 N0.getOperand(1) == N1 &&
16743 N1.getOpcode() == ISD::SRA &&
16744 N1.getOperand(0) == N0.getOperand(0))
16745 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16746 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16747 // Generate SUB & CMOV.
16748 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16749 DAG.getConstant(0, VT), N0.getOperand(0));
16751 SDValue Ops[] = { N0.getOperand(0), Neg,
16752 DAG.getConstant(X86::COND_GE, MVT::i8),
16753 SDValue(Neg.getNode(), 1) };
16754 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16755 Ops, array_lengthof(Ops));
16760 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16761 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16762 TargetLowering::DAGCombinerInfo &DCI,
16763 const X86Subtarget *Subtarget) {
16764 EVT VT = N->getValueType(0);
16765 if (DCI.isBeforeLegalizeOps())
16768 if (Subtarget->hasCMov()) {
16769 SDValue RV = performIntegerAbsCombine(N, DAG);
16774 // Try forming BMI if it is available.
16775 if (!Subtarget->hasBMI())
16778 if (VT != MVT::i32 && VT != MVT::i64)
16781 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16783 // Create BLSMSK instructions by finding X ^ (X-1)
16784 SDValue N0 = N->getOperand(0);
16785 SDValue N1 = N->getOperand(1);
16788 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16789 isAllOnes(N0.getOperand(1)))
16790 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16792 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16793 isAllOnes(N1.getOperand(1)))
16794 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16799 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16800 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16801 TargetLowering::DAGCombinerInfo &DCI,
16802 const X86Subtarget *Subtarget) {
16803 LoadSDNode *Ld = cast<LoadSDNode>(N);
16804 EVT RegVT = Ld->getValueType(0);
16805 EVT MemVT = Ld->getMemoryVT();
16807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16808 unsigned RegSz = RegVT.getSizeInBits();
16810 // On Sandybridge unaligned 256bit loads are inefficient.
16811 ISD::LoadExtType Ext = Ld->getExtensionType();
16812 unsigned Alignment = Ld->getAlignment();
16813 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16814 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16815 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16816 unsigned NumElems = RegVT.getVectorNumElements();
16820 SDValue Ptr = Ld->getBasePtr();
16821 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16823 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16825 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16826 Ld->getPointerInfo(), Ld->isVolatile(),
16827 Ld->isNonTemporal(), Ld->isInvariant(),
16829 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16830 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16831 Ld->getPointerInfo(), Ld->isVolatile(),
16832 Ld->isNonTemporal(), Ld->isInvariant(),
16833 std::min(16U, Alignment));
16834 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16836 Load2.getValue(1));
16838 SDValue NewVec = DAG.getUNDEF(RegVT);
16839 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16840 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16841 return DCI.CombineTo(N, NewVec, TF, true);
16844 // If this is a vector EXT Load then attempt to optimize it using a
16845 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16846 // expansion is still better than scalar code.
16847 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16848 // emit a shuffle and a arithmetic shift.
16849 // TODO: It is possible to support ZExt by zeroing the undef values
16850 // during the shuffle phase or after the shuffle.
16851 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16852 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16853 assert(MemVT != RegVT && "Cannot extend to the same type");
16854 assert(MemVT.isVector() && "Must load a vector from memory");
16856 unsigned NumElems = RegVT.getVectorNumElements();
16857 unsigned MemSz = MemVT.getSizeInBits();
16858 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16860 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16863 // All sizes must be a power of two.
16864 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16867 // Attempt to load the original value using scalar loads.
16868 // Find the largest scalar type that divides the total loaded size.
16869 MVT SclrLoadTy = MVT::i8;
16870 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16871 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16872 MVT Tp = (MVT::SimpleValueType)tp;
16873 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16878 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16879 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16881 SclrLoadTy = MVT::f64;
16883 // Calculate the number of scalar loads that we need to perform
16884 // in order to load our vector from memory.
16885 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16886 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16889 unsigned loadRegZize = RegSz;
16890 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16893 // Represent our vector as a sequence of elements which are the
16894 // largest scalar that we can load.
16895 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16896 loadRegZize/SclrLoadTy.getSizeInBits());
16898 // Represent the data using the same element type that is stored in
16899 // memory. In practice, we ''widen'' MemVT.
16901 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16902 loadRegZize/MemVT.getScalarType().getSizeInBits());
16904 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16905 "Invalid vector type");
16907 // We can't shuffle using an illegal type.
16908 if (!TLI.isTypeLegal(WideVecVT))
16911 SmallVector<SDValue, 8> Chains;
16912 SDValue Ptr = Ld->getBasePtr();
16913 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16914 TLI.getPointerTy());
16915 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16917 for (unsigned i = 0; i < NumLoads; ++i) {
16918 // Perform a single load.
16919 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16920 Ptr, Ld->getPointerInfo(),
16921 Ld->isVolatile(), Ld->isNonTemporal(),
16922 Ld->isInvariant(), Ld->getAlignment());
16923 Chains.push_back(ScalarLoad.getValue(1));
16924 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16925 // another round of DAGCombining.
16927 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16929 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16930 ScalarLoad, DAG.getIntPtrConstant(i));
16932 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16935 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16938 // Bitcast the loaded value to a vector of the original element type, in
16939 // the size of the target vector type.
16940 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16941 unsigned SizeRatio = RegSz/MemSz;
16943 if (Ext == ISD::SEXTLOAD) {
16944 // If we have SSE4.1 we can directly emit a VSEXT node.
16945 if (Subtarget->hasSSE41()) {
16946 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16947 return DCI.CombineTo(N, Sext, TF, true);
16950 // Otherwise we'll shuffle the small elements in the high bits of the
16951 // larger type and perform an arithmetic shift. If the shift is not legal
16952 // it's better to scalarize.
16953 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16956 // Redistribute the loaded elements into the different locations.
16957 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16958 for (unsigned i = 0; i != NumElems; ++i)
16959 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16961 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16962 DAG.getUNDEF(WideVecVT),
16965 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16967 // Build the arithmetic shift.
16968 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16969 MemVT.getVectorElementType().getSizeInBits();
16970 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16971 DAG.getConstant(Amt, RegVT));
16973 return DCI.CombineTo(N, Shuff, TF, true);
16976 // Redistribute the loaded elements into the different locations.
16977 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16978 for (unsigned i = 0; i != NumElems; ++i)
16979 ShuffleVec[i*SizeRatio] = i;
16981 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16982 DAG.getUNDEF(WideVecVT),
16985 // Bitcast to the requested type.
16986 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16987 // Replace the original load with the new sequence
16988 // and return the new chain.
16989 return DCI.CombineTo(N, Shuff, TF, true);
16995 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16996 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16997 const X86Subtarget *Subtarget) {
16998 StoreSDNode *St = cast<StoreSDNode>(N);
16999 EVT VT = St->getValue().getValueType();
17000 EVT StVT = St->getMemoryVT();
17002 SDValue StoredVal = St->getOperand(1);
17003 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17005 // If we are saving a concatenation of two XMM registers, perform two stores.
17006 // On Sandy Bridge, 256-bit memory operations are executed by two
17007 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17008 // memory operation.
17009 unsigned Alignment = St->getAlignment();
17010 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17011 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17012 StVT == VT && !IsAligned) {
17013 unsigned NumElems = VT.getVectorNumElements();
17017 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17018 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17020 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17021 SDValue Ptr0 = St->getBasePtr();
17022 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17024 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17025 St->getPointerInfo(), St->isVolatile(),
17026 St->isNonTemporal(), Alignment);
17027 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17028 St->getPointerInfo(), St->isVolatile(),
17029 St->isNonTemporal(),
17030 std::min(16U, Alignment));
17031 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17034 // Optimize trunc store (of multiple scalars) to shuffle and store.
17035 // First, pack all of the elements in one place. Next, store to memory
17036 // in fewer chunks.
17037 if (St->isTruncatingStore() && VT.isVector()) {
17038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17039 unsigned NumElems = VT.getVectorNumElements();
17040 assert(StVT != VT && "Cannot truncate to the same type");
17041 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17042 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17044 // From, To sizes and ElemCount must be pow of two
17045 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17046 // We are going to use the original vector elt for storing.
17047 // Accumulated smaller vector elements must be a multiple of the store size.
17048 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17050 unsigned SizeRatio = FromSz / ToSz;
17052 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17054 // Create a type on which we perform the shuffle
17055 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17056 StVT.getScalarType(), NumElems*SizeRatio);
17058 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17060 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17061 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17062 for (unsigned i = 0; i != NumElems; ++i)
17063 ShuffleVec[i] = i * SizeRatio;
17065 // Can't shuffle using an illegal type.
17066 if (!TLI.isTypeLegal(WideVecVT))
17069 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17070 DAG.getUNDEF(WideVecVT),
17072 // At this point all of the data is stored at the bottom of the
17073 // register. We now need to save it to mem.
17075 // Find the largest store unit
17076 MVT StoreType = MVT::i8;
17077 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17078 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17079 MVT Tp = (MVT::SimpleValueType)tp;
17080 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17084 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17085 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17086 (64 <= NumElems * ToSz))
17087 StoreType = MVT::f64;
17089 // Bitcast the original vector into a vector of store-size units
17090 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17091 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17092 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17093 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17094 SmallVector<SDValue, 8> Chains;
17095 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17096 TLI.getPointerTy());
17097 SDValue Ptr = St->getBasePtr();
17099 // Perform one or more big stores into memory.
17100 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17101 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17102 StoreType, ShuffWide,
17103 DAG.getIntPtrConstant(i));
17104 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17105 St->getPointerInfo(), St->isVolatile(),
17106 St->isNonTemporal(), St->getAlignment());
17107 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17108 Chains.push_back(Ch);
17111 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17115 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
17116 // the FP state in cases where an emms may be missing.
17117 // A preferable solution to the general problem is to figure out the right
17118 // places to insert EMMS. This qualifies as a quick hack.
17120 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17121 if (VT.getSizeInBits() != 64)
17124 const Function *F = DAG.getMachineFunction().getFunction();
17125 bool NoImplicitFloatOps = F->getAttributes().
17126 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17127 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17128 && Subtarget->hasSSE2();
17129 if ((VT.isVector() ||
17130 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17131 isa<LoadSDNode>(St->getValue()) &&
17132 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17133 St->getChain().hasOneUse() && !St->isVolatile()) {
17134 SDNode* LdVal = St->getValue().getNode();
17135 LoadSDNode *Ld = 0;
17136 int TokenFactorIndex = -1;
17137 SmallVector<SDValue, 8> Ops;
17138 SDNode* ChainVal = St->getChain().getNode();
17139 // Must be a store of a load. We currently handle two cases: the load
17140 // is a direct child, and it's under an intervening TokenFactor. It is
17141 // possible to dig deeper under nested TokenFactors.
17142 if (ChainVal == LdVal)
17143 Ld = cast<LoadSDNode>(St->getChain());
17144 else if (St->getValue().hasOneUse() &&
17145 ChainVal->getOpcode() == ISD::TokenFactor) {
17146 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17147 if (ChainVal->getOperand(i).getNode() == LdVal) {
17148 TokenFactorIndex = i;
17149 Ld = cast<LoadSDNode>(St->getValue());
17151 Ops.push_back(ChainVal->getOperand(i));
17155 if (!Ld || !ISD::isNormalLoad(Ld))
17158 // If this is not the MMX case, i.e. we are just turning i64 load/store
17159 // into f64 load/store, avoid the transformation if there are multiple
17160 // uses of the loaded value.
17161 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17166 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17167 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17169 if (Subtarget->is64Bit() || F64IsLegal) {
17170 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17171 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17172 Ld->getPointerInfo(), Ld->isVolatile(),
17173 Ld->isNonTemporal(), Ld->isInvariant(),
17174 Ld->getAlignment());
17175 SDValue NewChain = NewLd.getValue(1);
17176 if (TokenFactorIndex != -1) {
17177 Ops.push_back(NewChain);
17178 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17181 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17182 St->getPointerInfo(),
17183 St->isVolatile(), St->isNonTemporal(),
17184 St->getAlignment());
17187 // Otherwise, lower to two pairs of 32-bit loads / stores.
17188 SDValue LoAddr = Ld->getBasePtr();
17189 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17190 DAG.getConstant(4, MVT::i32));
17192 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17193 Ld->getPointerInfo(),
17194 Ld->isVolatile(), Ld->isNonTemporal(),
17195 Ld->isInvariant(), Ld->getAlignment());
17196 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17197 Ld->getPointerInfo().getWithOffset(4),
17198 Ld->isVolatile(), Ld->isNonTemporal(),
17200 MinAlign(Ld->getAlignment(), 4));
17202 SDValue NewChain = LoLd.getValue(1);
17203 if (TokenFactorIndex != -1) {
17204 Ops.push_back(LoLd);
17205 Ops.push_back(HiLd);
17206 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17210 LoAddr = St->getBasePtr();
17211 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17212 DAG.getConstant(4, MVT::i32));
17214 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17215 St->getPointerInfo(),
17216 St->isVolatile(), St->isNonTemporal(),
17217 St->getAlignment());
17218 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17219 St->getPointerInfo().getWithOffset(4),
17221 St->isNonTemporal(),
17222 MinAlign(St->getAlignment(), 4));
17223 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17228 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17229 /// and return the operands for the horizontal operation in LHS and RHS. A
17230 /// horizontal operation performs the binary operation on successive elements
17231 /// of its first operand, then on successive elements of its second operand,
17232 /// returning the resulting values in a vector. For example, if
17233 /// A = < float a0, float a1, float a2, float a3 >
17235 /// B = < float b0, float b1, float b2, float b3 >
17236 /// then the result of doing a horizontal operation on A and B is
17237 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17238 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17239 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17240 /// set to A, RHS to B, and the routine returns 'true'.
17241 /// Note that the binary operation should have the property that if one of the
17242 /// operands is UNDEF then the result is UNDEF.
17243 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17244 // Look for the following pattern: if
17245 // A = < float a0, float a1, float a2, float a3 >
17246 // B = < float b0, float b1, float b2, float b3 >
17248 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17249 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17250 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17251 // which is A horizontal-op B.
17253 // At least one of the operands should be a vector shuffle.
17254 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17255 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17258 EVT VT = LHS.getValueType();
17260 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17261 "Unsupported vector type for horizontal add/sub");
17263 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17264 // operate independently on 128-bit lanes.
17265 unsigned NumElts = VT.getVectorNumElements();
17266 unsigned NumLanes = VT.getSizeInBits()/128;
17267 unsigned NumLaneElts = NumElts / NumLanes;
17268 assert((NumLaneElts % 2 == 0) &&
17269 "Vector type should have an even number of elements in each lane");
17270 unsigned HalfLaneElts = NumLaneElts/2;
17272 // View LHS in the form
17273 // LHS = VECTOR_SHUFFLE A, B, LMask
17274 // If LHS is not a shuffle then pretend it is the shuffle
17275 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17276 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17279 SmallVector<int, 16> LMask(NumElts);
17280 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17281 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17282 A = LHS.getOperand(0);
17283 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17284 B = LHS.getOperand(1);
17285 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17286 std::copy(Mask.begin(), Mask.end(), LMask.begin());
17288 if (LHS.getOpcode() != ISD::UNDEF)
17290 for (unsigned i = 0; i != NumElts; ++i)
17294 // Likewise, view RHS in the form
17295 // RHS = VECTOR_SHUFFLE C, D, RMask
17297 SmallVector<int, 16> RMask(NumElts);
17298 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17299 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17300 C = RHS.getOperand(0);
17301 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17302 D = RHS.getOperand(1);
17303 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17304 std::copy(Mask.begin(), Mask.end(), RMask.begin());
17306 if (RHS.getOpcode() != ISD::UNDEF)
17308 for (unsigned i = 0; i != NumElts; ++i)
17312 // Check that the shuffles are both shuffling the same vectors.
17313 if (!(A == C && B == D) && !(A == D && B == C))
17316 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17317 if (!A.getNode() && !B.getNode())
17320 // If A and B occur in reverse order in RHS, then "swap" them (which means
17321 // rewriting the mask).
17323 CommuteVectorShuffleMask(RMask, NumElts);
17325 // At this point LHS and RHS are equivalent to
17326 // LHS = VECTOR_SHUFFLE A, B, LMask
17327 // RHS = VECTOR_SHUFFLE A, B, RMask
17328 // Check that the masks correspond to performing a horizontal operation.
17329 for (unsigned i = 0; i != NumElts; ++i) {
17330 int LIdx = LMask[i], RIdx = RMask[i];
17332 // Ignore any UNDEF components.
17333 if (LIdx < 0 || RIdx < 0 ||
17334 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17335 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17338 // Check that successive elements are being operated on. If not, this is
17339 // not a horizontal operation.
17340 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17341 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17342 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17343 if (!(LIdx == Index && RIdx == Index + 1) &&
17344 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17348 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17349 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17353 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17354 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17355 const X86Subtarget *Subtarget) {
17356 EVT VT = N->getValueType(0);
17357 SDValue LHS = N->getOperand(0);
17358 SDValue RHS = N->getOperand(1);
17360 // Try to synthesize horizontal adds from adds of shuffles.
17361 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17362 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17363 isHorizontalBinOp(LHS, RHS, true))
17364 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17368 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17369 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17370 const X86Subtarget *Subtarget) {
17371 EVT VT = N->getValueType(0);
17372 SDValue LHS = N->getOperand(0);
17373 SDValue RHS = N->getOperand(1);
17375 // Try to synthesize horizontal subs from subs of shuffles.
17376 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17377 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17378 isHorizontalBinOp(LHS, RHS, false))
17379 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17383 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17384 /// X86ISD::FXOR nodes.
17385 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17386 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17387 // F[X]OR(0.0, x) -> x
17388 // F[X]OR(x, 0.0) -> x
17389 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17390 if (C->getValueAPF().isPosZero())
17391 return N->getOperand(1);
17392 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17393 if (C->getValueAPF().isPosZero())
17394 return N->getOperand(0);
17398 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17399 /// X86ISD::FMAX nodes.
17400 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17401 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17403 // Only perform optimizations if UnsafeMath is used.
17404 if (!DAG.getTarget().Options.UnsafeFPMath)
17407 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17408 // into FMINC and FMAXC, which are Commutative operations.
17409 unsigned NewOp = 0;
17410 switch (N->getOpcode()) {
17411 default: llvm_unreachable("unknown opcode");
17412 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
17413 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
17416 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17417 N->getOperand(0), N->getOperand(1));
17420 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17421 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17422 // FAND(0.0, x) -> 0.0
17423 // FAND(x, 0.0) -> 0.0
17424 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17425 if (C->getValueAPF().isPosZero())
17426 return N->getOperand(0);
17427 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17428 if (C->getValueAPF().isPosZero())
17429 return N->getOperand(1);
17433 static SDValue PerformBTCombine(SDNode *N,
17435 TargetLowering::DAGCombinerInfo &DCI) {
17436 // BT ignores high bits in the bit index operand.
17437 SDValue Op1 = N->getOperand(1);
17438 if (Op1.hasOneUse()) {
17439 unsigned BitWidth = Op1.getValueSizeInBits();
17440 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17441 APInt KnownZero, KnownOne;
17442 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17443 !DCI.isBeforeLegalizeOps());
17444 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17445 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17446 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17447 DCI.CommitTargetLoweringOpt(TLO);
17452 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17453 SDValue Op = N->getOperand(0);
17454 if (Op.getOpcode() == ISD::BITCAST)
17455 Op = Op.getOperand(0);
17456 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17457 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17458 VT.getVectorElementType().getSizeInBits() ==
17459 OpVT.getVectorElementType().getSizeInBits()) {
17460 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17465 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17466 const X86Subtarget *Subtarget) {
17467 EVT VT = N->getValueType(0);
17468 if (!VT.isVector())
17471 SDValue N0 = N->getOperand(0);
17472 SDValue N1 = N->getOperand(1);
17473 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17476 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17477 // both SSE and AVX2 since there is no sign-extended shift right
17478 // operation on a vector with 64-bit elements.
17479 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17480 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17481 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17482 N0.getOpcode() == ISD::SIGN_EXTEND)) {
17483 SDValue N00 = N0.getOperand(0);
17485 // EXTLOAD has a better solution on AVX2,
17486 // it may be replaced with X86ISD::VSEXT node.
17487 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17488 if (!ISD::isNormalLoad(N00.getNode()))
17491 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17492 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17494 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17500 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17501 TargetLowering::DAGCombinerInfo &DCI,
17502 const X86Subtarget *Subtarget) {
17503 if (!DCI.isBeforeLegalizeOps())
17506 if (!Subtarget->hasFp256())
17509 EVT VT = N->getValueType(0);
17510 if (VT.isVector() && VT.getSizeInBits() == 256) {
17511 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17519 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17520 const X86Subtarget* Subtarget) {
17522 EVT VT = N->getValueType(0);
17524 // Let legalize expand this if it isn't a legal type yet.
17525 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17528 EVT ScalarVT = VT.getScalarType();
17529 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17530 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17533 SDValue A = N->getOperand(0);
17534 SDValue B = N->getOperand(1);
17535 SDValue C = N->getOperand(2);
17537 bool NegA = (A.getOpcode() == ISD::FNEG);
17538 bool NegB = (B.getOpcode() == ISD::FNEG);
17539 bool NegC = (C.getOpcode() == ISD::FNEG);
17541 // Negative multiplication when NegA xor NegB
17542 bool NegMul = (NegA != NegB);
17544 A = A.getOperand(0);
17546 B = B.getOperand(0);
17548 C = C.getOperand(0);
17552 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17554 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17556 return DAG.getNode(Opcode, dl, VT, A, B, C);
17559 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17560 TargetLowering::DAGCombinerInfo &DCI,
17561 const X86Subtarget *Subtarget) {
17562 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
17563 // (and (i32 x86isd::setcc_carry), 1)
17564 // This eliminates the zext. This transformation is necessary because
17565 // ISD::SETCC is always legalized to i8.
17567 SDValue N0 = N->getOperand(0);
17568 EVT VT = N->getValueType(0);
17570 if (N0.getOpcode() == ISD::AND &&
17572 N0.getOperand(0).hasOneUse()) {
17573 SDValue N00 = N0.getOperand(0);
17574 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17575 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17576 if (!C || C->getZExtValue() != 1)
17578 return DAG.getNode(ISD::AND, dl, VT,
17579 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17580 N00.getOperand(0), N00.getOperand(1)),
17581 DAG.getConstant(1, VT));
17585 if (VT.is256BitVector()) {
17586 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17594 // Optimize x == -y --> x+y == 0
17595 // x != -y --> x+y != 0
17596 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17597 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17598 SDValue LHS = N->getOperand(0);
17599 SDValue RHS = N->getOperand(1);
17601 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17602 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17603 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17604 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17605 LHS.getValueType(), RHS, LHS.getOperand(1));
17606 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17607 addV, DAG.getConstant(0, addV.getValueType()), CC);
17609 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17610 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17611 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17612 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17613 RHS.getValueType(), LHS, RHS.getOperand(1));
17614 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17615 addV, DAG.getConstant(0, addV.getValueType()), CC);
17620 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17621 // as "sbb reg,reg", since it can be extended without zext and produces
17622 // an all-ones bit which is more useful than 0/1 in some cases.
17623 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17624 return DAG.getNode(ISD::AND, DL, MVT::i8,
17625 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17626 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17627 DAG.getConstant(1, MVT::i8));
17630 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17631 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17632 TargetLowering::DAGCombinerInfo &DCI,
17633 const X86Subtarget *Subtarget) {
17635 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17636 SDValue EFLAGS = N->getOperand(1);
17638 if (CC == X86::COND_A) {
17639 // Try to convert COND_A into COND_B in an attempt to facilitate
17640 // materializing "setb reg".
17642 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17643 // cannot take an immediate as its first operand.
17645 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17646 EFLAGS.getValueType().isInteger() &&
17647 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17648 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17649 EFLAGS.getNode()->getVTList(),
17650 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17651 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17652 return MaterializeSETB(DL, NewEFLAGS, DAG);
17656 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17657 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17659 if (CC == X86::COND_B)
17660 return MaterializeSETB(DL, EFLAGS, DAG);
17664 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17665 if (Flags.getNode()) {
17666 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17667 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17673 // Optimize branch condition evaluation.
17675 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17676 TargetLowering::DAGCombinerInfo &DCI,
17677 const X86Subtarget *Subtarget) {
17679 SDValue Chain = N->getOperand(0);
17680 SDValue Dest = N->getOperand(1);
17681 SDValue EFLAGS = N->getOperand(3);
17682 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17686 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17687 if (Flags.getNode()) {
17688 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17689 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17696 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17697 const X86TargetLowering *XTLI) {
17698 SDValue Op0 = N->getOperand(0);
17699 EVT InVT = Op0->getValueType(0);
17701 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17702 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17704 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17705 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17706 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17709 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17710 // a 32-bit target where SSE doesn't support i64->FP operations.
17711 if (Op0.getOpcode() == ISD::LOAD) {
17712 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17713 EVT VT = Ld->getValueType(0);
17714 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17715 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17716 !XTLI->getSubtarget()->is64Bit() &&
17717 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17718 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17719 Ld->getChain(), Op0, DAG);
17720 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17727 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17728 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17729 X86TargetLowering::DAGCombinerInfo &DCI) {
17730 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17731 // the result is either zero or one (depending on the input carry bit).
17732 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17733 if (X86::isZeroNode(N->getOperand(0)) &&
17734 X86::isZeroNode(N->getOperand(1)) &&
17735 // We don't have a good way to replace an EFLAGS use, so only do this when
17737 SDValue(N, 1).use_empty()) {
17739 EVT VT = N->getValueType(0);
17740 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17741 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17742 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17743 DAG.getConstant(X86::COND_B,MVT::i8),
17745 DAG.getConstant(1, VT));
17746 return DCI.CombineTo(N, Res1, CarryOut);
17752 // fold (add Y, (sete X, 0)) -> adc 0, Y
17753 // (add Y, (setne X, 0)) -> sbb -1, Y
17754 // (sub (sete X, 0), Y) -> sbb 0, Y
17755 // (sub (setne X, 0), Y) -> adc -1, Y
17756 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17759 // Look through ZExts.
17760 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17761 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17764 SDValue SetCC = Ext.getOperand(0);
17765 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17768 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17769 if (CC != X86::COND_E && CC != X86::COND_NE)
17772 SDValue Cmp = SetCC.getOperand(1);
17773 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17774 !X86::isZeroNode(Cmp.getOperand(1)) ||
17775 !Cmp.getOperand(0).getValueType().isInteger())
17778 SDValue CmpOp0 = Cmp.getOperand(0);
17779 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17780 DAG.getConstant(1, CmpOp0.getValueType()));
17782 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17783 if (CC == X86::COND_NE)
17784 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17785 DL, OtherVal.getValueType(), OtherVal,
17786 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17787 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17788 DL, OtherVal.getValueType(), OtherVal,
17789 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17792 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17793 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17794 const X86Subtarget *Subtarget) {
17795 EVT VT = N->getValueType(0);
17796 SDValue Op0 = N->getOperand(0);
17797 SDValue Op1 = N->getOperand(1);
17799 // Try to synthesize horizontal adds from adds of shuffles.
17800 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17801 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17802 isHorizontalBinOp(Op0, Op1, true))
17803 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
17805 return OptimizeConditionalInDecrement(N, DAG);
17808 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17809 const X86Subtarget *Subtarget) {
17810 SDValue Op0 = N->getOperand(0);
17811 SDValue Op1 = N->getOperand(1);
17813 // X86 can't encode an immediate LHS of a sub. See if we can push the
17814 // negation into a preceding instruction.
17815 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17816 // If the RHS of the sub is a XOR with one use and a constant, invert the
17817 // immediate. Then add one to the LHS of the sub so we can turn
17818 // X-Y -> X+~Y+1, saving one register.
17819 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17820 isa<ConstantSDNode>(Op1.getOperand(1))) {
17821 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17822 EVT VT = Op0.getValueType();
17823 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
17825 DAG.getConstant(~XorC, VT));
17826 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
17827 DAG.getConstant(C->getAPIntValue()+1, VT));
17831 // Try to synthesize horizontal adds from adds of shuffles.
17832 EVT VT = N->getValueType(0);
17833 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17834 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17835 isHorizontalBinOp(Op0, Op1, true))
17836 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
17838 return OptimizeConditionalInDecrement(N, DAG);
17841 /// performVZEXTCombine - Performs build vector combines
17842 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17843 TargetLowering::DAGCombinerInfo &DCI,
17844 const X86Subtarget *Subtarget) {
17845 // (vzext (bitcast (vzext (x)) -> (vzext x)
17846 SDValue In = N->getOperand(0);
17847 while (In.getOpcode() == ISD::BITCAST)
17848 In = In.getOperand(0);
17850 if (In.getOpcode() != X86ISD::VZEXT)
17853 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
17857 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17858 DAGCombinerInfo &DCI) const {
17859 SelectionDAG &DAG = DCI.DAG;
17860 switch (N->getOpcode()) {
17862 case ISD::EXTRACT_VECTOR_ELT:
17863 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17865 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17866 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17867 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17868 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17869 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17870 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17873 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17874 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17875 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17876 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17877 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17878 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17879 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17880 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17881 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17883 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17885 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17886 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17887 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17888 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17889 case ISD::ANY_EXTEND:
17890 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17891 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17892 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17893 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17894 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17895 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17896 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17897 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17898 case X86ISD::SHUFP: // Handle all target specific shuffles
17899 case X86ISD::PALIGNR:
17900 case X86ISD::UNPCKH:
17901 case X86ISD::UNPCKL:
17902 case X86ISD::MOVHLPS:
17903 case X86ISD::MOVLHPS:
17904 case X86ISD::PSHUFD:
17905 case X86ISD::PSHUFHW:
17906 case X86ISD::PSHUFLW:
17907 case X86ISD::MOVSS:
17908 case X86ISD::MOVSD:
17909 case X86ISD::VPERMILP:
17910 case X86ISD::VPERM2X128:
17911 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17912 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17918 /// isTypeDesirableForOp - Return true if the target has native support for
17919 /// the specified value type and it is 'desirable' to use the type for the
17920 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17921 /// instruction encodings are longer and some i16 instructions are slow.
17922 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17923 if (!isTypeLegal(VT))
17925 if (VT != MVT::i16)
17932 case ISD::SIGN_EXTEND:
17933 case ISD::ZERO_EXTEND:
17934 case ISD::ANY_EXTEND:
17947 /// IsDesirableToPromoteOp - This method query the target whether it is
17948 /// beneficial for dag combiner to promote the specified node. If true, it
17949 /// should return the desired promotion type by reference.
17950 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17951 EVT VT = Op.getValueType();
17952 if (VT != MVT::i16)
17955 bool Promote = false;
17956 bool Commute = false;
17957 switch (Op.getOpcode()) {
17960 LoadSDNode *LD = cast<LoadSDNode>(Op);
17961 // If the non-extending load has a single use and it's not live out, then it
17962 // might be folded.
17963 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17964 Op.hasOneUse()*/) {
17965 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17966 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17967 // The only case where we'd want to promote LOAD (rather then it being
17968 // promoted as an operand is when it's only use is liveout.
17969 if (UI->getOpcode() != ISD::CopyToReg)
17976 case ISD::SIGN_EXTEND:
17977 case ISD::ZERO_EXTEND:
17978 case ISD::ANY_EXTEND:
17983 SDValue N0 = Op.getOperand(0);
17984 // Look out for (store (shl (load), x)).
17985 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17998 SDValue N0 = Op.getOperand(0);
17999 SDValue N1 = Op.getOperand(1);
18000 if (!Commute && MayFoldLoad(N1))
18002 // Avoid disabling potential load folding opportunities.
18003 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18005 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18015 //===----------------------------------------------------------------------===//
18016 // X86 Inline Assembly Support
18017 //===----------------------------------------------------------------------===//
18020 // Helper to match a string separated by whitespace.
18021 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18022 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18024 for (unsigned i = 0, e = args.size(); i != e; ++i) {
18025 StringRef piece(*args[i]);
18026 if (!s.startswith(piece)) // Check if the piece matches.
18029 s = s.substr(piece.size());
18030 StringRef::size_type pos = s.find_first_not_of(" \t");
18031 if (pos == 0) // We matched a prefix.
18039 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18042 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18043 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18045 std::string AsmStr = IA->getAsmString();
18047 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18048 if (!Ty || Ty->getBitWidth() % 16 != 0)
18051 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18052 SmallVector<StringRef, 4> AsmPieces;
18053 SplitString(AsmStr, AsmPieces, ";\n");
18055 switch (AsmPieces.size()) {
18056 default: return false;
18058 // FIXME: this should verify that we are targeting a 486 or better. If not,
18059 // we will turn this bswap into something that will be lowered to logical
18060 // ops instead of emitting the bswap asm. For now, we don't support 486 or
18061 // lower so don't worry about this.
18063 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18064 matchAsm(AsmPieces[0], "bswapl", "$0") ||
18065 matchAsm(AsmPieces[0], "bswapq", "$0") ||
18066 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18067 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18068 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18069 // No need to check constraints, nothing other than the equivalent of
18070 // "=r,0" would be valid here.
18071 return IntrinsicLowering::LowerToByteSwap(CI);
18074 // rorw $$8, ${0:w} --> llvm.bswap.i16
18075 if (CI->getType()->isIntegerTy(16) &&
18076 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18077 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18078 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18080 const std::string &ConstraintsStr = IA->getConstraintString();
18081 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18082 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18083 if (AsmPieces.size() == 4 &&
18084 AsmPieces[0] == "~{cc}" &&
18085 AsmPieces[1] == "~{dirflag}" &&
18086 AsmPieces[2] == "~{flags}" &&
18087 AsmPieces[3] == "~{fpsr}")
18088 return IntrinsicLowering::LowerToByteSwap(CI);
18092 if (CI->getType()->isIntegerTy(32) &&
18093 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18094 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18095 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18096 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18098 const std::string &ConstraintsStr = IA->getConstraintString();
18099 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18100 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18101 if (AsmPieces.size() == 4 &&
18102 AsmPieces[0] == "~{cc}" &&
18103 AsmPieces[1] == "~{dirflag}" &&
18104 AsmPieces[2] == "~{flags}" &&
18105 AsmPieces[3] == "~{fpsr}")
18106 return IntrinsicLowering::LowerToByteSwap(CI);
18109 if (CI->getType()->isIntegerTy(64)) {
18110 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18111 if (Constraints.size() >= 2 &&
18112 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18113 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18114 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
18115 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18116 matchAsm(AsmPieces[1], "bswap", "%edx") &&
18117 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18118 return IntrinsicLowering::LowerToByteSwap(CI);
18126 /// getConstraintType - Given a constraint letter, return the type of
18127 /// constraint it is for this target.
18128 X86TargetLowering::ConstraintType
18129 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18130 if (Constraint.size() == 1) {
18131 switch (Constraint[0]) {
18142 return C_RegisterClass;
18166 return TargetLowering::getConstraintType(Constraint);
18169 /// Examine constraint type and operand type and determine a weight value.
18170 /// This object must already have been set up with the operand type
18171 /// and the current alternative constraint selected.
18172 TargetLowering::ConstraintWeight
18173 X86TargetLowering::getSingleConstraintMatchWeight(
18174 AsmOperandInfo &info, const char *constraint) const {
18175 ConstraintWeight weight = CW_Invalid;
18176 Value *CallOperandVal = info.CallOperandVal;
18177 // If we don't have a value, we can't do a match,
18178 // but allow it at the lowest weight.
18179 if (CallOperandVal == NULL)
18181 Type *type = CallOperandVal->getType();
18182 // Look at the constraint type.
18183 switch (*constraint) {
18185 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18196 if (CallOperandVal->getType()->isIntegerTy())
18197 weight = CW_SpecificReg;
18202 if (type->isFloatingPointTy())
18203 weight = CW_SpecificReg;
18206 if (type->isX86_MMXTy() && Subtarget->hasMMX())
18207 weight = CW_SpecificReg;
18211 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18212 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18213 weight = CW_Register;
18216 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18217 if (C->getZExtValue() <= 31)
18218 weight = CW_Constant;
18222 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18223 if (C->getZExtValue() <= 63)
18224 weight = CW_Constant;
18228 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18229 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18230 weight = CW_Constant;
18234 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18235 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18236 weight = CW_Constant;
18240 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18241 if (C->getZExtValue() <= 3)
18242 weight = CW_Constant;
18246 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18247 if (C->getZExtValue() <= 0xff)
18248 weight = CW_Constant;
18253 if (dyn_cast<ConstantFP>(CallOperandVal)) {
18254 weight = CW_Constant;
18258 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18259 if ((C->getSExtValue() >= -0x80000000LL) &&
18260 (C->getSExtValue() <= 0x7fffffffLL))
18261 weight = CW_Constant;
18265 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18266 if (C->getZExtValue() <= 0xffffffff)
18267 weight = CW_Constant;
18274 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18275 /// with another that has more specific requirements based on the type of the
18276 /// corresponding operand.
18277 const char *X86TargetLowering::
18278 LowerXConstraint(EVT ConstraintVT) const {
18279 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18280 // 'f' like normal targets.
18281 if (ConstraintVT.isFloatingPoint()) {
18282 if (Subtarget->hasSSE2())
18284 if (Subtarget->hasSSE1())
18288 return TargetLowering::LowerXConstraint(ConstraintVT);
18291 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18292 /// vector. If it is invalid, don't add anything to Ops.
18293 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18294 std::string &Constraint,
18295 std::vector<SDValue>&Ops,
18296 SelectionDAG &DAG) const {
18297 SDValue Result(0, 0);
18299 // Only support length 1 constraints for now.
18300 if (Constraint.length() > 1) return;
18302 char ConstraintLetter = Constraint[0];
18303 switch (ConstraintLetter) {
18306 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18307 if (C->getZExtValue() <= 31) {
18308 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18314 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18315 if (C->getZExtValue() <= 63) {
18316 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18322 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18323 if (isInt<8>(C->getSExtValue())) {
18324 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18331 if (C->getZExtValue() <= 255) {
18332 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18338 // 32-bit signed value
18339 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18340 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18341 C->getSExtValue())) {
18342 // Widen to 64 bits here to get it sign extended.
18343 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18346 // FIXME gcc accepts some relocatable values here too, but only in certain
18347 // memory models; it's complicated.
18352 // 32-bit unsigned value
18353 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18354 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18355 C->getZExtValue())) {
18356 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18360 // FIXME gcc accepts some relocatable values here too, but only in certain
18361 // memory models; it's complicated.
18365 // Literal immediates are always ok.
18366 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18367 // Widen to 64 bits here to get it sign extended.
18368 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18372 // In any sort of PIC mode addresses need to be computed at runtime by
18373 // adding in a register or some sort of table lookup. These can't
18374 // be used as immediates.
18375 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18378 // If we are in non-pic codegen mode, we allow the address of a global (with
18379 // an optional displacement) to be used with 'i'.
18380 GlobalAddressSDNode *GA = 0;
18381 int64_t Offset = 0;
18383 // Match either (GA), (GA+C), (GA+C1+C2), etc.
18385 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18386 Offset += GA->getOffset();
18388 } else if (Op.getOpcode() == ISD::ADD) {
18389 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18390 Offset += C->getZExtValue();
18391 Op = Op.getOperand(0);
18394 } else if (Op.getOpcode() == ISD::SUB) {
18395 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18396 Offset += -C->getZExtValue();
18397 Op = Op.getOperand(0);
18402 // Otherwise, this isn't something we can handle, reject it.
18406 const GlobalValue *GV = GA->getGlobal();
18407 // If we require an extra load to get this address, as in PIC mode, we
18408 // can't accept it.
18409 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18410 getTargetMachine())))
18413 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18414 GA->getValueType(0), Offset);
18419 if (Result.getNode()) {
18420 Ops.push_back(Result);
18423 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18426 std::pair<unsigned, const TargetRegisterClass*>
18427 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18429 // First, see if this is a constraint that directly corresponds to an LLVM
18431 if (Constraint.size() == 1) {
18432 // GCC Constraint Letters
18433 switch (Constraint[0]) {
18435 // TODO: Slight differences here in allocation order and leaving
18436 // RIP in the class. Do they matter any more here than they do
18437 // in the normal allocation?
18438 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18439 if (Subtarget->is64Bit()) {
18440 if (VT == MVT::i32 || VT == MVT::f32)
18441 return std::make_pair(0U, &X86::GR32RegClass);
18442 if (VT == MVT::i16)
18443 return std::make_pair(0U, &X86::GR16RegClass);
18444 if (VT == MVT::i8 || VT == MVT::i1)
18445 return std::make_pair(0U, &X86::GR8RegClass);
18446 if (VT == MVT::i64 || VT == MVT::f64)
18447 return std::make_pair(0U, &X86::GR64RegClass);
18450 // 32-bit fallthrough
18451 case 'Q': // Q_REGS
18452 if (VT == MVT::i32 || VT == MVT::f32)
18453 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18454 if (VT == MVT::i16)
18455 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18456 if (VT == MVT::i8 || VT == MVT::i1)
18457 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18458 if (VT == MVT::i64)
18459 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18461 case 'r': // GENERAL_REGS
18462 case 'l': // INDEX_REGS
18463 if (VT == MVT::i8 || VT == MVT::i1)
18464 return std::make_pair(0U, &X86::GR8RegClass);
18465 if (VT == MVT::i16)
18466 return std::make_pair(0U, &X86::GR16RegClass);
18467 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18468 return std::make_pair(0U, &X86::GR32RegClass);
18469 return std::make_pair(0U, &X86::GR64RegClass);
18470 case 'R': // LEGACY_REGS
18471 if (VT == MVT::i8 || VT == MVT::i1)
18472 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18473 if (VT == MVT::i16)
18474 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18475 if (VT == MVT::i32 || !Subtarget->is64Bit())
18476 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18477 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18478 case 'f': // FP Stack registers.
18479 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18480 // value to the correct fpstack register class.
18481 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18482 return std::make_pair(0U, &X86::RFP32RegClass);
18483 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18484 return std::make_pair(0U, &X86::RFP64RegClass);
18485 return std::make_pair(0U, &X86::RFP80RegClass);
18486 case 'y': // MMX_REGS if MMX allowed.
18487 if (!Subtarget->hasMMX()) break;
18488 return std::make_pair(0U, &X86::VR64RegClass);
18489 case 'Y': // SSE_REGS if SSE2 allowed
18490 if (!Subtarget->hasSSE2()) break;
18492 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18493 if (!Subtarget->hasSSE1()) break;
18495 switch (VT.SimpleTy) {
18497 // Scalar SSE types.
18500 return std::make_pair(0U, &X86::FR32RegClass);
18503 return std::make_pair(0U, &X86::FR64RegClass);
18511 return std::make_pair(0U, &X86::VR128RegClass);
18519 return std::make_pair(0U, &X86::VR256RegClass);
18525 // Use the default implementation in TargetLowering to convert the register
18526 // constraint into a member of a register class.
18527 std::pair<unsigned, const TargetRegisterClass*> Res;
18528 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18530 // Not found as a standard register?
18531 if (Res.second == 0) {
18532 // Map st(0) -> st(7) -> ST0
18533 if (Constraint.size() == 7 && Constraint[0] == '{' &&
18534 tolower(Constraint[1]) == 's' &&
18535 tolower(Constraint[2]) == 't' &&
18536 Constraint[3] == '(' &&
18537 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18538 Constraint[5] == ')' &&
18539 Constraint[6] == '}') {
18541 Res.first = X86::ST0+Constraint[4]-'0';
18542 Res.second = &X86::RFP80RegClass;
18546 // GCC allows "st(0)" to be called just plain "st".
18547 if (StringRef("{st}").equals_lower(Constraint)) {
18548 Res.first = X86::ST0;
18549 Res.second = &X86::RFP80RegClass;
18554 if (StringRef("{flags}").equals_lower(Constraint)) {
18555 Res.first = X86::EFLAGS;
18556 Res.second = &X86::CCRRegClass;
18560 // 'A' means EAX + EDX.
18561 if (Constraint == "A") {
18562 Res.first = X86::EAX;
18563 Res.second = &X86::GR32_ADRegClass;
18569 // Otherwise, check to see if this is a register class of the wrong value
18570 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18571 // turn into {ax},{dx}.
18572 if (Res.second->hasType(VT))
18573 return Res; // Correct type already, nothing to do.
18575 // All of the single-register GCC register classes map their values onto
18576 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
18577 // really want an 8-bit or 32-bit register, map to the appropriate register
18578 // class and return the appropriate register.
18579 if (Res.second == &X86::GR16RegClass) {
18580 if (VT == MVT::i8 || VT == MVT::i1) {
18581 unsigned DestReg = 0;
18582 switch (Res.first) {
18584 case X86::AX: DestReg = X86::AL; break;
18585 case X86::DX: DestReg = X86::DL; break;
18586 case X86::CX: DestReg = X86::CL; break;
18587 case X86::BX: DestReg = X86::BL; break;
18590 Res.first = DestReg;
18591 Res.second = &X86::GR8RegClass;
18593 } else if (VT == MVT::i32 || VT == MVT::f32) {
18594 unsigned DestReg = 0;
18595 switch (Res.first) {
18597 case X86::AX: DestReg = X86::EAX; break;
18598 case X86::DX: DestReg = X86::EDX; break;
18599 case X86::CX: DestReg = X86::ECX; break;
18600 case X86::BX: DestReg = X86::EBX; break;
18601 case X86::SI: DestReg = X86::ESI; break;
18602 case X86::DI: DestReg = X86::EDI; break;
18603 case X86::BP: DestReg = X86::EBP; break;
18604 case X86::SP: DestReg = X86::ESP; break;
18607 Res.first = DestReg;
18608 Res.second = &X86::GR32RegClass;
18610 } else if (VT == MVT::i64 || VT == MVT::f64) {
18611 unsigned DestReg = 0;
18612 switch (Res.first) {
18614 case X86::AX: DestReg = X86::RAX; break;
18615 case X86::DX: DestReg = X86::RDX; break;
18616 case X86::CX: DestReg = X86::RCX; break;
18617 case X86::BX: DestReg = X86::RBX; break;
18618 case X86::SI: DestReg = X86::RSI; break;
18619 case X86::DI: DestReg = X86::RDI; break;
18620 case X86::BP: DestReg = X86::RBP; break;
18621 case X86::SP: DestReg = X86::RSP; break;
18624 Res.first = DestReg;
18625 Res.second = &X86::GR64RegClass;
18628 } else if (Res.second == &X86::FR32RegClass ||
18629 Res.second == &X86::FR64RegClass ||
18630 Res.second == &X86::VR128RegClass) {
18631 // Handle references to XMM physical registers that got mapped into the
18632 // wrong class. This can happen with constraints like {xmm0} where the
18633 // target independent register mapper will just pick the first match it can
18634 // find, ignoring the required type.
18636 if (VT == MVT::f32 || VT == MVT::i32)
18637 Res.second = &X86::FR32RegClass;
18638 else if (VT == MVT::f64 || VT == MVT::i64)
18639 Res.second = &X86::FR64RegClass;
18640 else if (X86::VR128RegClass.hasType(VT))
18641 Res.second = &X86::VR128RegClass;
18642 else if (X86::VR256RegClass.hasType(VT))
18643 Res.second = &X86::VR256RegClass;